getAttributes() throws FileSystemException;
/**
* Lists the attributes of the file's content.
*
* @return The names of the attributes. Never returns null;
* @throws FileSystemException If the file does not exist, or does not support attributes.
*/
String[] getAttributeNames() throws FileSystemException;
/**
* Gets the value of an attribute of the file's content.
*
* @param attrName The name of the attribute. Attribute names are case insensitive.
* @return The value of the attribute, or null if the attribute value is
* unknown.
* @throws FileSystemException If the file does not exist, or does not support attributes.
*/
Object getAttribute(String attrName) throws FileSystemException;
/**
* Sets the value of an attribute of the file's content. Creates the
* file if it does not exist.
*
* @param attrName The name of the attribute.
* @param value The value of the attribute.
* @throws FileSystemException If the file does not exist, or is read-only, or does not support
* attributes, or on error setting the attribute.
*/
void setAttribute(String attrName, Object value)
throws FileSystemException;
/**
* Removes the value of an attribute of the file's content.
*
* @param attrName The name of the attribute.
* @throws FileSystemException If the file does not exist, or is read-only, or does not support
* attributes, or on error removing the attribute.
*/
void removeAttribute(String attrName)
throws FileSystemException;
/**
* Retrieves the certificates if any used to sign this file or folder.
*
* @return The certificates, or an empty array if there are no certificates or
* the file does not support signing.
* @throws FileSystemException If the file does not exist, or is being written.
*/
Certificate[] getCertificates() throws FileSystemException;
/**
* Returns an input stream for reading the file's content.
*
* There may only be a single input or output stream open for the
* file at any time.
*
* @return An input stream to read the file's content from. The input
* stream is buffered, so there is no need to wrap it in a
* BufferedInputStream
.
* @throws FileSystemException If the file does not exist, or is being read, or is being written,
* or on error opening the stream.
*/
InputStream getInputStream() throws FileSystemException;
/**
* Returns an output stream for writing the file's content.
*
* If the file does not exist, this method creates it, and the parent
* folder, if necessary. If the file does exist, it is replaced with
* whatever is written to the output stream.
*
* There may only be a single input or output stream open for the
* file at any time.
*
* @return An output stream to write the file's content to. The stream is
* buffered, so there is no need to wrap it in a
* BufferedOutputStream
.
* @throws FileSystemException If the file is read-only, or is being read, or is being written,
* or on error opening the stream.
*/
OutputStream getOutputStream() throws FileSystemException;
/**
* Returns an stream for reading/writing the file's content.
*
* If the file does not exist, and you use one of the write* methods,
* this method creates it, and the parent folder, if necessary.
* If the file does exist, parts of the file are replaced with whatever is written
* at a given position.
*
* There may only be a single input or output stream open for the
* file at any time.
*
* @param mode The mode to use to access the file.
* @return the stream for reading and writing the file's content.
* @throws FileSystemException If the file is read-only, or is being read, or is being written,
* or on error opening the stream.
*/
RandomAccessContent getRandomAccessContent(final RandomAccessMode mode) throws FileSystemException;
/**
* Returns an output stream for writing the file's content.
*
* If the file does not exist, this method creates it, and the parent
* folder, if necessary. If the file does exist, it is replaced with
* whatever is written to the output stream.
*
* There may only be a single input or output stream open for the
* file at any time.
*
* @param bAppend true if you would like to append to the file
* @return An output stream to write the file's content to. The stream is
* buffered, so there is no need to wrap it in a
* BufferedOutputStream
.
* @throws FileSystemException If the file is read-only, or is being read, or is being written,
* or on error opening the stream.
*/
OutputStream getOutputStream(boolean bAppend) throws FileSystemException;
/**
* Closes all resources used by the content, including any open stream.
* Commits pending changes to the file.
*
* This method is a hint to the implementation that it can release
* resources. This object can continue to be used after calling this
* method.
* @throws FileSystemException if an error occurs closing the file.
*/
void close() throws FileSystemException;
/**
* get the content info. e.g. type, encoding, ...
* @return the FileContentInfo
* @throws FileSystemException if an error occurs.
*/
FileContentInfo getContentInfo() throws FileSystemException;
/**
* check if this file has open streams.
* @return true if the file is open, false otherwise.
*/
boolean isOpen();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileContentInfo.java 100644 765 24 2323 11623215066 27151 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Interface to the content info.
*
* @author Commons VFS team
*/
public interface FileContentInfo
{
/**
* the content type.
* @return The file content type.
*/
String getContentType();
/**
* the content encoding.
* @return The file content encoding.
*/
String getContentEncoding();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileContentInfoFactory.java 100644 765 24 2170 11623215066 30501 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Create a class which is able to determine the content-info for the given content.
*
* @author Commons VFS team
*/
public interface FileContentInfoFactory
{
FileContentInfo create(FileContent fileContent) throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileDepthSelector.java 100644 765 24 4041 11623215066 27467 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* A {@link FileSelector} that selects all files in a particular depth range.
*
* @author Commons VFS team
*/
public class FileDepthSelector
implements FileSelector
{
/**
* The minimum depth
*/
private final int minDepth;
/**
* The maximum depth
*/
private final int maxDepth;
public FileDepthSelector(int minDepth, int maxDepth)
{
this.minDepth = minDepth;
this.maxDepth = maxDepth;
}
/**
* Determines if a file or folder should be selected.
* @param fileInfo The file selection information
* @return true if the file or folder should be included, false otherwise.
*/
public boolean includeFile(final FileSelectInfo fileInfo)
{
final int depth = fileInfo.getDepth();
return minDepth <= depth && depth <= maxDepth;
}
/**
* Determines whether a folder should be traversed.
* @param fileInfo The file selection information
* @return true if the file or folder should be traversed, false otherwise.
*/
public boolean traverseDescendents(final FileSelectInfo fileInfo)
{
return fileInfo.getDepth() < maxDepth;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileFilter.java 100644 765 24 2417 11623215066 26154 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* This interface is used to select files when traversing the direct children of the base.
*
* @author Commons VFS team
*/
public interface FileFilter
{
/**
* Determines if a file or folder should be selected.
*
* @param fileInfo the file or folder to select.
* @return true if the file should be selected.
*/
boolean accept(final FileSelectInfo fileInfo);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileFilterSelector.java 100644 765 24 4505 11623215066 27655 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import org.apache.commons.vfs2.util.Messages;
/**
* A {@link org.apache.commons.vfs2.FileSelector} that selects all children of the given fileObject.
* This is to mimic the {@link java.io.FileFilter} interface
*
* @author Commons VFS team
*/
public class FileFilterSelector extends FileDepthSelector
{
/**
* The FileFilter.
*/
private final FileFilter fileFilter;
public FileFilterSelector()
{
this(null);
}
public FileFilterSelector(FileFilter fileFilter)
{
super(1, 1);
this.fileFilter = fileFilter;
}
/**
* Determines if a file or folder should be selected.
* @param fileInfo The file selection information.
* @return true if the file or folder should be included, false otherwise.
*/
@Override
public boolean includeFile(final FileSelectInfo fileInfo)
{
if (!super.includeFile(fileInfo))
{
return false;
}
return accept(fileInfo);
}
/**
* Determines whether the file should be selected.
* @param fileInfo The file selection information.
* @return true if the file should be selected, false otherwise.
*/
public boolean accept(final FileSelectInfo fileInfo)
{
if (fileFilter != null)
{
return fileFilter.accept(fileInfo);
}
throw new IllegalArgumentException(Messages.getString("vfs.selectors/filefilter.missing.error"));
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileListener.java 100644 765 24 3241 11623215066 26510 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Listens for changes to a file.
*
* @author Commons VFS team
*/
public interface FileListener
{
/**
* Called when a file is created.
* @param event The FileChangeEvent.
* @throws Exception if an error occurs.
*/
void fileCreated(FileChangeEvent event) throws Exception;
/**
* Called when a file is deleted.
* @param event The FileChangeEvent.
* @throws Exception if an error occurs.
*/
void fileDeleted(FileChangeEvent event) throws Exception;
/**
* Called when a file is changed.
* This will only happen if you monitor the file using {@link FileMonitor}.
* @param event The FileChangeEvent.
* @throws Exception if an error occurs.
*/
void fileChanged(FileChangeEvent event) throws Exception;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileMonitor.java 100644 765 24 2414 11623215066 26353 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* FileMonitor interface.
*
* @author Commons VFS team
*/
public interface FileMonitor
{
/**
* Adds a file to be monitored.
* @param file The FileObject to monitor.
*/
void addFile(final FileObject file);
/**
* Removes a file from being monitored.
* @param file The FileObject to stop monitoring.
*/
void removeFile(final FileObject file);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileName.java 100644 765 24 15634 11623215066 25634 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Represents a file name. File names are immutable, and work correctly as
* keys in hash tables.
*
* @author Commons VFS team
* @see FileObject
*/
public interface FileName extends Comparable
{
/**
* The separator character used in file paths.
*/
char SEPARATOR_CHAR = '/';
/**
* The separator used in file paths.
*/
String SEPARATOR = "/";
/**
* The absolute path of the root of a file system.
*/
String ROOT_PATH = "/";
/**
* Returns the base name of this file. The base name is the last element
* of the file name. For example the base name of
* /somefolder/somefile
is somefile
.
*
* The root file of a file system has an empty base name.
*
* @return The base name. Never returns null.
*/
String getBaseName();
/**
* Returns the absolute path of this file, within its file system. This
* path is normalised, so that .
and ..
elements
* have been removed. Also, the path only contains /
as its
* separator character. The path always starts with /
*
* The root of a file system has /
as its absolute path.
*
* @return The path. Never returns null.
*/
String getPath();
/**
* Returns the absolute path of this file, within its file system. This
* path is normalised, so that .
and ..
elements
* have been removed. Also, the path only contains /
as its
* separator character. The path always starts with /
*
* The root of a file system has /
as its absolute path.
*
* In contrast to {@link #getPath()} the path is decoded i.e. all %nn stuff
* replaced by its character.
*
* @return The path. Never returns null.
* @throws FileSystemException if the path is not correctly encoded
*/
String getPathDecoded() throws FileSystemException;
/**
* Returns the extension of this file name.
*
* @return The extension. Returns an empty string if the name has no
* extension.
*/
String getExtension();
/**
* Returns the depth of this file name, within its file system. The depth
* of the root of a file system is 0. The depth of any other file is
* 1 + the depth of its parent.
* @return The depth of this file name.
*/
int getDepth();
/**
* Returns the URI scheme of this file.
* @return The URI scheme of this file.
*/
String getScheme();
/**
* Returns the absolute URI of this file.
* @return the absolute URI of this file.
*/
String getURI();
/**
* Returns the root URI of the file system this file belongs to.
* @return the root URI.
*/
String getRootURI();
/**
* find the root of the filesystem.
* @return the file system root.
*/
FileName getRoot();
/**
* Returns the file name of the parent of this file. The root of a
* file system has no parent.
*
* @return A {@link FileName} object representing the parent name. Returns
* null for the root of a file system.
*/
FileName getParent();
/**
* Resolves a name, relative to this file name. Equivalent to calling
* resolveName( path, NameScope.FILE_SYSTEM )
.
*
* @param name The name to resolve.
* @return A {@link FileName} object representing the resolved file name.
* @throws FileSystemException If the name is invalid.
*/
// FileName resolveName(String name) throws FileSystemException;
/**
* Resolves a name, relative to this file name. Refer to {@link NameScope}
* for a description of how names are resolved.
*
* @param name The name to resolve.
* @param scope The scope to use when resolving the name.
* @return A {@link FileName} object representing the resolved file name.
* @throws FileSystemException If the name is invalid.
*/
// FileName resolveName(String name, NameScope scope)
// throws FileSystemException;
/**
* Converts a file name to a relative name, relative to this file name.
*
* @param name The name to convert to a relative path.
* @return The relative name.
* @throws FileSystemException On error.
*/
String getRelativeName(FileName name) throws FileSystemException;
/**
* Determines if another file name is an ancestor of this file name.
* @param ancestor The FileName to check.
* @return true if another file name is an ancestor of this file name.
*/
boolean isAncestor(FileName ancestor);
/**
* Determines if another file name is a descendent of this file name.
* @param descendent the FileName to check.
* @return true if the other FileName is a descendent of this file name.
*/
boolean isDescendent(FileName descendent);
/**
* Determines if another file name is a descendent of this file name.
* @param descendent the FileName to check.
* @param nameScope the NameScope of the FileName.
* @return true if the other FileName is a descendent of this file name.
*/
boolean isDescendent(FileName descendent, NameScope nameScope);
/**
* Returns the requested or current type of this name.
*
* The "requested" type is the one determined during resolving the name.
* In this case the name is a {@link FileType#FOLDER} if it ends with an "/" else
* it will be a {@link FileType#FILE}
*
*
* Once attached it will be changed to reflect the real type of this resource.
*
*
* @return {@link FileType#FOLDER} or {@link FileType#FILE}
*/
FileType getType();
/**
* returns a "friendly path", this is a path without a password.
* This path can not be used to resolve the path again
* @return the friendly URI as a String.
*/
String getFriendlyURI();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileNotFolderException.java 100644 765 24 3066 11623215066 30503 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Delivers a file-not-folder exception which happens when trying to issue {@link FileObject#getChildren()} on a file.
* @author Commons VFS team
* @since 2.0
*/
public class FileNotFolderException extends FileSystemException
{
/**
* serialVersionUID format is YYYYMMDD for the date of the last binary change.
*/
private static final long serialVersionUID = 20101208L;
public FileNotFolderException(final Object info0)
{
super("vfs.provider/list-children-not-folder.error", info0);
}
public FileNotFolderException(Object info0, Throwable throwable)
{
super("vfs.provider/list-children-not-folder.error", info0, throwable);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileNotFoundException.java 100644 765 24 2716 11623215066 30344 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* delivers a file-not-found exception.
* @author Commons VFS team
* @since 2.0
*/
public class FileNotFoundException extends FileSystemException
{
/**
* serialVersionUID format is YYYYMMDD for the date of the last binary change.
*/
private static final long serialVersionUID = 20101208L;
public FileNotFoundException(final Object info0)
{
super("vfs.provider/read-not-file.error", info0);
}
public FileNotFoundException(Object info0, Throwable throwable)
{
super("vfs.provider/read-not-file.error", info0, throwable);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileObject.java 100644 765 24 31711 11623215066 26154 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.net.URL;
import java.util.List;
import org.apache.commons.vfs2.operations.FileOperations;
/**
* Represents a file, and is used to access the content and
* structure of the file.
*
* Files are arranged in a hierarchy. Each hierachy forms a
* file system . A file system represents things like a local OS
* file system, a windows share, an HTTP server, or the contents of a Zip file.
*
* There are two types of files: Folders , which contain other files,
* and normal files , which contain data, or content . A folder may
* not have any content, and a normal file cannot contain other files.
*
* File Naming
*
* TODO - write this.
*
* Reading and Writing a File
*
* Reading and writing a file, and all other operations on the file's
* content , is done using the {@link FileContent} object returned
* by {@link #getContent}.
*
* Creating and Deleting a File
*
* A file is created using either {@link #createFolder}, {@link #createFile},
* or by writing to the file using one of the {@link FileContent} methods.
*
* A file is deleted using {@link #delete}. Recursive deletion can be
* done using {@link #delete(FileSelector)}.
*
* Finding Files
*
* Other files in the same file system as this file can be found
* using:
*
* {@link #resolveFile} to find another file relative to this file.
* {@link #getChildren} and {@link #getChild} to find the children of this file.
* {@link #getParent} to find the folder containing this file.
* {@link #getFileSystem} to find another file in the same file system.
*
*
* To find files in another file system, use a {@link FileSystemManager}.
*
* @author Commons VFS team
* @see FileSystemManager
* @see FileContent
* @see FileName
*/
public interface FileObject
{
/**
* Returns the name of this file.
* @return the FileName.
*/
FileName getName();
/**
* Returns a URL representing this file.
* @return the URL for the file.
* @throws FileSystemException if an error occurs.
*/
URL getURL() throws FileSystemException;
/**
* Determines if this file exists.
*
* @return true
if this file exists, false
if not.
* @throws FileSystemException On error determining if this file exists.
*/
boolean exists() throws FileSystemException;
/**
* Determines if this file is hidden.
*
* @return true
if this file is hidden, false
if not.
* @throws FileSystemException On error determining if this file exists.
*/
boolean isHidden() throws FileSystemException;
/**
* Determines if this file can be read.
*
* @return true
if this file is readable, false
if not.
* @throws FileSystemException On error determining if this file exists.
*/
boolean isReadable() throws FileSystemException;
/**
* Determines if this file can be written to.
*
* @return true
if this file is writeable, false
if not.
* @throws FileSystemException On error determining if this file exists.
*/
boolean isWriteable() throws FileSystemException;
/**
* Returns this file's type.
*
* @return One of the {@link FileType} constants. Never returns null.
* @throws FileSystemException On error determining the file's type.
*/
FileType getType() throws FileSystemException;
/**
* Returns the folder that contains this file.
*
* @return The folder that contains this file. Returns null if this file is
* the root of a file system.
* @throws FileSystemException On error finding the file's parent.
*/
FileObject getParent() throws FileSystemException;
/**
* Returns the file system that contains this file.
*
* @return The file system.
*/
FileSystem getFileSystem();
/**
* Lists the children of this file.
*
* @return An array containing the children of this file. The array is
* unordered. If the file does not have any children, a zero-length
* array is returned. This method never returns null.
* @throws FileSystemException If this file does not exist, or is not a folder, or on error
* listing this file's children.
*/
FileObject[] getChildren() throws FileSystemException;
/**
* Returns a child of this file. Note that this method returns null
* when the child does not exist. This differs from
* {@link #resolveFile( String, NameScope)} which never returns null.
*
* @param name The name of the child.
* @return The child, or null if there is no such child.
* @throws FileSystemException If this file does not exist, or is not a folder, or on error
* determining this file's children.
*/
FileObject getChild(String name) throws FileSystemException;
/**
* Finds a file, relative to this file. Refer to {@link NameScope}
* for a description of how names are resolved in the different scopes.
*
* @param name The name to resolve.
* @param scope the NameScope for the file.
* @return The file.
* @throws FileSystemException On error parsing the path, or on error finding the file.
*/
FileObject resolveFile(String name, NameScope scope)
throws FileSystemException;
/**
* Finds a file, relative to this file. Equivalent to calling
* resolveFile( path, NameScope.FILE_SYSTEM )
.
*
* @param path The path of the file to locate. Can either be a relative
* path or an absolute path.
* @return The file.
* @throws FileSystemException On error parsing the path, or on error finding the file.
*/
FileObject resolveFile(String path) throws FileSystemException;
/**
* Finds the set of matching descendents of this file, in depthwise order.
*
* @param selector The selector to use to select matching files.
* @return The matching files. The files are returned in depthwise order
* (that is, a child appears in the list before its parent).
* @throws FileSystemException if an error occurs.
*/
FileObject[] findFiles(FileSelector selector) throws FileSystemException;
/**
* Finds the set of matching descendents of this file.
*
* @param selector the selector used to determine if the file should be selected
* @param depthwise controls the ordering in the list. e.g. deepest first
* @param selected container for selected files. list needs not to be empty.
* @throws FileSystemException if an error occurs.
*/
void findFiles(FileSelector selector, boolean depthwise, List selected) throws FileSystemException;
/**
* Deletes this file. Does nothing if this file does not exist of if it is a
* folder that has children. Does not delete any descendents of this file,
* use {@link #delete(FileSelector)} for that.
*
* @return true if this object has been deleted
* @throws FileSystemException If this file is a non-empty folder, or if this file is read-only,
* or on error deleteing this file.
*/
boolean delete() throws FileSystemException;
/**
* Deletes all descendents of this file that match a selector. Does
* nothing if this file does not exist.
*
* This method is not transactional. If it fails and throws an
* exception, this file will potentially only be partially deleted.
*
* @param selector The selector to use to select which files to delete.
* @return the number of deleted objects
* @throws FileSystemException If this file or one of its descendents is read-only, or on error
* deleting this file or one of its descendents.
*/
int delete(FileSelector selector) throws FileSystemException;
/**
* Creates this folder, if it does not exist. Also creates any ancestor
* folders which do not exist. This method does nothing if the folder
* already exists.
*
* @throws FileSystemException If the folder already exists with the wrong type, or the parent
* folder is read-only, or on error creating this folder or one of
* its ancestors.
*/
void createFolder() throws FileSystemException;
/**
* Creates this file, if it does not exist. Also creates any ancestor
* folders which do not exist. This method does nothing if the file
* already exists and is a file.
*
* @throws FileSystemException If the file already exists with the wrong type, or the parent
* folder is read-only, or on error creating this file or one of
* its ancestors.
*/
void createFile() throws FileSystemException;
/**
* Copies another file, and all its descendents, to this file.
*
* If this file does not exist, it is created. Its parent folder is also
* created, if necessary. If this file does exist, it is deleted first.
*
* This method is not transactional. If it fails and throws an
* exception, this file will potentially only be partially copied.
*
* @param srcFile The source file to copy.
* @param selector The selector to use to select which files to copy.
* @throws FileSystemException If this file is read-only, or if the source file does not exist,
* or on error copying the file.
*/
void copyFrom(FileObject srcFile, FileSelector selector)
throws FileSystemException;
/**
* Move this file.
*
If the destFile exists, it is deleted first
*
* @param destFile the New filename.
* @throws FileSystemException If this file is read-only, or if the source file does not exist,
* or on error copying the file.
*/
void moveTo(FileObject destFile)
throws FileSystemException;
/**
* Queries the file if it is possible to rename it to newfile.
*
* @param newfile the new file(-name)
* @return true it this is the case
*/
boolean canRenameTo(FileObject newfile);
/**
* Returns this file's content. The {@link FileContent} returned by this
* method can be used to read and write the content of the file.
*
* This method can be called if the file does not exist, and
* the returned {@link FileContent} can be used to create the file
* by writing its content.
*
* @return This file's content.
* @throws FileSystemException On error getting this file's content.
*/
FileContent getContent() throws FileSystemException;
/**
* Closes this file, and its content. This method is a hint to the
* implementation that it can release any resources associated with
* the file.
*
* The file object can continue to be used after this method is called.
*
* @throws FileSystemException On error closing the file.
* @see FileContent#close
*/
void close() throws FileSystemException;
/**
* This will prepare the fileObject to get resynchronized with the underlaying filesystem if required.
* @throws FileSystemException if an error occurs.
*/
void refresh() throws FileSystemException;
/**
* check if the fileObject is attaced.
* @return true if the FileObject is attached.
*/
boolean isAttached();
/**
* check if someone reads/write to this file.
* @return true if the file content is open.
*/
boolean isContentOpen();
// --- OPERATIONS --
/**
* @return FileOperations interface that provides access to the operations API.
* @throws FileSystemException if an error occurs.
*/
FileOperations getFileOperations() throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FilesCache.java 100644 765 24 4426 11623215066 26117 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* The fileCache interface. Implementations of this interface are expected to be thread safe.
*
* @author Commons VFS team
*/
public interface FilesCache
{
/**
* add a fileobject to the cache.
*
* @param file the file
*/
void putFile(final FileObject file);
/**
* add a fileobject to the cache if it isn't already present.
*
* @param file the file
* @return true if the file was stored, false otherwise.
*/
boolean putFileIfAbsent(final FileObject file);
/**
* retrieve a file from the cache by its name.
*
* @param filesystem The FileSystem.
* @param name the name
* @return the fileobject or null if file is not cached
*/
FileObject getFile(final FileSystem filesystem, final FileName name);
/**
* purge the entries corresponding to the filesystem.
* @param filesystem The FileSystem.
*/
void clear(final FileSystem filesystem);
/**
* purge the whole cache.
*/
void close();
/**
* removes a file from cache.
*
* @param filesystem filesystem
* @param name filename
*/
void removeFile(final FileSystem filesystem, final FileName name);
/**
* if the cache uses timestamps it could use this method to handle
* updates of them.
*
* @param file filename
*/
// public void touchFile(final FileObject file);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileSelectInfo.java 100644 765 24 3103 11623215066 26753 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Information about a file, that is used to select files during the
* traversal of a hierarchy.
*
* @author Commons VFS team
* @todo Rename this interface, as it is used by both FileSelector and FileVisitor.
*/
public interface FileSelectInfo
{
/**
* Returns the base folder of the traversal.
* @return FileObject representing the base folder.
*/
FileObject getBaseFolder();
/**
* Returns the file (or folder) to be considered.
* @return The FileObject.
*/
FileObject getFile();
/**
* Returns the depth of the file relative to the base folder.
* @return The depth of the file relative to the base folder.
*/
int getDepth();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileSelector.java 100644 765 24 4076 11623215066 26512 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* This interface is used to select files when traversing a file hierarchy.
*
* @author Commons VFS team
* @see Selectors
*/
public interface FileSelector
{
/**
* Determines if a file or folder should be selected. This method is
* called in depthwise order (that is, it is called for the children
* of a folder before it is called for the folder itself).
*
* @param fileInfo the file or folder to select.
* @return true if the file should be selected.
* @throws Exception if an error occurs.
*/
boolean includeFile(FileSelectInfo fileInfo)
throws Exception;
/**
* Determines whether a folder should be traversed. If this method returns
* true, {@link #includeFile} is called for each of the children of
* the folder, and each of the child folders is recursively traversed.
*
* This method is called on a folder before {@link #includeFile}
* is called.
*
* @param fileInfo the file or folder to select.
* @return true if the folder should be traversed.
* @throws Exception if an error occurs.
*/
boolean traverseDescendents(FileSelectInfo fileInfo)
throws Exception;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileSystem.java 100644 765 24 15631 11623215066 26235 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.io.File;
/**
* A file system, made up of a hierarchy of files.
*
* @author Commons VFS team
*/
public interface FileSystem
{
/**
* Returns the root file of this file system.
* @return The root FileObject.
* @throws FileSystemException if an error occurs.
*/
FileObject getRoot() throws FileSystemException;
/**
* Returns the name of the root file of this file system. The root name always
* contains a path String of "/".
* @return the root FileName.
*/
FileName getRootName();
/**
* The root URI passed as a file system option or obtained from the rootName.
* @return The root URI.
*/
String getRootURI();
/**
* Determines if this file system has a particular capability.
*
* @param capability The capability to check for.
* @return true if this filesystem has the requested capability.
* Note that not all files in the file system may have the
* capability.
* @todo Move this to another interface, so that set of capabilities can be queried.
*/
boolean hasCapability(Capability capability);
/**
* Returns the parent layer if this is a layered file system.
*
* @return The parent layer, or null if this is not a layered file system.
* @throws FileSystemException if an error occurs.
*/
FileObject getParentLayer() throws FileSystemException;
/**
* Gets the value of an attribute of the file system.
*
* TODO - change to Map getAttributes()
instead?
*
* TODO - define the standard attribute names, and define which attrs
* are guaranteed to be present.
*
* @param attrName The name of the attribute.
* @return The value of the attribute.
* @throws org.apache.commons.vfs2.FileSystemException
* If the file does not exist, or is being written, or if the
* attribute is unknown.
* @see org.apache.commons.vfs2.FileContent#getAttribute
*/
Object getAttribute(String attrName) throws FileSystemException;
/**
* Sets the value of an attribute of the file's content. Creates the
* file if it does not exist.
*
* @param attrName The name of the attribute.
* @param value The value of the attribute.
* @throws FileSystemException If the file is read-only, or is being read, or if the attribute
* is not supported, or on error setting the attribute.
* @see FileContent#setAttribute
*/
void setAttribute(String attrName, Object value)
throws FileSystemException;
/**
* Finds a file in this file system.
*
* @param name The name of the file.
* @return The file. Never returns null.
* @throws FileSystemException if an error occurs.
*/
FileObject resolveFile(FileName name) throws FileSystemException;
/**
* Finds a file in this file system.
*
* @param name The name of the file. This must be an absolute path.
* @return The file. Never returns null.
* @throws FileSystemException if an error occurs.
*/
FileObject resolveFile(String name) throws FileSystemException;
/**
* Adds a listener on a file in this file system.
*
* @param file The file to attach the listener to.
* @param listener The listener to add.
*/
void addListener(FileObject file, FileListener listener);
/**
* Removes a listener from a file in this file system.
*
* @param file The file to remove the listener from.
* @param listener The listener to remove.
*/
void removeListener(FileObject file, FileListener listener);
/**
* Adds a junction to this file system. A junction is a link that attaches
* the supplied file to a point in this file system, making it look like
* part of the file system.
*
* @param junctionPoint The point in this file system to add the junction.
* @param targetFile The file to link to.
* @throws FileSystemException If this file system does not support junctions, or the junction
* point or target file is invalid (the file system may not support
* nested junctions, for example).
*/
void addJunction(String junctionPoint, FileObject targetFile)
throws FileSystemException;
/**
* Removes a junction from this file system.
*
* @param junctionPoint The junction to remove.
* @throws FileSystemException On error removing the junction.
*/
void removeJunction(String junctionPoint) throws FileSystemException;
/**
* Creates a temporary local copy of a file and its descendents. If
* this file is already a local file, a copy is not made.
*
* Note that the local copy may include additonal files, that were
* not selected by the given selector.
*
* @param file The file to replicate.
* @param selector The selector to use to select the files to replicate.
* @return The local copy of this file.
* @throws FileSystemException If this file does not exist, or on error replicating the file.
* @todo Add options to indicate whether the caller is happy to deal with
* extra files being present locally (eg if the file has been
* replicated previously), or whether the caller expects only
* the selected files to be present.
*/
File replicateFile(FileObject file, FileSelector selector)
throws FileSystemException;
/**
* Returns the FileSystemOptions used to instantiate this filesystem.
* @return The FileSystemOptions.
*/
FileSystemOptions getFileSystemOptions();
/**
* Returns a reference to the FileSytemManager.
* @return The FileSystemManager.
*/
FileSystemManager getFileSystemManager();
/**
* Returns the accuracy of the last modification time.
*
* @return ms 0 perfectly accurate, >0 might be off by this value e.g. sftp 1000ms.
*/
double getLastModTimeAccuracy();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileSystemConfigBuilder.java 100644 765 24 23174 11623215066 30673 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Abstract class which has the right to fill FileSystemOptions.
*
* @author Commons VFS team
*/
public abstract class FileSystemConfigBuilder
{
/** Default prefix to use when resolving system properties */
private static final String PREFIX = "vfs.";
/** The root uri of the file system */
private static final String ROOTURI = "rootURI";
/** The prefix to use when resolving system properties */
private final String prefix;
protected FileSystemConfigBuilder()
{
this.prefix = PREFIX;
}
/** @since 2.0 */
protected FileSystemConfigBuilder(String component)
{
this.prefix = PREFIX + component;
}
/**
* The root URI of the file system.
* @param opts The FileSystem options
* @param rootURI The creator name to be associated with the file.
* @since 2.0
*/
public void setRootURI(FileSystemOptions opts, String rootURI)
{
setParam(opts, ROOTURI, rootURI);
}
/**
* Return the root URI of the file system.
* @param opts The FileSystem options
* @return The root URI.
* @since 2.0
*/
public String getRootURI(FileSystemOptions opts)
{
return getString(opts, ROOTURI);
}
protected void setParam(FileSystemOptions opts, String name, Object value)
{
opts.setOption(getConfigClass(), name, value);
}
protected Object getParam(FileSystemOptions opts, String name)
{
if (opts == null)
{
return null;
}
return opts.getOption(getConfigClass(), name);
}
protected boolean hasParam(FileSystemOptions opts, String name)
{
return opts != null && opts.hasOption(getConfigClass(), name);
}
/** @since 2.0 */
protected boolean hasObject(FileSystemOptions opts, String name)
{
return hasParam(opts, name) || System.getProperties().containsKey(PREFIX + name);
}
/** @since 2.0 */
protected Boolean getBoolean(FileSystemOptions opts, String name)
{
return getBoolean(opts, name, null);
}
/** @since 2.0 */
protected boolean getBoolean(FileSystemOptions opts, String name, boolean defaultValue)
{
return getBoolean(opts, name, new Boolean(defaultValue)).booleanValue();
}
/** @since 2.0 */
protected Boolean getBoolean(FileSystemOptions opts, String name, Boolean defaultValue)
{
Boolean value = (Boolean) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(PREFIX + name);
if (str == null)
{
return defaultValue;
}
value = Boolean.valueOf(str);
}
return value;
}
/** @since 2.0 */
protected Byte getByte(FileSystemOptions opts, String name)
{
return getByte(opts, name, null);
}
/** @since 2.0 */
protected byte getByte(FileSystemOptions opts, String name, byte defaultValue)
{
return getByte(opts, name, new Byte(defaultValue)).byteValue();
}
/** @since 2.0 */
protected Byte getByte(FileSystemOptions opts, String name, Byte defaultValue)
{
Byte value = (Byte) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(this.prefix + name);
if (str == null)
{
return defaultValue;
}
value = Byte.valueOf(str);
}
return value;
}
/** @since 2.0 */
protected Character getCharacter(FileSystemOptions opts, String name)
{
return getCharacter(opts, name, null);
}
/** @since 2.0 */
protected char getCharacter(FileSystemOptions opts, String name, char defaultValue)
{
return getCharacter(opts, name, new Character(defaultValue)).charValue();
}
/** @since 2.0 */
protected Character getCharacter(FileSystemOptions opts, String name, Character defaultValue)
{
Character value = (Character) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(this.prefix + name);
if (str == null || str.length() <= 0)
{
return defaultValue;
}
value = new Character(str.charAt(0));
}
return value;
}
/** @since 2.0 */
protected Double getDouble(FileSystemOptions opts, String name)
{
return getDouble(opts, name, null);
}
/** @since 2.0 */
protected double getDouble(FileSystemOptions opts, String name, double defaultValue)
{
return getDouble(opts, name, new Double(defaultValue)).doubleValue();
}
/** @since 2.0 */
protected Double getDouble(FileSystemOptions opts, String name, Double defaultValue)
{
Double value = (Double) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(this.prefix + name);
if (str == null || str.length() <= 0)
{
return defaultValue;
}
value = Double.valueOf(str);
}
return value;
}
/** @since 2.0 */
protected Float getFloat(FileSystemOptions opts, String name)
{
return getFloat(opts, name, null);
}
/** @since 2.0 */
protected float getFloat(FileSystemOptions opts, String name, float defaultValue)
{
return getFloat(opts, name, new Float(defaultValue)).floatValue();
}
/** @since 2.0 */
protected Float getFloat(FileSystemOptions opts, String name, Float defaultValue)
{
Float value = (Float) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(this.prefix + name);
if (str == null || str.length() <= 0)
{
return defaultValue;
}
value = Float.valueOf(str);
}
return value;
}
/** @since 2.0 */
protected Integer getInteger(FileSystemOptions opts, String name)
{
return getInteger(opts, name, null);
}
/** @since 2.0 */
protected int getInteger(FileSystemOptions opts, String name, int defaultValue)
{
return getInteger(opts, name, new Integer(defaultValue)).intValue();
}
/** @since 2.0 */
protected Integer getInteger(FileSystemOptions opts, String name, Integer defaultValue)
{
Integer value = (Integer) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(this.prefix + name);
if (str == null)
{
return defaultValue;
}
value = Integer.valueOf(str);
}
return value;
}
/** @since 2.0 */
protected Long getLong(FileSystemOptions opts, String name)
{
return getLong(opts, name, null);
}
/** @since 2.0 */
protected long getLong(FileSystemOptions opts, String name, long defaultValue)
{
return getLong(opts, name, new Long(defaultValue)).longValue();
}
/** @since 2.0 */
protected Long getLong(FileSystemOptions opts, String name, Long defaultValue)
{
Long value = (Long) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(this.prefix + name);
if (str == null)
{
return defaultValue;
}
value = Long.valueOf(str);
}
return value;
}
/** @since 2.0 */
protected Short getShort(FileSystemOptions opts, String name)
{
return getShort(opts, name, null);
}
/** @since 2.0 */
protected short getShort(FileSystemOptions opts, String name, short defaultValue)
{
return getShort(opts, name, new Short(defaultValue)).shortValue();
}
/** @since 2.0 */
protected Short getShort(FileSystemOptions opts, String name, Short defaultValue)
{
Short value = (Short) getParam(opts, name);
if (value == null)
{
String str = System.getProperty(this.prefix + name);
if (str == null)
{
return defaultValue;
}
value = Short.valueOf(str);
}
return value;
}
/** @since 2.0 */
protected String getString(FileSystemOptions opts, String name)
{
return getString(opts, name, null);
}
/** @since 2.0 */
protected String getString(FileSystemOptions opts, String name, String defaultValue)
{
String value = (String) getParam(opts, name);
if (value == null)
{
value = System.getProperty(this.prefix + name);
if (value == null)
{
return defaultValue;
}
}
return value;
}
protected abstract Class extends FileSystem> getConfigClass();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileSystemException.java 100644 765 24 13071 11623215066 30110 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.io.IOException;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.commons.vfs2.util.Messages;
/**
* Thrown for file system errors.
*
* @author Commons VFS team
*/
public class FileSystemException
extends IOException
{
/**
* serialVersionUID format is YYYYMMDD for the date of the last binary change.
*/
private static final long serialVersionUID = 20101208L;
/** URL pattern */
private static final Pattern URL_PATTERN = Pattern.compile("[a-z]+://.*");
/** Password pattern */
private static final Pattern PASSWORD_PATTERN = Pattern.compile(":(?:[^/]+)@");
/**
* The Throwable that caused this exception to be thrown.
*/
private final Throwable throwable;
/**
* The message code.
*/
private final String code;
/**
* array of complementary info (context).
*/
private final String[] info;
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
*/
public FileSystemException(final String code)
{
this(code, null, null);
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info0 one context information.
*/
public FileSystemException(final String code, final Object info0)
{
this(code, new Object[]{info0}, null);
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info0 one context information.
* @param throwable the cause.
*/
public FileSystemException(final String code,
final Object info0,
final Throwable throwable)
{
this(code, new Object[]{info0}, throwable);
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info array of complementary info (context).
*/
public FileSystemException(final String code, final Object[] info)
{
this(code, info, null);
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param throwable the original cause
*/
public FileSystemException(final String code, final Throwable throwable)
{
this(code, null, throwable);
}
/**
* Constructs exception with the specified detail message.
*
* @param code the error code of the message.
* @param info array of complementary info (context).
* @param throwable the cause.
*/
public FileSystemException(final String code,
final Object[] info,
final Throwable throwable)
{
super(code);
if (info == null)
{
this.info = new String[0];
}
else
{
this.info = new String[info.length];
for (int i = 0; i < info.length; i++)
{
String value = String.valueOf(info[i]);
// mask passwords (VFS-169)
final Matcher urlMatcher = URL_PATTERN.matcher(value);
if (urlMatcher.find())
{
final Matcher pwdMatcher = PASSWORD_PATTERN.matcher(value);
value = pwdMatcher.replaceFirst(":***@");
}
this.info[i] = value;
}
}
this.code = code;
this.throwable = throwable;
}
/**
* Constructs wrapper exception.
*
* @param throwable the root cause to wrap.
*/
public FileSystemException(final Throwable throwable)
{
this(throwable.getMessage(), null, throwable);
}
/**
* retrieve message from bundle.
* @return The exception message.
*/
@Override
public String getMessage()
{
return Messages.getString(super.getMessage(), getInfo());
}
/**
* Retrieve root cause of the exception.
*
* @return the root cause
*/
@Override
public final Throwable getCause()
{
return throwable;
}
/**
* Retrieve error code of the exception.
* Could be used as key for internationalization.
*
* @return the code.
*/
public String getCode()
{
return code;
}
/**
* Retrieve array of complementary info (context).
* Could be used as parameter for internationalization.
*
* @return the context info.
*/
public String[] getInfo()
{
return info;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileSystemManager.java 100644 765 24 31556 11623215066 27534 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URLStreamHandlerFactory;
import java.util.Collection;
import org.apache.commons.logging.Log;
import org.apache.commons.vfs2.operations.FileOperationProvider;
/**
* A FileSystemManager manages a set of file systems. This interface is
* used to locate a {@link FileObject} by name from one of those file systems.
*
* To locate a {@link FileObject}, use one of the resolveFile()
* methods.
*
*
*
* A file system manager can recognise several types of file names:
*
*
*
* Absolute URI. These must start with a scheme, such as
* file:
or ftp:
, followed by a scheme dependent
* file name. Some examples:
*
* file:/c:/somefile
* ftp://somewhere.org/somefile
*
*
* Absolute local file name. For example,
* /home/someuser/a-file
or c:\dir\somefile.html
.
* Elements in the name can be separated using any of the following
* characters: /
, \
, or the native file separator
* character. For example, the following file names are the same:
*
* c:\somedir\somefile.xml
* c:/somedir/somefile.xml
*
*
* Relative path. For example: ../somefile
or
* somedir/file.txt
. The file system manager resolves relative
* paths against its base file . Elements in the relative path can be
* separated using /
, \
, or file system specific
* separator characters. Relative paths may also contain ..
and
* .
elements. See {@link FileObject#resolveFile} for more
* details.
*
*
*
* @author Commons VFS team
*/
public interface FileSystemManager
{
/**
* Returns the base file used to resolve relative paths.
* @return The base FileObject.
* @throws FileSystemException if an error occurs.
*/
FileObject getBaseFile() throws FileSystemException;
/**
* Locates a file by name. Equivalent to calling
* resolveFile(uri, getBaseName())
.
*
* @param name The name of the file.
* @return The file. Never returns null.
* @throws FileSystemException On error parsing the file name.
*/
FileObject resolveFile(String name) throws FileSystemException;
/**
* Locates a file by name. Equivalent to calling
* resolveFile(uri, getBaseName())
.
*
* @param name The name of the file.
* @param fileSystemOptions The FileSystemOptions used for FileSystem creation
* @return The file. Never returns null.
* @throws FileSystemException On error parsing the file name.
*/
FileObject resolveFile(String name, FileSystemOptions fileSystemOptions)
throws FileSystemException;
/** §
* Locates a file by name. The name is resolved as described
* above . That is, the name can be either
* an absolute URI, an absolute file name, or a relative path to
* be resolved against baseFile
.
*
* Note that the file does not have to exist when this method is called.
*
* @param name The name of the file.
* @param baseFile The base file to use to resolve relative paths.
* May be null.
* @return The file. Never returns null.
* @throws FileSystemException On error parsing the file name.
*/
FileObject resolveFile(FileObject baseFile, String name) throws FileSystemException;
/**
* Locates a file by name. See {@link #resolveFile(FileObject, String)}
* for details.
*
* @param baseFile The base file to use to resolve relative paths.
* May be null.
* @param name The name of the file.
* @return The file. Never returns null.
* @throws FileSystemException On error parsing the file name.
*/
FileObject resolveFile(File baseFile, String name) throws FileSystemException;
/**
* Resolves a name, relative to this file name. Equivalent to calling
* resolveName( path, NameScope.FILE_SYSTEM )
.
*
* @param root the base filename
* @param name The name to resolve.
* @return A {@link FileName} object representing the resolved file name.
* @throws FileSystemException If the name is invalid.
*/
FileName resolveName(final FileName root, final String name) throws FileSystemException;
/**
* Resolves a name, relative to the "root" file name. Refer to {@link NameScope}
* for a description of how names are resolved.
*
* @param root the base filename
* @param name The name to resolve.
* @param scope The {@link NameScope} to use when resolving the name.
* @return A {@link FileName} object representing the resolved file name.
* @throws FileSystemException If the name is invalid.
*/
FileName resolveName(final FileName root, String name, NameScope scope)
throws FileSystemException;
/**
* Converts a local file into a {@link FileObject}.
*
* @param file The file to convert.
* @return The {@link FileObject} that represents the local file. Never
* returns null.
* @throws FileSystemException On error converting the file.
*/
FileObject toFileObject(File file) throws FileSystemException;
/**
* Creates a layered file system. A layered file system is a file system
* that is created from the contents of a file, such as a zip or tar file.
*
* @param provider The name of the file system provider to use. This name
* is the same as the scheme used in URI to identify the provider.
* @param file The file to use to create the file system.
* @return The root file of the new file system.
* @throws FileSystemException On error creating the file system.
*/
FileObject createFileSystem(String provider, FileObject file)
throws FileSystemException;
/**
* Closes the given filesystem.
* If you use VFS as singleton it is VERY dangerous to call this method.
* @param filesystem The FileSystem to close.
*/
void closeFileSystem(FileSystem filesystem);
/**
* Creates a layered file system. A layered file system is a file system
* that is created from the contents of a file, such as a zip or tar file.
*
* @param file The file to use to create the file system.
* @return The root file of the new file system.
* @throws FileSystemException On error creating the file system.
*/
FileObject createFileSystem(FileObject file) throws FileSystemException;
/**
* Creates an empty virtual file system. Can be populated by adding
* junctions to it.
*
* @param rootUri The root URI to use for the new file system. Can be null.
* @return The root file of the new file system.
* @throws FileSystemException if an error occurs creating the VirtualFileSystem.
*/
FileObject createVirtualFileSystem(String rootUri) throws FileSystemException;
/**
* Creates a virtual file system. The file system will contain a junction
* at the fs root to the supplied root file.
*
* @param rootFile The root file to backs the file system.
* @return The root of the new file system.
* @throws FileSystemException if an error occurs creating the VirtualFileSystem.
*/
FileObject createVirtualFileSystem(FileObject rootFile) throws FileSystemException;
/**
* Returns a streamhandler factory to enable URL lookup using this
* FileSystemManager.
* @return the URLStreamHandlerFactory.
*/
URLStreamHandlerFactory getURLStreamHandlerFactory();
/**
* Determines if a layered file system can be created for a given file.
*
* @param file The file to check for.
* @return true if the FileSystem can be created.
* @throws FileSystemException if an error occurs.
*/
boolean canCreateFileSystem(FileObject file) throws FileSystemException;
/**
* Get the cache used to cache fileobjects.
* @return The FilesCache.
*/
FilesCache getFilesCache();
/**
* Get the cache strategy used.
* @return the CacheStrategy.
*/
CacheStrategy getCacheStrategy();
/**
* Get the file object decorator used.
* @return the file object decorator Class.
*/
Class> getFileObjectDecorator();
/**
* The constructor associated to the fileObjectDecorator.
* We cache it here for performance reasons.
* @return the Constructor associated with the FileObjectDecorator.
*/
Constructor> getFileObjectDecoratorConst();
/**
* The class to use to determine the content-type (mime-type).
* @return the FileContentInfoFactory.
*/
FileContentInfoFactory getFileContentInfoFactory();
/**
* Returns true if this manager has a provider for a particular scheme.
* @param scheme The scheme for which a provider should be checked.
* @return true if a provider for the scheme is available.
*/
boolean hasProvider(final String scheme);
/**
* Get the schemes currently available.
* @return An array of available scheme names that are supported.
*/
String[] getSchemes();
/**
* Get the capabilities for a given scheme.
*
* @param scheme The scheme to use to locate the provider's capabilities.
* @return A Collection of the various capabilities.
* @throws FileSystemException if the given scheme is not konwn.
*/
Collection getProviderCapabilities(final String scheme) throws FileSystemException;
/**
* Sets the logger to use.
* @param log The logger to use.
*/
void setLogger(final Log log);
/**
* Get the configuration builder for the given scheme.
*
* @param scheme The schem to use to obtain the FileSystemConfigBuidler.
* @return A FileSystemConfigBuilder appropriate for the given scheme.
* @throws FileSystemException if the given scheme is not konwn.
*/
FileSystemConfigBuilder getFileSystemConfigBuilder(final String scheme) throws FileSystemException;
/**
* Resolve the uri to a filename.
*
* @param uri The uri to resolve.
* @return A FileName that matches the uri.
* @throws FileSystemException if this is not possible.
*/
FileName resolveURI(String uri) throws FileSystemException;
// -- OPERATIONS --
/**
* Adds the specified FileOperationProvider for the specified scheme.
* Several FileOperationProvider's might be registered for the same scheme.
* For example, for "file" scheme we can register SvnWsOperationProvider and
* CvsOperationProvider.
*
* @param scheme The scheme assoicated with this provider.
* @param operationProvider The FileOperationProvider to add.
* @throws FileSystemException if an error occurs.
*/
void addOperationProvider(final String scheme, final FileOperationProvider operationProvider)
throws FileSystemException;
/**
* @see FileSystemManager#addOperationProvider(String, org.apache.commons.vfs2.operations.FileOperationProvider)
*
* @param schemes The schemes that will be associated with the provider.
* @param operationProvider The FileOperationProvider to add.
* @throws FileSystemException if an error occurs.
*/
void addOperationProvider(final String[] schemes, final FileOperationProvider operationProvider)
throws FileSystemException;
/**
* @param scheme the scheme for wich we want to get the list af registered providers.
*
* @return the registered FileOperationProviders for the specified scheme.
* If there were no providers registered for the scheme, it returns null.
*
* @throws FileSystemException if an error occurs.
*/
FileOperationProvider[] getOperationProviders(final String scheme) throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileSystemOptions.java 100644 765 24 12072 11623215066 27605 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.util.Map;
import java.util.TreeMap;
/**
* Container for FileSystemOptions.
* You have to use *FileSystemConfigBuilder.getInstance() to fill this container
* * = the filesystem provider short name
*
* @author Commons VFS team
* @see org.apache.commons.vfs2.provider.sftp.SftpFileSystemConfigBuilder
* @see org.apache.commons.vfs2.provider.ftp.FtpFileSystemConfigBuilder
*/
public final class FileSystemOptions implements Cloneable
{
/** The options */
private Map options = new TreeMap();
/**
* Keys in the options Map.
*/
private static final class FileSystemOptionKey implements Comparable
{
/** Constant used to create hashcode */
private static final int HASH = 29;
/** The FileSystem class */
private final Class extends FileSystem> fileSystemClass;
/** The option name */
private final String name;
// TODO: the parameter name suggests that the class should only be a
// a FileSystem, however some of the tests pass in DefaultFileSystemConfigBuilder
private FileSystemOptionKey(Class extends FileSystem> fileSystemClass, String name)
{
this.fileSystemClass = fileSystemClass;
this.name = name;
}
public int compareTo(FileSystemOptionKey o)
{
int ret = fileSystemClass.getName().compareTo(o.fileSystemClass.getName());
if (ret != 0)
{
return ret;
}
return name.compareTo(o.name);
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
final FileSystemOptionKey that = (FileSystemOptionKey) o;
if (!fileSystemClass.equals(that.fileSystemClass))
{
return false;
}
if (!name.equals(that.name))
{
return false;
}
return true;
}
@Override
public int hashCode()
{
int result;
result = fileSystemClass.hashCode();
result = HASH * result + name.hashCode();
return result;
}
}
public FileSystemOptions()
{
}
void setOption(Class extends FileSystem> fileSystemClass, String name, Object value)
{
options.put(new FileSystemOptionKey(fileSystemClass, name), value);
}
Object getOption(Class extends FileSystem> fileSystemClass, String name)
{
FileSystemOptionKey key = new FileSystemOptionKey(fileSystemClass, name);
return options.get(key);
}
boolean hasOption(Class extends FileSystem> fileSystemClass, String name)
{
FileSystemOptionKey key = new FileSystemOptionKey(fileSystemClass, name);
return options.containsKey(key);
}
public int compareTo(FileSystemOptions other)
{
if (this == other)
{
// the same instance
return 0;
}
int propsSz = options == null ? 0 : options.size();
int propsFkSz = other.options == null ? 0 : other.options.size();
if (propsSz < propsFkSz)
{
return -1;
}
if (propsSz > propsFkSz)
{
return 1;
}
if (propsSz == 0)
{
// props empty
return 0;
}
int hash = options.hashCode();
int hashFk = other.options.hashCode();
if (hash < hashFk)
{
return -1;
}
if (hash > hashFk)
{
return 1;
}
// bad props not the same instance, but looks like the same
// TODO: compare Entry by Entry
return 0;
}
/**
* {@inheritDoc}
* @since 2.0
*/
@Override
public Object clone()
{
FileSystemOptions clone = new FileSystemOptions();
clone.options = new TreeMap(options);
return clone;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileType.java 100644 765 24 6305 11623215066 25650 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* An enumerated type that represents a file's type.
*
* @author Commons VFS team
*/
public enum FileType
{
/**
* A folder. May contain other files, and have attributes, but does not
* have any data content.
*/
FOLDER("folder", true, false, true),
/**
* A regular file. May have data content and attributes, but cannot
* contain other files.
*/
FILE("file", false, true, true),
/**
* A file or folder. May have data content and attributes, and can
* contain other files.
*/
FILE_OR_FOLDER("fileOrFolder", true, true, true),
/**
* A file that does not exist. May not have data content, attributes,
* or contain other files.
*/
IMAGINARY("imaginary", false, false, false);
/** The name of the FileType */
private final String name;
/** true if the FileType can have children */
private final boolean hasChildren;
/** true if the FileType can have content */
private final boolean hasContent;
/** true if the FileType has attributes */
private final boolean hasAttrs;
private FileType(final String name,
final boolean hasChildren,
final boolean hasContent,
final boolean hasAttrs)
{
this.name = name;
this.hasChildren = hasChildren;
this.hasContent = hasContent;
this.hasAttrs = hasAttrs;
}
/**
* Returns the name of this type.
* @return The name of this type.
*/
@Override
public String toString()
{
return name;
}
/**
* Returns the name of this type.
* @return The name of the type.
*/
public String getName()
{
return name;
}
/**
* Returns true if files of this type may contain other files.
* @return tru if files can contain other files.
*/
public boolean hasChildren()
{
return hasChildren;
}
/**
* Returns true if files of this type may have data content.
* @return true if files can have content.
*/
public boolean hasContent()
{
return hasContent;
}
/**
* Returns true if files of this type may have attributes.
* @return true if files can have attributes
*/
public boolean hasAttributes()
{
return hasAttrs;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileTypeHasNoContentException.java 100644 765 24 3120 11623215066 32003 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* delivers a file-not-folder exception which happens when trying to issue
* {@link org.apache.commons.vfs2.FileObject#getChildren()} on a file.
* @author Commons VFS team
* @since 2.0
*/
public class FileTypeHasNoContentException extends FileSystemException
{
/**
* serialVersionUID format is YYYYMMDD for the date of the last binary change.
*/
private static final long serialVersionUID = 20101208L;
public FileTypeHasNoContentException(final Object info0)
{
super("vfs.provider/read-not-file.error", info0);
}
public FileTypeHasNoContentException(Object info0, Throwable throwable)
{
super("vfs.provider/read-not-file.error", info0, throwable);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileTypeSelector.java 100644 765 24 3567 11623215066 27360 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* A {@link FileSelector} that selects files of a particular type.
*
* @author Commons VFS team
*/
public class FileTypeSelector
implements FileSelector
{
/** The FileType */
private final FileType type;
public FileTypeSelector(final FileType type)
{
this.type = type;
}
/**
* Determines if a file or folder should be selected.
* @param fileInfo The file selection information.
* @return true if the file or folder should be selected.
* @throws FileSystemException if an error occurs
*/
public boolean includeFile(final FileSelectInfo fileInfo)
throws FileSystemException
{
return fileInfo.getFile().getType() == type;
}
/**
* Determines whether a folder should be traversed.
* @param fileInfo The file selection information.
* @return true if the file or folder should be traversed.
*/
public boolean traverseDescendents(final FileSelectInfo fileInfo)
{
return true;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/FileUtil.java 100644 765 24 7055 11623215066 25647 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* Utility methods for dealng with FileObjects.
*
* @author Commons VFS team
*/
public final class FileUtil
{
/** The buffer size */
private static final int BUFFER_SIZE = 1024;
private FileUtil()
{
}
/**
* Returns the content of a file, as a byte array.
*
* @param file The file to get the content of.
* @return The content as a byte array.
* @throws IOException if the file content cannot be accessed.
*/
public static byte[] getContent(final FileObject file)
throws IOException
{
final FileContent content = file.getContent();
final int size = (int) content.getSize();
final byte[] buf = new byte[size];
final InputStream in = content.getInputStream();
try
{
int read = 0;
for (int pos = 0; pos < size && read >= 0; pos += read)
{
read = in.read(buf, pos, size - pos);
}
}
finally
{
in.close();
}
return buf;
}
/**
* Writes the content of a file to an OutputStream.
* @param file The FileObject to write.
* @param outstr The OutputStream to write to.
* @throws IOException if an error occurs writing the file.
*/
public static void writeContent(final FileObject file,
final OutputStream outstr)
throws IOException
{
final InputStream instr = file.getContent().getInputStream();
try
{
final byte[] buffer = new byte[BUFFER_SIZE];
while (true)
{
final int nread = instr.read(buffer);
if (nread < 0)
{
break;
}
outstr.write(buffer, 0, nread);
}
}
finally
{
instr.close();
}
}
/**
* Copies the content from a source file to a destination file.
* @param srcFile The source FileObject.
* @param destFile The target FileObject
* @throws IOException If an error occurs copying the file.
*/
public static void copyContent(final FileObject srcFile,
final FileObject destFile)
throws IOException
{
// Create the output stream via getContent(), to pick up the
// validation it does
final OutputStream outstr = destFile.getContent().getOutputStream();
try
{
writeContent(srcFile, outstr);
}
finally
{
outstr.close();
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DecoratedFileObject.java 100644 765 24 12440 11623215065 30725 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.net.URL;
import java.util.List;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.operations.FileOperations;
/**
* Base class to build a fileObject decoration.
*
* @author Commons VFS team
*/
public class DecoratedFileObject implements FileObject
{
private final FileObject decoratedFileObject;
public DecoratedFileObject(FileObject decoratedFileObject)
{
super();
this.decoratedFileObject = decoratedFileObject;
}
public boolean canRenameTo(FileObject newfile)
{
return decoratedFileObject.canRenameTo(newfile);
}
public void close() throws FileSystemException
{
decoratedFileObject.close();
}
public void copyFrom(FileObject srcFile, FileSelector selector) throws FileSystemException
{
decoratedFileObject.copyFrom(srcFile, selector);
}
public void createFile() throws FileSystemException
{
decoratedFileObject.createFile();
}
public void createFolder() throws FileSystemException
{
decoratedFileObject.createFolder();
}
public boolean delete() throws FileSystemException
{
return decoratedFileObject.delete();
}
public int delete(FileSelector selector) throws FileSystemException
{
return decoratedFileObject.delete(selector);
}
public boolean exists() throws FileSystemException
{
return decoratedFileObject.exists();
}
public void findFiles(FileSelector selector, boolean depthwise, List selected)
throws FileSystemException
{
decoratedFileObject.findFiles(selector, depthwise, selected);
}
public FileObject[] findFiles(FileSelector selector) throws FileSystemException
{
return decoratedFileObject.findFiles(selector);
}
public FileObject getChild(String name) throws FileSystemException
{
return decoratedFileObject.getChild(name);
}
public FileObject[] getChildren() throws FileSystemException
{
return decoratedFileObject.getChildren();
}
public FileContent getContent() throws FileSystemException
{
return decoratedFileObject.getContent();
}
public FileSystem getFileSystem()
{
return decoratedFileObject.getFileSystem();
}
public FileName getName()
{
return decoratedFileObject.getName();
}
public FileObject getParent() throws FileSystemException
{
return decoratedFileObject.getParent();
}
public FileType getType() throws FileSystemException
{
return decoratedFileObject.getType();
}
public URL getURL() throws FileSystemException
{
return decoratedFileObject.getURL();
}
public boolean isHidden() throws FileSystemException
{
return decoratedFileObject.isHidden();
}
public boolean isReadable() throws FileSystemException
{
return decoratedFileObject.isReadable();
}
public boolean isWriteable() throws FileSystemException
{
return decoratedFileObject.isWriteable();
}
public void moveTo(FileObject destFile) throws FileSystemException
{
decoratedFileObject.moveTo(destFile);
}
public FileObject resolveFile(String name, NameScope scope) throws FileSystemException
{
return decoratedFileObject.resolveFile(name, scope);
}
public FileObject resolveFile(String path) throws FileSystemException
{
return decoratedFileObject.resolveFile(path);
}
public void refresh() throws FileSystemException
{
decoratedFileObject.refresh();
}
public FileObject getDecoratedFileObject()
{
return decoratedFileObject;
}
public boolean isAttached()
{
return decoratedFileObject.isAttached();
}
public boolean isContentOpen()
{
return decoratedFileObject.isContentOpen();
}
@Override
public String toString()
{
return decoratedFileObject.toString();
}
public FileOperations getFileOperations() throws FileSystemException
{
return decoratedFileObject.getFileOperations();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileContentInfo.java 100644 765 24 2765 11623215065 31430 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import org.apache.commons.vfs2.FileContentInfo;
/**
* The default file content information.
* @author Commons VFS team
*/
public class DefaultFileContentInfo implements FileContentInfo
{
private final String contentType;
private final String contentEncoding;
public DefaultFileContentInfo(final String contentType, final String contentEncoding)
{
this.contentType = contentType;
this.contentEncoding = contentEncoding;
}
public String getContentType()
{
return contentType;
}
public String getContentEncoding()
{
return contentEncoding;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileMonitor.java 100644 765 24 51422 11623215065 30643 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileMonitor;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
/**
* A polling {@link FileMonitor} implementation.
*
* The DefaultFileMonitor is a Thread based polling file system monitor with a 1
* second delay.
*
* Design:
*
* There is a Map of monitors known as FileMonitorAgents. With the thread running,
* each FileMonitorAgent object is asked to "check" on the file it is
* responsible for.
* To do this check, the cache is cleared.
*
*
* If the file existed before the refresh and it no longer exists, a delete
* event is fired.
* If the file existed before the refresh and it still exists, check the
* last modified timestamp to see if that has changed.
* If it has, fire a change event.
*
*
* With each file delete, the FileMonitorAgent of the parent is asked to
* re-build its
* list of children, so that they can be accurately checked when there are new
* children.
* New files are detected during each "check" as each file does a check for new
* children.
* If new children are found, create events are fired recursively if recursive
* descent is
* enabled.
*
*
* For performance reasons, added a delay that increases as the number of files
* monitored
* increases. The default is a delay of 1 second for every 1000 files processed.
*
* Example usage:
* FileSystemManager fsManager = VFS.getManager();
* FileObject listendir = fsManager.resolveFile("/home/username/monitored/");
*
* DefaultFileMonitor fm = new DefaultFileMonitor(new CustomFileListener());
* fm.setRecursive(true);
* fm.addFile(listendir);
* fm.start();
*
* (where CustomFileListener is a class that implements the FileListener
* interface.)
*
* @author Commons VFS team
*/
public class DefaultFileMonitor implements Runnable, FileMonitor
{
private static final Log LOG = LogFactory.getLog(DefaultFileMonitor.class);
private static final long DEFAULT_DELAY = 1000;
private static final int DEFAULT_MAX_FILES = 1000;
/**
* Map from FileName to FileObject being monitored.
*/
private final Map monitorMap = new HashMap();
/**
* The low priority thread used for checking the files being monitored.
*/
private Thread monitorThread;
/**
* File objects to be removed from the monitor map.
*/
private final Stack deleteStack = new Stack();
/**
* File objects to be added to the monitor map.
*/
private final Stack addStack = new Stack();
/**
* A flag used to determine if the monitor thread should be running.
*/
private volatile boolean shouldRun = true; // used for inter-thread communication
/**
* A flag used to determine if adding files to be monitored should be recursive.
*/
private boolean recursive;
/**
* Set the delay between checks
*/
private long delay = DEFAULT_DELAY;
/**
* Set the number of files to check until a delay will be inserted
*/
private int checksPerRun = DEFAULT_MAX_FILES;
/**
* A listener object that if set, is notified on file creation and deletion.
*/
private final FileListener listener;
public DefaultFileMonitor(final FileListener listener)
{
this.listener = listener;
}
/**
* Access method to get the recursive setting when adding files for monitoring.
* @return true if monitoring is enabled for children.
*/
public boolean isRecursive()
{
return this.recursive;
}
/**
* Access method to set the recursive setting when adding files for monitoring.
* @param newRecursive true if monitoring should be enabled for children.
*/
public void setRecursive(final boolean newRecursive)
{
this.recursive = newRecursive;
}
/**
* Access method to get the current FileListener object notified when there
* are changes with the files added.
* @return The FileListener.
*/
FileListener getFileListener()
{
return this.listener;
}
/**
* Adds a file to be monitored.
* @param file The FileObject to monitor.
*/
public void addFile(final FileObject file)
{
doAddFile(file);
try
{
// add all direct children too
if (file.getType().hasChildren())
{
// Traverse the children
final FileObject[] children = file.getChildren();
for (int i = 0; i < children.length; i++)
{
doAddFile(children[i]);
}
}
}
catch (FileSystemException fse)
{
LOG.error(fse.getLocalizedMessage(), fse);
}
}
/**
* Adds a file to be monitored.
* @param file The FileObject to add.
*/
private void doAddFile(final FileObject file)
{
synchronized (this.monitorMap)
{
if (this.monitorMap.get(file.getName()) == null)
{
this.monitorMap.put(file.getName(), new FileMonitorAgent(this,
file));
try
{
if (this.listener != null)
{
file.getFileSystem().addListener(file, this.listener);
}
if (file.getType().hasChildren() && this.recursive)
{
// Traverse the children
final FileObject[] children = file.getChildren();
for (int i = 0; i < children.length; i++)
{
this.addFile(children[i]); // Add depth first
}
}
}
catch (FileSystemException fse)
{
LOG.error(fse.getLocalizedMessage(), fse);
}
}
}
}
/**
* Removes a file from being monitored.
* @param file The FileObject to remove from monitoring.
*/
public void removeFile(final FileObject file)
{
synchronized (this.monitorMap)
{
FileName fn = file.getName();
if (this.monitorMap.get(fn) != null)
{
FileObject parent;
try
{
parent = file.getParent();
}
catch (FileSystemException fse)
{
parent = null;
}
this.monitorMap.remove(fn);
if (parent != null)
{ // Not the root
FileMonitorAgent parentAgent =
this.monitorMap.get(parent.getName());
if (parentAgent != null)
{
parentAgent.resetChildrenList();
}
}
}
}
}
/**
* Queues a file for removal from being monitored.
* @param file The FileObject to be removed from being monitored.
*/
protected void queueRemoveFile(final FileObject file)
{
this.deleteStack.push(file);
}
/**
* Get the delay between runs.
* @return The delay period.
*/
public long getDelay()
{
return delay;
}
/**
* Set the delay between runs.
* @param delay The delay period.
*/
public void setDelay(long delay)
{
if (delay > 0)
{
this.delay = delay;
}
else
{
this.delay = DEFAULT_DELAY;
}
}
/**
* get the number of files to check per run.
* @return The number of files to check per iteration.
*/
public int getChecksPerRun()
{
return checksPerRun;
}
/**
* set the number of files to check per run.
* a additional delay will be added if there are more files to check
*
* @param checksPerRun a value less than 1 will disable this feature
*/
public void setChecksPerRun(int checksPerRun)
{
this.checksPerRun = checksPerRun;
}
/**
* Queues a file for addition to be monitored.
* @param file The FileObject to add.
*/
protected void queueAddFile(final FileObject file)
{
this.addStack.push(file);
}
/**
* Starts monitoring the files that have been added.
*/
public void start()
{
if (this.monitorThread == null)
{
this.monitorThread = new Thread(this);
this.monitorThread.setDaemon(true);
this.monitorThread.setPriority(Thread.MIN_PRIORITY);
}
this.monitorThread.start();
}
/**
* Stops monitoring the files that have been added.
*/
public void stop()
{
this.shouldRun = false;
}
/**
* Asks the agent for each file being monitored to check its file for changes.
*/
public void run()
{
mainloop:
while (!monitorThread.isInterrupted() && this.shouldRun)
{
while (!this.deleteStack.empty())
{
this.removeFile(this.deleteStack.pop());
}
// For each entry in the map
Object[] fileNames;
synchronized (this.monitorMap)
{
fileNames = this.monitorMap.keySet().toArray();
}
for (int iterFileNames = 0; iterFileNames < fileNames.length;
iterFileNames++)
{
FileName fileName = (FileName) fileNames[iterFileNames];
FileMonitorAgent agent;
synchronized (this.monitorMap)
{
agent = this.monitorMap.get(fileName);
}
if (agent != null)
{
agent.check();
}
if (getChecksPerRun() > 0)
{
if ((iterFileNames % getChecksPerRun()) == 0)
{
try
{
Thread.sleep(getDelay());
}
catch (InterruptedException e)
{
// Woke up.
}
}
}
if (monitorThread.isInterrupted() || !this.shouldRun)
{
continue mainloop;
}
}
while (!this.addStack.empty())
{
this.addFile(this.addStack.pop());
}
try
{
Thread.sleep(getDelay());
}
catch (InterruptedException e)
{
continue;
}
}
this.shouldRun = true;
}
/**
* File monitor agent.
*/
private static final class FileMonitorAgent
{
private final FileObject file;
private final DefaultFileMonitor fm;
private boolean exists;
private long timestamp;
private Map children;
private FileMonitorAgent(DefaultFileMonitor fm, FileObject file)
{
this.fm = fm;
this.file = file;
this.refresh();
this.resetChildrenList();
try
{
this.exists = this.file.exists();
}
catch (FileSystemException fse)
{
this.exists = false;
this.timestamp = -1;
}
if (this.exists)
{
try
{
this.timestamp = this.file.getContent().getLastModifiedTime();
}
catch (FileSystemException fse)
{
this.timestamp = -1;
}
}
}
private void resetChildrenList()
{
try
{
if (this.file.getType().hasChildren())
{
this.children = new HashMap();
FileObject[] childrenList = this.file.getChildren();
for (int i = 0; i < childrenList.length; i++)
{
this.children.put(childrenList[i].getName(), new
Object()); // null?
}
}
}
catch (FileSystemException fse)
{
this.children = null;
}
}
/**
* Clear the cache and re-request the file object
*/
private void refresh()
{
try
{
this.file.refresh();
}
catch (FileSystemException fse)
{
LOG.error(fse.getLocalizedMessage(), fse);
}
}
/**
* Recursively fires create events for all children if recursive descent is
* enabled. Otherwise the create event is only fired for the initial
* FileObject.
* @param child The child to add.
*/
private void fireAllCreate(FileObject child)
{
// Add listener so that it can be triggered
if (this.fm.getFileListener() != null)
{
child.getFileSystem().addListener(child, this.fm.getFileListener());
}
((AbstractFileSystem) child.getFileSystem()).fireFileCreated(child);
// Remove it because a listener is added in the queueAddFile
if (this.fm.getFileListener() != null)
{
child.getFileSystem().removeListener(child,
this.fm.getFileListener());
}
this.fm.queueAddFile(child); // Add
try
{
if (this.fm.isRecursive())
{
if (child.getType().hasChildren())
{
FileObject[] newChildren = child.getChildren();
for (int i = 0; i < newChildren.length; i++)
{
fireAllCreate(newChildren[i]);
}
}
}
}
catch (FileSystemException fse)
{
LOG.error(fse.getLocalizedMessage(), fse);
}
}
/**
* Only checks for new children. If children are removed, they'll
* eventually be checked.
*/
private void checkForNewChildren()
{
try
{
if (this.file.getType().hasChildren())
{
FileObject[] newChildren = this.file.getChildren();
if (this.children != null)
{
// See which new children are not listed in the current children map.
Map newChildrenMap = new HashMap();
Stack missingChildren = new Stack();
for (int i = 0; i < newChildren.length; i++)
{
newChildrenMap.put(newChildren[i].getName(), new
Object()); // null ?
// If the child's not there
if
(!this.children.containsKey(newChildren[i].getName()))
{
missingChildren.push(newChildren[i]);
}
}
this.children = newChildrenMap;
// If there were missing children
if (!missingChildren.empty())
{
while (!missingChildren.empty())
{
FileObject child = missingChildren.pop();
this.fireAllCreate(child);
}
}
}
else
{
// First set of children - Break out the cigars
if (newChildren.length > 0)
{
this.children = new HashMap();
}
for (int i = 0; i < newChildren.length; i++)
{
this.children.put(newChildren[i].getName(), new
Object()); // null?
this.fireAllCreate(newChildren[i]);
}
}
}
}
catch (FileSystemException fse)
{
LOG.error(fse.getLocalizedMessage(), fse);
}
}
private void check()
{
this.refresh();
try
{
// If the file existed and now doesn't
if (this.exists && !this.file.exists())
{
this.exists = this.file.exists();
this.timestamp = -1;
// Fire delete event
((AbstractFileSystem)
this.file.getFileSystem()).fireFileDeleted(this.file);
// Remove listener in case file is re-created. Don't want to fire twice.
if (this.fm.getFileListener() != null)
{
this.file.getFileSystem().removeListener(this.file,
this.fm.getFileListener());
}
// Remove from map
this.fm.queueRemoveFile(this.file);
}
else if (this.exists && this.file.exists())
{
// Check the timestamp to see if it has been modified
if (this.timestamp != this.file.getContent().getLastModifiedTime())
{
this.timestamp = this.file.getContent().getLastModifiedTime();
// Fire change event
// Don't fire if it's a folder because new file children
// and deleted files in a folder have their own event triggered.
if (!this.file.getType().hasChildren())
{
((AbstractFileSystem)
this.file.getFileSystem()).fireFileChanged(this.file);
}
}
}
else if (!this.exists && this.file.exists())
{
this.exists = this.file.exists();
this.timestamp = this.file.getContent().getLastModifiedTime();
// Don't fire if it's a folder because new file children
// and deleted files in a folder have their own event triggered.
if (!this.file.getType().hasChildren())
{
((AbstractFileSystem)
this.file.getFileSystem()).fireFileCreated(this.file);
}
}
this.checkForNewChildren();
}
catch (FileSystemException fse)
{
LOG.error(fse.getLocalizedMessage(), fse);
}
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileReplicator.java 100644 765 24 17042 11623215065 31320 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.File;
import java.util.ArrayList;
import java.util.Random;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VfsLog;
import org.apache.commons.vfs2.provider.AbstractVfsComponent;
import org.apache.commons.vfs2.provider.FileReplicator;
import org.apache.commons.vfs2.provider.TemporaryFileStore;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.util.Messages;
/**
* A simple file replicator and temporary file store.
*
* @author Commons VFS team
*/
public class DefaultFileReplicator
extends AbstractVfsComponent
implements FileReplicator, TemporaryFileStore
{
private static final char[] TMP_RESERVED_CHARS = new char[]
{
'?', '/', '\\', ' ', '&', '"', '\'', '*', '#', ';', ':', '<', '>', '|'
};
private static final Log log = LogFactory.getLog(DefaultFileReplicator.class);
private static final int MASK = 0xffff;
private final ArrayList copies = new ArrayList();
private File tempDir;
private long filecount;
private boolean tempDirMessageLogged;
/**
* constructor to set the location of the temporary directory.
*
* @param tempDir The temporary directory.
*/
public DefaultFileReplicator(final File tempDir)
{
this.tempDir = tempDir;
}
public DefaultFileReplicator()
{
}
/**
* Initialises this component.
* @throws FileSystemException if an error occurs.
*/
@Override
public void init() throws FileSystemException
{
if (tempDir == null)
{
String baseTmpDir = System.getProperty("java.io.tmpdir");
tempDir = new File(baseTmpDir, "vfs_cache").getAbsoluteFile();
}
filecount = new Random().nextInt() & MASK;
if (!tempDirMessageLogged)
{
final String message = Messages.getString("vfs.impl/temp-dir.info", tempDir);
VfsLog.info(getLogger(), log, message);
tempDirMessageLogged = true;
}
}
/**
* Closes the replicator, deleting all temporary files.
*/
@Override
public void close()
{
// Delete the temporary files
synchronized (copies)
{
while (copies.size() > 0)
{
final File file = (File) removeFile();
deleteFile(file);
}
}
// Clean up the temp directory, if it is empty
if (tempDir != null && tempDir.exists() && tempDir.list().length == 0)
{
tempDir.delete();
tempDir = null;
}
}
/**
* physically deletes the file from the filesystem
* @param file The File to delete.
*/
protected void deleteFile(File file)
{
try
{
final FileObject fileObject = getContext().toFileObject(file);
fileObject.delete(Selectors.SELECT_ALL);
}
catch (final FileSystemException e)
{
final String message = Messages.getString("vfs.impl/delete-temp.warn", file.getName());
VfsLog.warn(getLogger(), log, message, e);
}
}
/**
* removes a file from the copies list. Will be used for cleanup.
* Notice: The system awaits that the returning object can be cast to a java.io.File
* @return the File that was removed.
*/
protected Object removeFile()
{
synchronized (copies)
{
return copies.remove(0);
}
}
/**
* removes a instance from the list of copies
* @param file The File to remove.
*/
protected void removeFile(Object file)
{
synchronized (copies)
{
copies.remove(file);
}
}
/**
* Allocates a new temporary file.
* @param baseName the base file name.
* @return The created File.
* @throws FileSystemException if an error occurs.
*/
public File allocateFile(final String baseName) throws FileSystemException
{
// Create a unique-ish file name
final String basename = createFilename(baseName);
synchronized (this)
{
filecount++;
}
return createAndAddFile(tempDir, basename);
}
protected File createAndAddFile(final File parent, final String basename) throws FileSystemException
{
final File file = createFile(tempDir, basename);
// Keep track to delete later
addFile(file);
return file;
}
protected void addFile(Object file)
{
synchronized (copies)
{
copies.add(file);
}
}
protected long getFilecount()
{
return filecount;
}
/**
* create the temporary file name
* @param baseName The base to prepend to the file name being created.
* @return the name of the File.
*/
protected String createFilename(final String baseName)
{
// BUG29007
// return baseName + "_" + getFilecount() + ".tmp";
// imario@apache.org: BUG34976 get rid of maybe reserved and dangerous characters
// e.g. to allow replication of http://hostname.org/fileservlet?file=abc.txt
String safeBasename = UriParser.encode(baseName, TMP_RESERVED_CHARS).replace('%', '_');
return "tmp_" + getFilecount() + "_" + safeBasename;
}
/**
* create the temporary file
* @param parent The file to use as the parent of the file being created.
* @param name The name of the file to create.
* @return The File that was created.
* @throws FileSystemException if an error occurs creating the file.
*/
protected File createFile(final File parent, final String name) throws FileSystemException
{
return new File(parent, UriParser.decode(name));
}
/**
* Creates a local copy of the file, and all its descendents.
* @param srcFile The file to copy.
* @param selector The FileSelector.
* @return the created File.
* @throws FileSystemException if an error occurs copying the file.
*/
public File replicateFile(final FileObject srcFile,
final FileSelector selector)
throws FileSystemException
{
final String basename = srcFile.getName().getBaseName();
final File file = allocateFile(basename);
// Copy from the source file
final FileObject destFile = getContext().toFileObject(file);
destFile.copyFrom(srcFile, selector);
return file;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemConfigBuilder.java 100644 765 24 5057 11623215065 33120 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticator;
/**
* Default options usable for all filesystems.
* @author Commons VFS team
*/
public class DefaultFileSystemConfigBuilder extends FileSystemConfigBuilder
{
/** The default FileSystemConfigBuilder */
private static final DefaultFileSystemConfigBuilder BUILDER = new DefaultFileSystemConfigBuilder();
public static DefaultFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
/**
* Sets the user authenticator to get authentication informations.
* @param opts The FileSystemOptions.
* @param userAuthenticator The UserAuthenticator.
* @throws FileSystemException if an error occurs setting the UserAuthenticator.
*/
public void setUserAuthenticator(FileSystemOptions opts, UserAuthenticator userAuthenticator)
throws FileSystemException
{
setParam(opts, "userAuthenticator", userAuthenticator);
}
/**
* @see #setUserAuthenticator
* @param opts The FileSystemOptions.
* @return The UserAuthenticator.
*/
public UserAuthenticator getUserAuthenticator(FileSystemOptions opts)
{
return (UserAuthenticator) getParam(opts, "userAuthenticator");
}
/**
* Dummy class that implements FileSystem.
*/
abstract static class DefaultFileSystem implements FileSystem
{
}
@Override
protected Class extends FileSystem> getConfigClass()
{
return DefaultFileSystem.class;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DefaultFileSystemManager.java 100644 765 24 111333 11623215065 32011 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.File;
import java.lang.reflect.Constructor;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.CacheStrategy;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileContentInfoFactory;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.FilesCache;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.cache.SoftRefFilesCache;
import org.apache.commons.vfs2.operations.FileOperationProvider;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileProvider;
import org.apache.commons.vfs2.provider.DefaultURLStreamHandler;
import org.apache.commons.vfs2.provider.FileProvider;
import org.apache.commons.vfs2.provider.FileReplicator;
import org.apache.commons.vfs2.provider.LocalFileProvider;
import org.apache.commons.vfs2.provider.TemporaryFileStore;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.provider.VfsComponent;
/**
* A default file system manager implementation.
*
* @author Commons VFS team
* 2006) $
*/
public class DefaultFileSystemManager implements FileSystemManager
{
/**
* The provider for local files.
*/
private LocalFileProvider localFileProvider;
/**
* The default provider.
*/
private FileProvider defaultProvider;
/**
* The file replicator to use.
*/
private FileReplicator fileReplicator;
/**
* Mapping from URI scheme to FileProvider.
*/
private final Map providers = new HashMap();
/**
* All components used by this manager.
*/
private final ArrayList components = new ArrayList();
/**
* The base file to use for relative URI.
*/
private FileObject baseFile;
/**
* The files cache
*/
private FilesCache filesCache;
/**
* The cache strategy
*/
private CacheStrategy fileCacheStrategy;
/**
* Class which decorates all returned fileObjects
*/
private Class> fileObjectDecorator;
private Constructor> fileObjectDecoratorConst;
/**
* The class to use to determine the content-type (mime-type)
*/
private FileContentInfoFactory fileContentInfoFactory;
/**
* The logger to use.
*/
private Log log = LogFactory.getLog(getClass());
/**
* The context to pass to providers.
*/
private final DefaultVfsComponentContext context = new DefaultVfsComponentContext(
this);
private TemporaryFileStore tempFileStore;
private final FileTypeMap map = new FileTypeMap();
private final VirtualFileProvider vfsProvider = new VirtualFileProvider();
private boolean init;
private final Map> operationProviders =
new HashMap>();
/**
* Returns the logger used by this manager.
* @return the Logger.
*/
protected Log getLogger()
{
return log;
}
/**
* Registers a file system provider. The manager takes care of all lifecycle
* management. A provider may be registered multiple times.
*
* @param urlScheme
* The scheme the provider will handle.
* @param provider
* The provider.
* @throws FileSystemException if an error occurs adding the provider.
*/
public void addProvider(final String urlScheme, final FileProvider provider)
throws FileSystemException
{
addProvider(new String[] {urlScheme}, provider);
}
/**
* Registers a file system provider. The manager takes care of all lifecycle
* management. A provider may be registered multiple times.
*
* @param urlSchemes
* The schemes the provider will handle.
* @param provider
* The provider.
* @throws FileSystemException if an error occurs adding the provider.
*/
public void addProvider(final String[] urlSchemes,
final FileProvider provider) throws FileSystemException
{
// Warn about duplicate providers
for (int i = 0; i < urlSchemes.length; i++)
{
final String scheme = urlSchemes[i];
if (providers.containsKey(scheme))
{
throw new FileSystemException(
"vfs.impl/multiple-providers-for-scheme.error", scheme);
}
}
// Contextualise the component (if not already)
setupComponent(provider);
// Add to map
for (int i = 0; i < urlSchemes.length; i++)
{
final String scheme = urlSchemes[i];
providers.put(scheme, provider);
}
if (provider instanceof LocalFileProvider && localFileProvider == null)
{
localFileProvider = (LocalFileProvider) provider;
}
}
/**
* Returns true if this manager has a provider for a particular scheme.
* @param scheme The scheme to check.
* @return true if a provider is configured for this scheme, false otherwise.
*/
public boolean hasProvider(final String scheme)
{
return providers.containsKey(scheme);
}
/**
* Adds an filename extension mapping.
*
* @param extension The file name extension.
* @param scheme The scheme to use for files with this extension.
*/
public void addExtensionMap(final String extension, final String scheme)
{
map.addExtension(extension, scheme);
}
/**
* Adds a mime type mapping.
*
* @param mimeType The mime type.
* @param scheme The scheme to use for files with this mime type.
*/
public void addMimeTypeMap(final String mimeType, final String scheme)
{
map.addMimeType(mimeType, scheme);
}
/**
* Sets the default provider. This is the provider that will handle URI with
* unknown schemes. The manager takes care of all lifecycle management.
* @param provider The FileProvider.
* @throws FileSystemException if an error occurs setting the provider.
*/
public void setDefaultProvider(final FileProvider provider)
throws FileSystemException
{
setupComponent(provider);
defaultProvider = provider;
}
/**
* Returns the filesCache implementation used to cache files.
* @return The FilesCache.
*/
public FilesCache getFilesCache()
{
return filesCache;
}
/**
* Sets the filesCache implementation used to cache files.
* @param filesCache The FilesCache.
* @throws FileSystemException if an error occurs setting the cache..
*/
public void setFilesCache(final FilesCache filesCache)
throws FileSystemException
{
if (init)
{
throw new FileSystemException("vfs.impl/already-inited.error");
}
this.filesCache = filesCache;
}
/**
*
* Set the cache strategy to use when dealing with file object data. You can
* set it only once before the FileSystemManager is initialized.
*
*
* The default is {@link CacheStrategy#ON_RESOLVE}
*
*
* @param fileCacheStrategy The CacheStrategy to use.
* @throws FileSystemException
* if this is not possible. e.g. it is already set.
*/
public void setCacheStrategy(final CacheStrategy fileCacheStrategy)
throws FileSystemException
{
if (init)
{
throw new FileSystemException("vfs.impl/already-inited.error");
}
this.fileCacheStrategy = fileCacheStrategy;
}
/**
* Get the cache strategy used.
* @return The CacheStrategy.
*/
public CacheStrategy getCacheStrategy()
{
return fileCacheStrategy;
}
/**
* Get the file object decorator used.
* @return The decorator.
*/
public Class> getFileObjectDecorator()
{
return fileObjectDecorator;
}
/**
* The constructor associated to the fileObjectDecorator.
* We cache it here for performance reasons.
* @return The decorator's Constructor.
*/
public Constructor> getFileObjectDecoratorConst()
{
return fileObjectDecoratorConst;
}
/**
* Set a fileObject decorator to be used for ALL returned file objects.
*
* @param fileObjectDecorator must be inherted from {@link DecoratedFileObject} a has to provide a
* constructor with a single {@link FileObject} as argument
* @throws FileSystemException if an error occurs setting the decorator.
*/
public void setFileObjectDecorator(Class> fileObjectDecorator) throws FileSystemException
{
if (init)
{
throw new FileSystemException("vfs.impl/already-inited.error");
}
if (!DecoratedFileObject.class.isAssignableFrom(fileObjectDecorator))
{
throw new FileSystemException("vfs.impl/invalid-decorator.error", fileObjectDecorator.getName());
}
try
{
fileObjectDecoratorConst = fileObjectDecorator.getConstructor(new Class[]{FileObject.class});
}
catch (NoSuchMethodException e)
{
throw new FileSystemException("vfs.impl/invalid-decorator.error", fileObjectDecorator.getName(), e);
}
this.fileObjectDecorator = fileObjectDecorator;
}
/**
* get the fileContentInfoFactory used to determine the infos of a file
* content.
* @return The FileContentInfoFactory.
*/
public FileContentInfoFactory getFileContentInfoFactory()
{
return fileContentInfoFactory;
}
/**
* set the fileContentInfoFactory used to determine the infos of a file
* content.
* @param fileContentInfoFactory The FileContentInfoFactory.
* @throws FileSystemException if an error occurs setting the FileContentInfoFactory.
*/
public void setFileContentInfoFactory(FileContentInfoFactory fileContentInfoFactory)
throws FileSystemException
{
if (init)
{
throw new FileSystemException("vfs.impl/already-inited.error");
}
this.fileContentInfoFactory = fileContentInfoFactory;
}
/**
* Sets the file replicator to use. The manager takes care of all lifecycle
* management.
* @param replicator The FileReplicator.
* @throws FileSystemException if an error occurs setting the replicator.
*/
public void setReplicator(final FileReplicator replicator)
throws FileSystemException
{
setupComponent(replicator);
fileReplicator = replicator;
}
/**
* Sets the temporary file store to use. The manager takes care of all
* lifecycle management.
* @param tempFileStore The temporary FileStore.
* @throws FileSystemException if an error occurs adding the file store.
*/
public void setTemporaryFileStore(final TemporaryFileStore tempFileStore)
throws FileSystemException
{
setupComponent(tempFileStore);
this.tempFileStore = tempFileStore;
}
/**
* Sets the logger to use.
* @param log The Logger to use.
*/
public void setLogger(final Log log)
{
this.log = log;
}
/**
* Initialises a component, if it has not already been initialised.
* @param component The component to setup.
* @throws FileSystemException if an error occurs.
*/
private void setupComponent(final Object component)
throws FileSystemException
{
if (!components.contains(component))
{
if (component instanceof VfsComponent)
{
final VfsComponent vfsComponent = (VfsComponent) component;
vfsComponent.setLogger(getLogger());
vfsComponent.setContext(context);
vfsComponent.init();
}
components.add(component);
}
}
/**
* Closes a component, if it has not already been closed.
* @param component The component to close.
*/
private void closeComponent(final Object component)
{
if (component != null && components.contains(component))
{
if (component instanceof VfsComponent)
{
final VfsComponent vfsComponent = (VfsComponent) component;
vfsComponent.close();
}
components.remove(component);
}
}
/**
* Returns the file replicator.
*
* @return The file replicator. Never returns null.
* @throws FileSystemException if there is no FileReplicator.
*/
public FileReplicator getReplicator() throws FileSystemException
{
if (fileReplicator == null)
{
throw new FileSystemException("vfs.impl/no-replicator.error");
}
return fileReplicator;
}
/**
* Returns the temporary file store.
*
* @return The file store. Never returns null.
* @throws FileSystemException if there is no TemporaryFileStore.
*/
public TemporaryFileStore getTemporaryFileStore()
throws FileSystemException
{
if (tempFileStore == null)
{
throw new FileSystemException("vfs.impl/no-temp-file-store.error");
}
return tempFileStore;
}
/**
* Initialises this manager.
* @throws FileSystemException if an error occurs during initialization.
*/
public void init() throws FileSystemException
{
if (filesCache == null)
{
// filesCache = new DefaultFilesCache();
filesCache = new SoftRefFilesCache();
}
if (fileContentInfoFactory == null)
{
fileContentInfoFactory = new FileContentInfoFilenameFactory();
}
if (fileCacheStrategy == null)
{
fileCacheStrategy = CacheStrategy.ON_RESOLVE;
}
setupComponent(filesCache);
setupComponent(vfsProvider);
init = true;
}
/**
* Closes all files created by this manager, and cleans up any temporary
* files. Also closes all providers and the replicator.
*/
public void close()
{
if (!init)
{
return;
}
// Close the providers.
for (Iterator> iterator = providers.values().iterator(); iterator
.hasNext();)
{
final Object provider = iterator.next();
closeComponent(provider);
}
// Close the other components
closeComponent(defaultProvider);
closeComponent(fileReplicator);
closeComponent(tempFileStore);
components.clear();
providers.clear();
filesCache.close();
localFileProvider = null;
defaultProvider = null;
fileReplicator = null;
tempFileStore = null;
init = false;
}
/**
* Free all resources used by unused filesystems created by this manager.
*/
public void freeUnusedResources()
{
if (!init)
{
return;
}
// Close the providers.
for (Iterator iterator = providers.values().iterator(); iterator
.hasNext();)
{
final AbstractFileProvider provider = (AbstractFileProvider) iterator
.next();
provider.freeUnusedResources();
}
}
/**
* Sets the base file to use when resolving relative URI.
* @param baseFile The new base FileObject.
* @throws FileSystemException if an error occurs.
*/
public void setBaseFile(final FileObject baseFile)
throws FileSystemException
{
this.baseFile = baseFile;
}
/**
* Sets the base file to use when resolving relative URI.
* @param baseFile The new base FileObject.
* @throws FileSystemException if an error occurs.
*/
public void setBaseFile(final File baseFile) throws FileSystemException
{
this.baseFile = getLocalFileProvider().findLocalFile(baseFile);
}
/**
* Returns the base file used to resolve relative URI.
* @return The FileObject that represents the base file.
* @throws FileSystemException if an error occurs.
*/
public FileObject getBaseFile() throws FileSystemException
{
return baseFile;
}
/**
* Locates a file by URI.
* @param uri The URI of the file to locate.
* @return The FileObject for the located file.
* @throws FileSystemException if the file cannot be located or an error occurs.
*/
public FileObject resolveFile(final String uri) throws FileSystemException
{
// return resolveFile(baseFile, uri);
return resolveFile(getBaseFile(), uri);
}
/**
* Locate a file by URI, use the FileSystemOptions for file-system creation.
* @param uri The URI of the file to locate.
* @param fileSystemOptions The options for the FileSystem.
* @return The FileObject for the located file.
* @throws FileSystemException if the file cannot be located or an error occurs.
*/
public FileObject resolveFile(final String uri,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// return resolveFile(baseFile, uri, fileSystemOptions);
return resolveFile(getBaseFile(), uri, fileSystemOptions);
}
/**
* Locates a file by URI.
* @param baseFile The base File to use to locate the file.
* @param uri The URI of the file to locate.
* @return The FileObject for the located file.
* @throws FileSystemException if the file cannot be located or an error occurs.
*/
public FileObject resolveFile(final File baseFile, final String uri)
throws FileSystemException
{
final FileObject baseFileObj = getLocalFileProvider().findLocalFile(
baseFile);
return resolveFile(baseFileObj, uri);
}
/**
* Resolves a URI, relative to a base file.
* @param baseFile The base FileOjbect to use to locate the file.
* @param uri The URI of the file to locate.
* @return The FileObject for the located file.
* @throws FileSystemException if the file cannot be located or an error occurs.
*/
public FileObject resolveFile(final FileObject baseFile, final String uri)
throws FileSystemException
{
return resolveFile(baseFile, uri, baseFile == null ? null : baseFile
.getFileSystem().getFileSystemOptions());
}
/**
* Resolves a URI, realtive to a base file with specified FileSystem
* configuration.
* @param baseFile The base file.
* @param uri The file name. May be a fully qualified or relative path or a url.
* @param fileSystemOptions Options to pass to the file system.
* @return A FileObject representing the target file.
* @throws FileSystemException if an error occurs accessing the file.
*/
public FileObject resolveFile(final FileObject baseFile, final String uri,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
final FileObject realBaseFile;
if (baseFile != null && VFS.isUriStyle()
&& baseFile.getName().getType() == FileType.FILE)
{
realBaseFile = baseFile.getParent();
}
else
{
realBaseFile = baseFile;
}
// TODO: use resolveName and use this name to resolve the fileObject
UriParser.checkUriEncoding(uri);
if (uri == null)
{
throw new IllegalArgumentException();
}
// Extract the scheme
final String scheme = UriParser.extractScheme(uri);
if (scheme != null)
{
// An absolute URI - locate the provider
final FileProvider provider = providers.get(scheme);
if (provider != null)
{
return provider.findFile(realBaseFile, uri, fileSystemOptions);
}
// Otherwise, assume a local file
}
// Handle absolute file names
if (localFileProvider != null
&& localFileProvider.isAbsoluteLocalName(uri))
{
return localFileProvider.findLocalFile(uri);
}
if (scheme != null)
{
// An unknown scheme - hand it to the default provider
if (defaultProvider == null)
{
throw new FileSystemException("vfs.impl/unknown-scheme.error",
new Object[] {scheme, uri});
}
return defaultProvider.findFile(realBaseFile, uri, fileSystemOptions);
}
// Assume a relative name - use the supplied base file
if (realBaseFile == null)
{
throw new FileSystemException("vfs.impl/find-rel-file.error", uri);
}
return realBaseFile.resolveFile(uri);
}
/**
* Resolves a name, relative to the file. If the supplied name is an
* absolute path, then it is resolved relative to the root of the file
* system that the file belongs to. If a relative name is supplied, then it
* is resolved relative to this file name.
* @param root The base FileName.
* @param path The path to the file relative to the base FileName or an absolute path.
* @return The constructed FileName.
* @throws FileSystemException if an error occurs constructing the FileName.
*/
public FileName resolveName(final FileName root, final String path)
throws FileSystemException
{
return resolveName(root, path, NameScope.FILE_SYSTEM);
}
/**
* Resolves a name, relative to the root.
*
* @param base the base filename
* @param name the name
* @param scope the {@link NameScope}
* @return The FileName of the file.
* @throws FileSystemException if an error occurs.
*/
public FileName resolveName(final FileName base, final String name,
final NameScope scope) throws FileSystemException
{
final FileName realBase;
if (base != null && VFS.isUriStyle() && base.getType() == FileType.FILE)
{
realBase = base.getParent();
}
else
{
realBase = base;
}
final StringBuilder buffer = new StringBuilder(name);
// Adjust separators
UriParser.fixSeparators(buffer);
String scheme = UriParser.extractScheme(buffer.toString());
// Determine whether to prepend the base path
if (name.length() == 0 || (scheme == null && buffer.charAt(0) != FileName.SEPARATOR_CHAR))
{
// Supplied path is not absolute
if (!VFS.isUriStyle())
{
// when using uris the parent already do have the trailing "/"
buffer.insert(0, FileName.SEPARATOR_CHAR);
}
buffer.insert(0, realBase.getPath());
}
// // UriParser.canonicalizePath(buffer, 0, name.length());
// Normalise the path
FileType fileType = UriParser.normalisePath(buffer);
// Check the name is ok
final String resolvedPath = buffer.toString();
if (!AbstractFileName
.checkName(realBase.getPath(), resolvedPath, scope))
{
throw new FileSystemException(
"vfs.provider/invalid-descendent-name.error", name);
}
String fullPath;
if (scheme != null)
{
fullPath = resolvedPath;
}
else
{
scheme = realBase.getScheme();
fullPath = realBase.getRootURI() + resolvedPath;
}
final FileProvider provider = providers.get(scheme);
if (provider != null)
{
// todo: extend the filename parser to be able to parse
// only a pathname and take the missing informations from
// the base. Then we can get rid of the string operation.
// // String fullPath = base.getRootURI() +
// resolvedPath.substring(1);
return provider.parseUri(realBase, fullPath);
}
if (scheme != null)
{
// An unknown scheme - hand it to the default provider - if possible
if (defaultProvider != null)
{
return defaultProvider.parseUri(realBase, fullPath);
}
}
// todo: avoid fallback to this point
// this happens if we have a virtual filesystem (no provider for scheme)
return ((AbstractFileName) realBase).createName(resolvedPath, fileType);
}
/**
* Resolve the uri to a filename.
* @param uri The URI to resolve.
* @return The FileName of the file.
* @throws FileSystemException if an error occurs.
*/
public FileName resolveURI(String uri) throws FileSystemException
{
UriParser.checkUriEncoding(uri);
if (uri == null)
{
throw new IllegalArgumentException();
}
// Extract the scheme
final String scheme = UriParser.extractScheme(uri);
if (scheme != null)
{
// An absolute URI - locate the provider
final FileProvider provider = providers.get(scheme);
if (provider != null)
{
return provider.parseUri(null, uri);
}
// Otherwise, assume a local file
}
// Handle absolute file names
if (localFileProvider != null
&& localFileProvider.isAbsoluteLocalName(uri))
{
return localFileProvider.parseUri(null, uri);
}
if (scheme != null)
{
// An unknown scheme - hand it to the default provider
if (defaultProvider == null)
{
throw new FileSystemException("vfs.impl/unknown-scheme.error",
new Object[] {scheme, uri});
}
return defaultProvider.parseUri(null, uri);
}
// Assume a relative name - use the supplied base file
if (baseFile == null)
{
throw new FileSystemException("vfs.impl/find-rel-file.error", uri);
}
return resolveName(baseFile.getName(), uri, NameScope.FILE_SYSTEM);
}
/**
* Converts a local file into a {@link FileObject}.
* @param file The input File.
* @return the create FileObject
* @throws FileSystemException if an error occurs creating the file naem.
*/
public FileObject toFileObject(final File file) throws FileSystemException
{
return getLocalFileProvider().findLocalFile(file);
}
/**
* Creates a layered file system.
* @param scheme The scheme to use.
* @param file The FileObject.
* @return The layered FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileObject createFileSystem(final String scheme,
final FileObject file) throws FileSystemException
{
final FileProvider provider = providers.get(scheme);
if (provider == null)
{
throw new FileSystemException("vfs.impl/unknown-provider.error",
new Object[] {scheme, file});
}
return provider.createFileSystem(scheme, file, file.getFileSystem().getFileSystemOptions());
}
/**
* Creates a layered file system.
* @param file The FileObject to use.
* @return The layered FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileObject createFileSystem(final FileObject file)
throws FileSystemException
{
final String scheme = map.getScheme(file);
if (scheme == null)
{
throw new FileSystemException(
"vfs.impl/no-provider-for-file.error", file);
}
return createFileSystem(scheme, file);
}
/**
* Determines if a layered file system can be created for a given file.
*
* @param file The file to check for.
* @return true if the FileSystem can be created.
* @throws FileSystemException if an error occurs.
*/
public boolean canCreateFileSystem(final FileObject file)
throws FileSystemException
{
return map.getScheme(file) != null;
}
/**
* Creates a virtual file system.
* @param rootFile The FileObject to use.
* @return The FileObject in the VirtualFileSystem.
* @throws FileSystemException if an error occurs creating the file.
*/
public FileObject createVirtualFileSystem(final FileObject rootFile)
throws FileSystemException
{
return vfsProvider.createFileSystem(rootFile);
}
/**
* Creates an empty virtual file system.
* @param rootUri The URI to use as the root of the FileSystem.
* @return A FileObject in the virtual FileSystem.
* @throws FileSystemException if an error occurs.
*/
public FileObject createVirtualFileSystem(final String rootUri)
throws FileSystemException
{
return vfsProvider.createFileSystem(rootUri);
}
/**
* Locates the local file provider.
* @return The LocalFileProvider.
* @throws FileSystemException if an error occurs.
*/
private LocalFileProvider getLocalFileProvider() throws FileSystemException
{
if (localFileProvider == null)
{
throw new FileSystemException(
"vfs.impl/no-local-file-provider.error");
}
return localFileProvider;
}
/**
* Get the URLStreamHandlerFactory.
* @return The URLStreamHandlerFactory.
*/
public URLStreamHandlerFactory getURLStreamHandlerFactory()
{
return new VfsStreamHandlerFactory();
}
/**
* Closes the given filesystem.
* If you use VFS as singleton it is VERY dangerous to call this method
* @param filesystem The FileSystem to close.
*/
public void closeFileSystem(FileSystem filesystem)
{
// inform the cache ...
getFilesCache().clear(filesystem);
// just in case the cache didnt call _closeFileSystem
_closeFileSystem(filesystem);
}
/**
* Closes the given filesystem.
* If you use VFS as singleton it is VERY dangerous to call this method
* @param filesystem The FileSystem to close.
*/
public void _closeFileSystem(FileSystem filesystem)
{
FileProvider provider = providers.get(filesystem.getRootName().getScheme());
if (provider != null)
{
((AbstractFileProvider) provider).closeFileSystem(filesystem);
}
}
/**
* This is an internal class because it needs access to the private member
* providers.
*/
final class VfsStreamHandlerFactory implements URLStreamHandlerFactory
{
public URLStreamHandler createURLStreamHandler(final String protocol)
{
FileProvider provider = providers.get(protocol);
if (provider != null)
{
return new DefaultURLStreamHandler(context);
}
// Route all other calls to the default URLStreamHandlerFactory
return new URLStreamHandlerProxy();
}
}
/**
* Get the schemes currently available.
* @return The array of scheme names.
*/
public String[] getSchemes()
{
String[] schemes = new String[providers.size()];
providers.keySet().toArray(schemes);
return schemes;
}
/**
* Get the capabilities for a given scheme.
*
* @param scheme The scheme to located.
* @return A Collection of capabilities.
* @throws FileSystemException if the given scheme is not konwn
*/
public Collection getProviderCapabilities(final String scheme)
throws FileSystemException
{
FileProvider provider = providers.get(scheme);
if (provider == null)
{
throw new FileSystemException("vfs.impl/unknown-scheme.error",
new Object[] {scheme});
}
return provider.getCapabilities();
}
/**
* Get the configuration builder for the given scheme.
* @param scheme The scheme to locate.
* @return The FileSystemConfigBuilder for the scheme.
* @throws FileSystemException if the given scheme is not konwn
*/
public FileSystemConfigBuilder getFileSystemConfigBuilder(final String scheme)
throws FileSystemException
{
FileProvider provider = providers.get(scheme);
if (provider == null)
{
throw new FileSystemException("vfs.impl/unknown-scheme.error", new Object[] {scheme});
}
return provider.getConfigBuilder();
}
// -- OPERATIONS --
/**
* Adds the specified FileOperationProvider for the specified scheme.
* Several FileOperationProvider's might be registered for the same scheme.
* For example, for "file" scheme we can register SvnWsOperationProvider and
* CvsOperationProvider.
*
* @param scheme The scheme the provider should be registered for.
* @param operationProvider The FileOperationProvider.
* @throws FileSystemException if an error occurs adding the provider.
*/
public void addOperationProvider(final String scheme,
final FileOperationProvider operationProvider)
throws FileSystemException
{
addOperationProvider(new String[] {scheme}, operationProvider);
}
/**
* @see FileSystemManager#addOperationProvider(String,
* org.apache.commons.vfs2.operations.FileOperationProvider)
*
* @param schemes The array of schemes the provider should apply to.
* @param operationProvider The FileOperationProvider.
* @throws FileSystemException if an error occurs.
*/
public void addOperationProvider(final String[] schemes,
final FileOperationProvider operationProvider)
throws FileSystemException
{
for (int i = 0; i < schemes.length; i++)
{
final String scheme = schemes[i];
if (!operationProviders.containsKey(scheme))
{
final List providers = new ArrayList();
operationProviders.put(scheme, providers);
}
final List providers = operationProviders.get(scheme);
if (providers.contains(operationProvider))
{
throw new FileSystemException(
"vfs.operation/operation-provider-already-added.error", scheme);
}
setupComponent(operationProvider);
providers.add(operationProvider);
}
}
/**
* @param scheme
* the scheme for wich we want to get the list af registered
* providers.
*
* @return the registered FileOperationProviders for the specified scheme.
* If there were no providers registered for the scheme, it returns
* null.
*
* @throws FileSystemException if an error occurs.
*/
public FileOperationProvider[] getOperationProviders(final String scheme)
throws FileSystemException
{
List> providers = operationProviders.get(scheme);
if (providers == null || providers.size() == 0)
{
return null;
}
return providers.toArray(new FileOperationProvider[] {});
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DefaultProviderConfiguration.java 100644 765 24 2216 11623215065 32713 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
/**
* Same as {@link ProviderConfiguration} but for the default provider.
*
* @author Commons VFS team
*/
public class DefaultProviderConfiguration extends ProviderConfiguration
{
@Override
public boolean isDefault()
{
return true;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/DefaultVfsComponentContext.java 100644 765 24 6177 11623215065 32371 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.File;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.FileReplicator;
import org.apache.commons.vfs2.provider.TemporaryFileStore;
import org.apache.commons.vfs2.provider.VfsComponentContext;
/**
* The default context implementation.
*
* @author Commons VFS team
*/
final class DefaultVfsComponentContext
implements VfsComponentContext
{
private final DefaultFileSystemManager manager;
public DefaultVfsComponentContext(final DefaultFileSystemManager manager)
{
this.manager = manager;
}
/**
* Locate a file by name.
*/
public FileObject resolveFile(final FileObject baseFile, final String name,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
return manager.resolveFile(baseFile, name, fileSystemOptions);
}
/**
* Locate a file by name.
*/
public FileObject resolveFile(final String name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
return manager.resolveFile(name, fileSystemOptions);
}
public FileName parseURI(String uri) throws FileSystemException
{
return manager.resolveURI(uri);
}
/**
* Returns a {@link FileObject} for a local file.
*/
public FileObject toFileObject(File file)
throws FileSystemException
{
return manager.toFileObject(file);
}
/**
* Locates a file replicator for the provider to use.
*/
public FileReplicator getReplicator() throws FileSystemException
{
return manager.getReplicator();
}
/**
* Locates a temporary file store for the provider to use.
*/
public TemporaryFileStore getTemporaryFileStore() throws FileSystemException
{
return manager.getTemporaryFileStore();
}
/**
* Returns the filesystem manager for the current context
*
* @return the filesystem manager
*/
public FileSystemManager getFileSystemManager()
{
return manager;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/FileContentInfoFilenameFactory.java 100644 765 24 3407 11623215065 33106 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.net.FileNameMap;
import java.net.URLConnection;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileContentInfo;
import org.apache.commons.vfs2.FileContentInfoFactory;
/**
* The FileContentInfoFilenameFactory.
* Uses the filename extension to determine the content-type.
* The content-encoding is not resolved.
*
* @author Commons VFS team
*/
public class FileContentInfoFilenameFactory implements FileContentInfoFactory
{
public FileContentInfo create(FileContent fileContent)
{
String contentType = null;
String name = fileContent.getFile().getName().getBaseName();
if (name != null)
{
FileNameMap fileNameMap = URLConnection.getFileNameMap();
contentType = fileNameMap.getContentTypeFor(name);
}
return new DefaultFileContentInfo(contentType, null);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/FileTypeMap.java 100644 765 24 4622 11623215065 27246 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
/**
* A helper class that determines the provider to use for a file.
*
* @author Commons VFS team
*/
class FileTypeMap
{
private final Map mimeTypeMap = new HashMap();
private final Map extensionMap = new HashMap();
/**
* Adds a MIME type mapping.
*/
public void addMimeType(final String mimeType, final String scheme)
{
mimeTypeMap.put(mimeType, scheme);
}
/**
* Adds a filename extension mapping.
*/
public void addExtension(final String extension, final String scheme)
{
extensionMap.put(extension, scheme);
}
/**
* Finds the provider to use to create a filesystem from a given file.
*/
public String getScheme(final FileObject file) throws FileSystemException
{
// Check the file's mime type for a match
final FileContent content = file.getContent();
// final String mimeType = (String) content.getAttribute("content-type");
final String mimeType = content.getContentInfo().getContentType();
if (mimeType != null)
{
return mimeTypeMap.get(mimeType);
}
// Check the file's extension for a match
final String extension = file.getName().getExtension();
return extensionMap.get(extension);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/package.html 100644 765 24 1552 11623215065 26504 0 ustar rgoers staff 0 0
The standard VFS implementation.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/PrivilegedFileReplicator.java 100644 765 24 12764 11623215065 32034 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.File;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import org.apache.commons.logging.Log;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.FileReplicator;
import org.apache.commons.vfs2.provider.VfsComponent;
import org.apache.commons.vfs2.provider.VfsComponentContext;
/**
* A file replicator that wraps another file replicator, performing
* the replication as a privileged action.
*
* @author Commons VFS team
*/
public class PrivilegedFileReplicator
implements FileReplicator, VfsComponent
{
private final FileReplicator replicator;
private final VfsComponent replicatorComponent;
public PrivilegedFileReplicator(FileReplicator replicator)
{
this.replicator = replicator;
if (replicator instanceof VfsComponent)
{
replicatorComponent = (VfsComponent) replicator;
}
else
{
replicatorComponent = null;
}
}
/**
* Sets the Logger to use for the component.
* @param logger The logger.
*/
public void setLogger(final Log logger)
{
if (replicatorComponent != null)
{
replicatorComponent.setLogger(logger);
}
}
/**
* Sets the context for the replicator.
* @param context The component context.
*/
public void setContext(final VfsComponentContext context)
{
if (replicatorComponent != null)
{
replicatorComponent.setContext(context);
}
}
/**
* Initialises the component.
* @throws FileSystemException if an error occurs.
*/
public void init() throws FileSystemException
{
if (replicatorComponent != null)
{
try
{
AccessController.doPrivileged(new InitAction());
}
catch (final PrivilegedActionException e)
{
throw new FileSystemException("vfs.impl/init-replicator.error", null, e);
}
}
}
/**
* Closes the replicator.
*/
public void close()
{
if (replicatorComponent != null)
{
AccessController.doPrivileged(new CloseAction());
}
}
/**
* Creates a local copy of the file, and all its descendents.
* @param srcFile The source FileObject.
* @param selector The file selector.
* @return The replicated file.
* @throws FileSystemException if an error occurs.
*/
public File replicateFile(FileObject srcFile, FileSelector selector)
throws FileSystemException
{
try
{
final ReplicateAction action = new ReplicateAction(srcFile, selector);
return AccessController.doPrivileged(action);
}
catch (final PrivilegedActionException e)
{
throw new FileSystemException("vfs.impl/replicate-file.error", new Object[]{srcFile.getName()}, e);
}
}
/**
* An action that initialises the wrapped replicator.
*/
private class InitAction implements PrivilegedExceptionAction
{
/**
* Performs the action.
*/
public Object run() throws Exception
{
replicatorComponent.init();
return null;
}
}
/**
* An action that replicates a file using the wrapped replicator.
*/
private class ReplicateAction implements PrivilegedExceptionAction
{
private final FileObject srcFile;
private final FileSelector selector;
public ReplicateAction(final FileObject srcFile,
final FileSelector selector)
{
this.srcFile = srcFile;
this.selector = selector;
}
/**
* Performs the action.
* @throws Exception if an error occurs.
*/
public File run() throws Exception
{
// TODO - Do not pass the selector through. It is untrusted
// TODO - Need to determine which files can be read
return replicator.replicateFile(srcFile, selector);
}
}
/**
* An action that closes the wrapped replicator.
*/
private class CloseAction implements PrivilegedAction
{
/**
* Performs the action.
*/
public Object run()
{
replicatorComponent.close();
return null;
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/ProviderConfiguration.java 100644 765 24 3615 11623215065 31412 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.util.ArrayList;
import java.util.List;
/**
* This class describes the configuration for a provider.
* Used by digester in StandardFileSystemManager
*
* @author Commons VFS team
*/
public class ProviderConfiguration
{
private String className;
private final List schemes = new ArrayList(10);
private final List dependenies = new ArrayList(10);
public ProviderConfiguration()
{
}
public String getClassName()
{
return className;
}
public void setClassName(String className)
{
this.className = className;
}
public void setScheme(String scheme)
{
schemes.add(scheme);
}
public List getSchemes()
{
return schemes;
}
public void setDependency(String dependency)
{
dependenies.add(dependency);
}
public List getDependencies()
{
return dependenies;
}
public boolean isDefault()
{
return false;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/providers.xml 100644 765 24 13630 11623215065 27002 0 ustar rgoers staff 0 0
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/Resource.java 100644 765 24 6437 11623215065 26664 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.IOException;
import java.net.URL;
import java.util.jar.Attributes;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileUtil;
/**
* Helper class for VFSClassLoader. This represents a resource loaded with
* the classloader.
*
* @author Commons VFS team
* @see VFSClassLoader
*/
class Resource
{
private final FileObject root;
private final FileObject resource;
private final FileObject packageFolder;
private final String packageName;
/**
* Creates a new instance.
*
* @param root The code source FileObject.
* @param resource The resource of the FileObject.
*/
public Resource(final String name,
final FileObject root,
final FileObject resource)
throws FileSystemException
{
this.root = root;
this.resource = resource;
packageFolder = resource.getParent();
final int pos = name.lastIndexOf('/');
if (pos == -1)
{
packageName = null;
}
else
{
packageName = name.substring(0, pos).replace('/', '.');
}
}
/**
* Returns the URL of the resource.
*/
public URL getURL() throws FileSystemException
{
return resource.getURL();
}
/**
* Returns the name of the package containing the resource.
*/
public String getPackageName()
{
return packageName;
}
/**
* Returns an attribute of the package containing the resource.
*/
public String getPackageAttribute(final Attributes.Name attrName) throws FileSystemException
{
return (String) packageFolder.getContent().getAttribute(attrName.toString());
}
/**
* Returns the folder for the package containing the resource.
*/
public FileObject getPackageFolder()
{
return packageFolder;
}
/**
* Returns the FileObject of the resource.
*/
public FileObject getFileObject()
{
return resource;
}
/**
* Returns the code source as an URL.
*/
public URL getCodeSourceURL() throws FileSystemException
{
return root.getURL();
}
/**
* Returns the data for this resource as a byte array.
*/
public byte[] getBytes() throws IOException
{
return FileUtil.getContent(resource);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/StandardFileSystemManager.java 100644 765 24 37364 11623215065 32160 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Enumeration;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.VfsLog;
import org.apache.commons.vfs2.operations.FileOperationProvider;
import org.apache.commons.vfs2.provider.FileProvider;
import org.apache.commons.vfs2.util.Messages;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
/**
* A {@link org.apache.commons.vfs2.FileSystemManager} that configures itself
* from an XML (Default: providers.xml) configuration file.
* Certain providers are only loaded and available if the dependend library is in your
* classpath. You have to configure your debugging facility to log "debug" messages to see
* if a provider was skipped due to "unresolved externals".
*
* @author Commons VFS team
*/
public class StandardFileSystemManager
extends DefaultFileSystemManager
{
private static final String CONFIG_RESOURCE = "providers.xml";
private static final String PLUGIN_CONFIG_RESOURCE = "META-INF/vfs-providers.xml";
private URL configUri;
private ClassLoader classLoader;
/**
* Sets the configuration file for this manager.
* @param configUri The URI for this manager.
*/
public void setConfiguration(final String configUri)
{
try
{
setConfiguration(new URL(configUri));
}
catch (MalformedURLException e)
{
getLogger().warn(e.getLocalizedMessage(), e);
}
}
/**
* Sets the configuration file for this manager.
* @param configUri The URI forthis manager.
*/
public void setConfiguration(final URL configUri)
{
this.configUri = configUri;
}
/**
* Sets the ClassLoader to use to load the providers. Default is to
* use the ClassLoader that loaded this class.
* @param classLoader The ClassLoader.
*/
public void setClassLoader(final ClassLoader classLoader)
{
this.classLoader = classLoader;
}
/**
* Initializes this manager. Adds the providers and replicator.
* @throws FileSystemException if an error occurs.
*/
@Override
public void init() throws FileSystemException
{
// Set the replicator and temporary file store (use the same component)
final DefaultFileReplicator replicator = createDefaultFileReplicator();
setReplicator(new PrivilegedFileReplicator(replicator));
setTemporaryFileStore(replicator);
/* replaced by findClassLoader
if (classLoader == null)
{
// Use default classloader
classLoader = getClass().getClassLoader();
}
*/
if (configUri == null)
{
// Use default config
final URL url = getClass().getResource(CONFIG_RESOURCE);
if (url == null)
{
throw new FileSystemException("vfs.impl/find-config-file.error", CONFIG_RESOURCE);
}
configUri = url;
}
// Configure
configure(configUri);
// Configure Plugins
configurePlugins();
// Initialise super-class
super.init();
}
/**
* Scans the classpath to find any droped plugin.
* The plugin-description has to be in /META-INF/vfs-providers.xml
* @throws FileSystemException if an error occurs.
*/
protected void configurePlugins() throws FileSystemException
{
ClassLoader cl = findClassLoader();
Enumeration enumResources;
try
{
enumResources = cl.getResources(PLUGIN_CONFIG_RESOURCE);
}
catch (IOException e)
{
throw new FileSystemException(e);
}
while (enumResources.hasMoreElements())
{
URL url = enumResources.nextElement();
configure(url);
}
}
private ClassLoader findClassLoader()
{
if (classLoader != null)
{
return classLoader;
}
ClassLoader cl = Thread.currentThread().getContextClassLoader();
if (cl == null)
{
cl = getClass().getClassLoader();
}
return cl;
}
protected DefaultFileReplicator createDefaultFileReplicator()
{
return new DefaultFileReplicator();
}
/**
* Configures this manager from an XML configuration file.
* @param configUri The URI of the configuration.
* @throws FileSystemException if an error occus.
*/
private void configure(final URL configUri) throws FileSystemException
{
InputStream configStream = null;
try
{
// Load up the config
// TODO - validate
final DocumentBuilder builder = createDocumentBuilder();
configStream = configUri.openStream();
final Element config = builder.parse(configStream).getDocumentElement();
configure(config);
}
catch (final Exception e)
{
throw new FileSystemException("vfs.impl/load-config.error", configUri.toString(), e);
}
finally
{
if (configStream != null)
{
try
{
configStream.close();
}
catch (IOException e)
{
getLogger().warn(e.getLocalizedMessage(), e);
}
}
}
}
/**
* Configures this manager from an XML configuration file.
* @param configUri The URI of the configuration.
* @param configStream An InputStream containing the configuration.
* @throws FileSystemException if an error occurs.
*/
@SuppressWarnings("unused")
private void configure(final String configUri, final InputStream configStream)
throws FileSystemException
{
try
{
// Load up the config
// TODO - validate
final DocumentBuilder builder = createDocumentBuilder();
final Element config = builder.parse(configStream).getDocumentElement();
configure(config);
}
catch (final Exception e)
{
throw new FileSystemException("vfs.impl/load-config.error", configUri, e);
}
}
/**
* Configure and create a DocumentBuilder
* @return A DocumentBuilder for the configuration.
* @throws ParserConfigurationException if an error occurs.
*/
private DocumentBuilder createDocumentBuilder() throws ParserConfigurationException
{
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
factory.setIgnoringElementContentWhitespace(true);
factory.setIgnoringComments(true);
factory.setExpandEntityReferences(true);
return factory.newDocumentBuilder();
}
/**
* Configures this manager from an parsed XML configuration file
* @param config The configuration Element.
* @throws FileSystemException if an error occurs.
*/
private void configure(final Element config) throws FileSystemException
{
// Add the providers
final NodeList providers = config.getElementsByTagName("provider");
final int count = providers.getLength();
for (int i = 0; i < count; i++)
{
final Element provider = (Element) providers.item(i);
addProvider(provider, false);
}
// Add the operation providers
final NodeList operationProviders = config.getElementsByTagName("operationProvider");
for (int i = 0; i < operationProviders.getLength(); i++)
{
final Element operationProvider = (Element) operationProviders.item(i);
addOperationProvider(operationProvider);
}
// Add the default provider
final NodeList defProviders = config.getElementsByTagName("default-provider");
if (defProviders.getLength() > 0)
{
final Element provider = (Element) defProviders.item(0);
addProvider(provider, true);
}
// Add the mime-type maps
final NodeList mimeTypes = config.getElementsByTagName("mime-type-map");
for (int i = 0; i < mimeTypes.getLength(); i++)
{
final Element map = (Element) mimeTypes.item(i);
addMimeTypeMap(map);
}
// Add the extension maps
final NodeList extensions = config.getElementsByTagName("extension-map");
for (int i = 0; i < extensions.getLength(); i++)
{
final Element map = (Element) extensions.item(i);
addExtensionMap(map);
}
}
/**
* Adds an extension map.
* @param map containing the Elements.
*/
private void addExtensionMap(final Element map)
{
final String extension = map.getAttribute("extension");
final String scheme = map.getAttribute("scheme");
if (scheme != null && scheme.length() > 0)
{
addExtensionMap(extension, scheme);
}
}
/**
* Adds a mime-type map.
* @param map containing the Elements.
*/
private void addMimeTypeMap(final Element map)
{
final String mimeType = map.getAttribute("mime-type");
final String scheme = map.getAttribute("scheme");
addMimeTypeMap(mimeType, scheme);
}
/**
* Adds a provider from a provider definition.
* @param providerDef the provider definition
* @param isDefault true if the default should be used.
* @throws FileSystemException if an error occurs.
*/
private void addProvider(final Element providerDef, final boolean isDefault)
throws FileSystemException
{
final String classname = providerDef.getAttribute("class-name");
// Make sure all required schemes are available
final String[] requiredSchemes = getRequiredSchemes(providerDef);
for (int i = 0; i < requiredSchemes.length; i++)
{
final String requiredScheme = requiredSchemes[i];
if (!hasProvider(requiredScheme))
{
final String msg = Messages.getString("vfs.impl/skipping-provider-scheme.debug",
new String[]{classname, requiredScheme});
VfsLog.debug(getLogger(), getLogger(), msg);
return;
}
}
// Make sure all required classes are in classpath
final String[] requiredClasses = getRequiredClasses(providerDef);
for (int i = 0; i < requiredClasses.length; i++)
{
final String requiredClass = requiredClasses[i];
if (!findClass(requiredClass))
{
final String msg = Messages.getString("vfs.impl/skipping-provider.debug",
new String[]{classname, requiredClass});
VfsLog.debug(getLogger(), getLogger(), msg);
return;
}
}
// Create and register the provider
final FileProvider provider = (FileProvider) createInstance(classname);
final String[] schemas = getSchemas(providerDef);
if (schemas.length > 0)
{
addProvider(schemas, provider);
}
// Set as default, if required
if (isDefault)
{
setDefaultProvider(provider);
}
}
/**
* Adds a operationProvider from a operationProvider definition.
*/
private void addOperationProvider(final Element providerDef) throws FileSystemException
{
final String classname = providerDef.getAttribute("class-name");
// Attach only to available schemas
final String[] schemas = getSchemas(providerDef);
for (int i = 0; i < schemas.length; i++)
{
final String schema = schemas[i];
if (hasProvider(schema))
{
final FileOperationProvider operationProvider = (FileOperationProvider) createInstance(classname);
addOperationProvider(schema, operationProvider);
}
}
}
/**
* Tests if a class is available.
*/
private boolean findClass(final String className)
{
try
{
findClassLoader().loadClass(className);
return true;
}
catch (final ClassNotFoundException e)
{
return false;
}
}
/**
* Extracts the required classes from a provider definition.
*/
private String[] getRequiredClasses(final Element providerDef)
{
final ArrayList classes = new ArrayList();
final NodeList deps = providerDef.getElementsByTagName("if-available");
final int count = deps.getLength();
for (int i = 0; i < count; i++)
{
final Element dep = (Element) deps.item(i);
String className = dep.getAttribute("class-name");
if (className != null && className.length() > 0)
{
classes.add(className);
}
}
return classes.toArray(new String[classes.size()]);
}
/**
* Extracts the required schemes from a provider definition.
*/
private String[] getRequiredSchemes(final Element providerDef)
{
final ArrayList schemes = new ArrayList();
final NodeList deps = providerDef.getElementsByTagName("if-available");
final int count = deps.getLength();
for (int i = 0; i < count; i++)
{
final Element dep = (Element) deps.item(i);
String scheme = dep.getAttribute("scheme");
if (scheme != null && scheme.length() > 0)
{
schemes.add(scheme);
}
}
return schemes.toArray(new String[schemes.size()]);
}
/**
* Extracts the schema names from a provider definition.
*/
private String[] getSchemas(final Element provider)
{
final ArrayList schemas = new ArrayList();
final NodeList schemaElements = provider.getElementsByTagName("scheme");
final int count = schemaElements.getLength();
for (int i = 0; i < count; i++)
{
final Element scheme = (Element) schemaElements.item(i);
schemas.add(scheme.getAttribute("name"));
}
return schemas.toArray(new String[schemas.size()]);
}
/**
* Creates a provider.
*/
private Object createInstance(final String className)
throws FileSystemException
{
try
{
final Class> clazz = findClassLoader().loadClass(className);
return clazz.newInstance();
}
catch (final Exception e)
{
throw new FileSystemException("vfs.impl/create-provider.error", className, e);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/SynchronizedFileObject.java 100644 765 24 12257 11623215065 31520 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.util.List;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.NameScope;
/**
* This decorator synchronize all access to the FileObject.
*
* @author Commons VFS team
*/
public class SynchronizedFileObject extends DecoratedFileObject
{
public SynchronizedFileObject(FileObject fileObject)
{
super(fileObject);
}
@Override
public void close() throws FileSystemException
{
synchronized (this)
{
super.close();
}
}
@Override
public void copyFrom(FileObject srcFile, FileSelector selector) throws FileSystemException
{
synchronized (this)
{
super.copyFrom(srcFile, selector);
}
}
@Override
public void createFile() throws FileSystemException
{
synchronized (this)
{
super.createFile();
}
}
@Override
public void createFolder() throws FileSystemException
{
synchronized (this)
{
super.createFolder();
}
}
@Override
public boolean delete() throws FileSystemException
{
synchronized (this)
{
return super.delete();
}
}
@Override
public int delete(FileSelector selector) throws FileSystemException
{
synchronized (this)
{
return super.delete(selector);
}
}
@Override
public boolean exists() throws FileSystemException
{
synchronized (this)
{
return super.exists();
}
}
@Override
public void findFiles(FileSelector selector, boolean depthwise, List selected)
throws FileSystemException
{
synchronized (this)
{
super.findFiles(selector, depthwise, selected);
}
}
@Override
public FileObject[] findFiles(FileSelector selector) throws FileSystemException
{
synchronized (this)
{
return super.findFiles(selector);
}
}
@Override
public FileObject getChild(String name) throws FileSystemException
{
synchronized (this)
{
return super.getChild(name);
}
}
@Override
public FileObject[] getChildren() throws FileSystemException
{
synchronized (this)
{
return super.getChildren();
}
}
@Override
public FileContent getContent() throws FileSystemException
{
synchronized (this)
{
return super.getContent();
}
}
@Override
public FileType getType() throws FileSystemException
{
synchronized (this)
{
return super.getType();
}
}
@Override
public boolean isHidden() throws FileSystemException
{
synchronized (this)
{
return super.isHidden();
}
}
@Override
public boolean isReadable() throws FileSystemException
{
synchronized (this)
{
return super.isReadable();
}
}
@Override
public boolean isWriteable() throws FileSystemException
{
synchronized (this)
{
return super.isWriteable();
}
}
@Override
public void moveTo(FileObject destFile) throws FileSystemException
{
synchronized (this)
{
super.moveTo(destFile);
}
}
@Override
public FileObject resolveFile(String name, NameScope scope) throws FileSystemException
{
synchronized (this)
{
return super.resolveFile(name, scope);
}
}
@Override
public FileObject resolveFile(String path) throws FileSystemException
{
synchronized (this)
{
return super.resolveFile(path);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/URLStreamHandlerProxy.java 100644 765 24 4170 11623215065 31243 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
/**
* A proxy for URLs that are supported by the standard stream handler factory.
*
* @author Commons VFS team
*/
class URLStreamHandlerProxy
extends URLStreamHandler
{
@Override
protected URLConnection openConnection(final URL url)
throws IOException
{
final URL proxyURL = new URL(url.toExternalForm());
return proxyURL.openConnection();
}
@Override
protected void parseURL(final URL u,
final String spec,
final int start,
final int limit)
{
try
{
final URL url = new URL(u, spec);
setURL(u, url.getProtocol(), url.getHost(),
url.getPort(), url.getAuthority(), url.getUserInfo(),
url.getFile(), url.getQuery(), url.getRef());
}
catch (MalformedURLException mue)
{
//We retrow this as a simple runtime exception.
//It is retrown in URL as a MalformedURLException anyway.
throw new RuntimeException(mue.getMessage());
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/VFSClassLoader.java 100644 765 24 32672 11623215065 27670 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.io.IOException;
import java.net.URL;
import java.security.CodeSource;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.Permissions;
import java.security.SecureClassLoader;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.NameScope;
/**
* A class loader that can load classes and resources from a search path
* VFS FileObjects refering both to folders and JAR files. Any FileObject
* of type FileType.FILE is asumed to be a JAR and is opened
* by creating a layered file system with the "jar" scheme.
* TODO - Test this with signed Jars and a SecurityManager.
*
* @author Commons VFS team
* @see FileSystemManager#createFileSystem
*/
public class VFSClassLoader extends SecureClassLoader
{
private final ArrayList resources = new ArrayList();
/**
* Constructors a new VFSClassLoader for the given file.
*
* @param file the file to load the classes and resources from.
* @param manager the FileManager to use when trying create a layered Jar file
* system.
* @throws FileSystemException if an error occurs.
*/
public VFSClassLoader(final FileObject file,
final FileSystemManager manager)
throws FileSystemException
{
this(new FileObject[]{file}, manager, null);
}
/**
* Constructors a new VFSClassLoader for the given file.
*
* @param file the file to load the classes and resources from.
* @param manager the FileManager to use when trying create a layered Jar file
* system.
* @param parent the parent class loader for delegation.
* @throws FileSystemException if an error occurs.
*/
public VFSClassLoader(final FileObject file,
final FileSystemManager manager,
final ClassLoader parent)
throws FileSystemException
{
this(new FileObject[]{file}, manager, parent);
}
/**
* Constructors a new VFSClassLoader for the given files. The files will
* be searched in the order specified.
*
* @param files the files to load the classes and resources from.
* @param manager the FileManager to use when trying create a layered Jar file
* system.
* @throws FileSystemException if an error occurs.
*/
public VFSClassLoader(final FileObject[] files,
final FileSystemManager manager)
throws FileSystemException
{
this(files, manager, null);
}
/**
* Constructors a new VFSClassLoader for the given FileObjects.
* The FileObjects will be searched in the order specified.
*
* @param files the FileObjects to load the classes and resources from.
* @param manager the FileManager to use when trying create a layered Jar file
* system.
* @param parent the parent class loader for delegation.
* @throws FileSystemException if an error occurs.
*/
public VFSClassLoader(final FileObject[] files,
final FileSystemManager manager,
final ClassLoader parent) throws FileSystemException
{
super(parent);
addFileObjects(manager, files);
}
/**
* Provide access to the file objects this class loader represents.
* @return An array of FileObjects.
* @since 2.0
*/
public FileObject[] getFileObjects()
{
return resources.toArray(new FileObject[resources.size()]);
}
/**
* Appends the specified FileObjects to the list of FileObjects to search
* for classes and resources.
*
* @param manager The FileSystemManager.
* @param files the FileObjects to append to the search path.
* @throws FileSystemException if an error occurs.
*/
private void addFileObjects(final FileSystemManager manager,
final FileObject[] files) throws FileSystemException
{
for (int i = 0; i < files.length; i++)
{
FileObject file = files[i];
if (!file.exists())
{
// Does not exist - skip
continue;
}
// TODO - use federation instead
if (manager.canCreateFileSystem(file))
{
// Use contents of the file
file = manager.createFileSystem(file);
}
resources.add(file);
}
}
/**
* Finds and loads the class with the specified name from the search
* path.
*
* @throws ClassNotFoundException if the class is not found.
*/
@Override
protected Class> findClass(final String name) throws ClassNotFoundException
{
try
{
final String path = name.replace('.', '/').concat(".class");
final Resource res = loadResource(path);
if (res == null)
{
throw new ClassNotFoundException(name);
}
return defineClass(name, res);
}
catch (final IOException ioe)
{
throw new ClassNotFoundException(name, ioe);
}
}
/**
* Loads and verifies the class with name and located with res.
*/
private Class> defineClass(final String name, final Resource res)
throws IOException
{
final URL url = res.getCodeSourceURL();
final String pkgName = res.getPackageName();
if (pkgName != null)
{
final Package pkg = getPackage(pkgName);
if (pkg != null)
{
if (pkg.isSealed())
{
if (!pkg.isSealed(url))
{
throw new FileSystemException("vfs.impl/pkg-sealed-other-url", pkgName);
}
}
else
{
if (isSealed(res))
{
throw new FileSystemException("vfs.impl/pkg-sealing-unsealed", pkgName);
}
}
}
else
{
definePackage(pkgName, res);
}
}
final byte[] bytes = res.getBytes();
final Certificate[] certs =
res.getFileObject().getContent().getCertificates();
final CodeSource cs = new CodeSource(url, certs);
return defineClass(name, bytes, 0, bytes.length, cs);
}
/**
* Returns true if the we should seal the package where res resides.
*/
private boolean isSealed(final Resource res)
throws FileSystemException
{
final String sealed = res.getPackageAttribute(Attributes.Name.SEALED);
return "true".equalsIgnoreCase(sealed);
}
/**
* Reads attributes for the package and defines it.
*/
private Package definePackage(final String name,
final Resource res)
throws FileSystemException
{
// TODO - check for MANIFEST_ATTRIBUTES capability first
final String specTitle = res.getPackageAttribute(Name.SPECIFICATION_TITLE);
final String specVendor = res.getPackageAttribute(Attributes.Name.SPECIFICATION_VENDOR);
final String specVersion = res.getPackageAttribute(Name.SPECIFICATION_VERSION);
final String implTitle = res.getPackageAttribute(Name.IMPLEMENTATION_TITLE);
final String implVendor = res.getPackageAttribute(Name.IMPLEMENTATION_VENDOR);
final String implVersion = res.getPackageAttribute(Name.IMPLEMENTATION_VERSION);
final URL sealBase;
if (isSealed(res))
{
sealBase = res.getCodeSourceURL();
}
else
{
sealBase = null;
}
return definePackage(name, specTitle, specVersion, specVendor,
implTitle, implVersion, implVendor, sealBase);
}
/**
* Calls super.getPermissions both for the code source and also
* adds the permissions granted to the parent layers.
* @param cs the CodeSource.
* @return The PermissionCollections.
*/
@Override
protected PermissionCollection getPermissions(final CodeSource cs)
{
try
{
final String url = cs.getLocation().toString();
FileObject file = lookupFileObject(url);
if (file == null)
{
return super.getPermissions(cs);
}
FileObject parentLayer = file.getFileSystem().getParentLayer();
if (parentLayer == null)
{
return super.getPermissions(cs);
}
Permissions combi = new Permissions();
PermissionCollection permCollect = super.getPermissions(cs);
copyPermissions(permCollect, combi);
for (FileObject parent = parentLayer;
parent != null;
parent = parent.getFileSystem().getParentLayer())
{
final CodeSource parentcs =
new CodeSource(parent.getURL(),
parent.getContent().getCertificates());
permCollect = super.getPermissions(parentcs);
copyPermissions(permCollect, combi);
}
return combi;
}
catch (final FileSystemException fse)
{
throw new SecurityException(fse.getMessage());
}
}
/**
* Copies the permissions from src to dest.
* @param src The source PermissionCollection.
* @param dest The destination PermissionCollection.
*/
protected void copyPermissions(final PermissionCollection src,
final PermissionCollection dest)
{
for (Enumeration elem = src.elements(); elem.hasMoreElements();)
{
final Permission permission = elem.nextElement();
dest.add(permission);
}
}
/**
* Does a reverse lookup to find the FileObject when we only have the
* URL.
*/
private FileObject lookupFileObject(final String name)
{
final Iterator it = resources.iterator();
while (it.hasNext())
{
final FileObject object = it.next();
if (name.equals(object.getName().getURI()))
{
return object;
}
}
return null;
}
/**
* Finds the resource with the specified name from the search path.
* This returns null if the resource is not found.
* @param name The resource name.
* @return The URL that matches the resource.
*/
@Override
protected URL findResource(final String name)
{
try
{
final Resource res = loadResource(name);
if (res != null)
{
return res.getURL();
}
}
catch (final Exception mue)
{
// Ignore
// TODO - report?
}
return null;
}
/**
* Returns an Enumeration of all the resources in the search path
* with the specified name.
* TODO - Implement this.
* @param name The resources to find.
* @return An Enumeration of the resources associated with the name.
*/
@Override
protected Enumeration findResources(final String name)
{
return new Enumeration()
{
public boolean hasMoreElements()
{
return false;
}
public URL nextElement()
{
return null;
}
};
}
/**
* Searches through the search path of for the first class or resource
* with specified name.
* @param name The resource to load.
* @return The Resource.
* @throws FileSystemException if an error occurs.
*/
private Resource loadResource(final String name) throws FileSystemException
{
final Iterator it = resources.iterator();
while (it.hasNext())
{
final FileObject baseFile = it.next();
final FileObject file =
baseFile.resolveFile(name, NameScope.DESCENDENT_OR_SELF);
if (file.exists())
{
return new Resource(name, baseFile, file);
}
}
return null;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileName.java 100644 765 24 3162 11623215065 30114 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
/**
* A simple Filename to hold the scheme for to be created virtual filesytsem.
*
* @author Commons VFS team
*/
public class VirtualFileName extends AbstractFileName
{
public VirtualFileName(final String scheme, final String absPath, final FileType type)
{
super(scheme, absPath, type);
}
@Override
public FileName createName(String absPath, FileType type)
{
return new VirtualFileName(getScheme(), absPath, type);
}
@Override
protected void appendRootUri(StringBuilder buffer, boolean addPassword)
{
buffer.append(getScheme());
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileProvider.java 100644 765 24 5446 11623215065 31035 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractVfsContainer;
/**
* A virtual filesystem provider.
*
* @author Commons VFS team
*/
public class VirtualFileProvider extends AbstractVfsContainer
{
/**
* Creates a virtual file system, with the supplied file as its root.
* @param rootFile The root of the file system.
* @return A FileObject in the FileSystem.
* @throws FileSystemException if an error occurs.
*/
public FileObject createFileSystem(final FileObject rootFile) throws FileSystemException
{
final AbstractFileName rootName = (AbstractFileName)
getContext().getFileSystemManager().resolveName(rootFile.getName(), FileName.ROOT_PATH);
// final FileName rootName =
// new BasicFileName(rootFile.getName(), FileName.ROOT_PATH);
final VirtualFileSystem fs = new VirtualFileSystem(rootName, rootFile.getFileSystem().getFileSystemOptions());
addComponent(fs);
fs.addJunction(FileName.ROOT_PATH, rootFile);
return fs.getRoot();
}
/**
* Creates an empty virtual file system.
* @param rootUri The root of the file system.
* @return A FileObject in the FileSystem.
* @throws FileSystemException if an error occurs.
*/
public FileObject createFileSystem(final String rootUri) throws FileSystemException
{
final AbstractFileName rootName =
new VirtualFileName(rootUri, FileName.ROOT_PATH, FileType.FOLDER);
// final FileName rootName =
// new BasicFileName(rootUri, FileName.ROOT_PATH);
final VirtualFileSystem fs = new VirtualFileSystem(rootName, null);
addComponent(fs);
return fs.getRoot();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/impl/VirtualFileSystem.java 100644 765 24 16115 11623215065 30542 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.impl;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
import org.apache.commons.vfs2.provider.DelegateFileObject;
/**
* A logical file system, made up of set of junctions, or links, to files from
* other file systems.
*
* @author Commons VFS team
* @todo Handle nested junctions.
*/
public class VirtualFileSystem extends AbstractFileSystem
{
private final Map junctions = new HashMap();
public VirtualFileSystem(final AbstractFileName rootName, final FileSystemOptions fileSystemOptions)
{
super(rootName, null, fileSystemOptions);
}
/**
* Adds the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
// TODO - this isn't really true
caps.add(Capability.ATTRIBUTES);
caps.add(Capability.CREATE);
caps.add(Capability.DELETE);
caps.add(Capability.GET_TYPE);
caps.add(Capability.JUNCTIONS);
caps.add(Capability.GET_LAST_MODIFIED);
caps.add(Capability.SET_LAST_MODIFIED_FILE);
caps.add(Capability.SET_LAST_MODIFIED_FOLDER);
caps.add(Capability.LIST_CHILDREN);
caps.add(Capability.READ_CONTENT);
caps.add(Capability.SIGNING);
caps.add(Capability.WRITE_CONTENT);
caps.add(Capability.APPEND_CONTENT);
}
/**
* Creates a file object. This method is called only if the requested
* file is not cached.
*/
@Override
protected FileObject createFile(final AbstractFileName name) throws Exception
{
// Find the file that the name points to
final FileName junctionPoint = getJunctionForFile(name);
final FileObject file;
if (junctionPoint != null)
{
// Resolve the real file
final FileObject junctionFile = junctions.get(junctionPoint);
final String relName = junctionPoint.getRelativeName(name);
file = junctionFile.resolveFile(relName, NameScope.DESCENDENT_OR_SELF);
}
else
{
file = null;
}
// Return a wrapper around the file
return new DelegateFileObject(name, this, file);
}
/**
* Adds a junction to this file system.
* @param junctionPoint The location of the junction.
* @param targetFile The target file to base the junction on.
* @throws FileSystemException if an error occurs.
*/
@Override
public void addJunction(final String junctionPoint,
final FileObject targetFile)
throws FileSystemException
{
final FileName junctionName = getFileSystemManager().resolveName(getRootName(), junctionPoint);
// Check for nested junction - these are not supported yet
if (getJunctionForFile(junctionName) != null)
{
throw new FileSystemException("vfs.impl/nested-junction.error", junctionName);
}
try
{
// Add to junction table
junctions.put(junctionName, targetFile);
// Attach to file
final DelegateFileObject junctionFile = (DelegateFileObject) getFileFromCache(junctionName);
if (junctionFile != null)
{
junctionFile.setFile(targetFile);
}
// Create ancestors of junction point
FileName childName = junctionName;
boolean done = false;
for (AbstractFileName parentName = (AbstractFileName) childName.getParent();
!done && parentName != null;
childName = parentName, parentName = (AbstractFileName) parentName.getParent())
{
DelegateFileObject file = (DelegateFileObject) getFileFromCache(parentName);
if (file == null)
{
file = new DelegateFileObject(parentName, this, null);
putFileToCache(file);
}
else
{
done = file.exists();
}
// As this is the parent of our junction it has to be a folder
file.attachChild(childName, FileType.FOLDER);
}
// TODO - attach all cached children of the junction point to their real file
}
catch (final Exception e)
{
throw new FileSystemException("vfs.impl/create-junction.error", junctionName, e);
}
}
/**
* Removes a junction from this file system.
* @param junctionPoint The junction to remove.
* @throws FileSystemException if an error occurs.
*/
@Override
public void removeJunction(final String junctionPoint)
throws FileSystemException
{
final FileName junctionName = getFileSystemManager().resolveName(getRootName(), junctionPoint);
junctions.remove(junctionName);
// TODO - remove from parents of junction point
// TODO - detach all cached children of the junction point from their real file
}
/**
* Locates the junction point for the junction containing the given file.
* @param name The FileName.
* @return the FileName where the junction occurs.
*/
private FileName getJunctionForFile(final FileName name)
{
if (junctions.containsKey(name))
{
// The name points to the junction point directly
return name;
}
// Find matching junction
for (Iterator iterator = junctions.keySet().iterator(); iterator.hasNext();)
{
final FileName junctionPoint = iterator.next();
if (junctionPoint.isDescendent(name))
{
return junctionPoint;
}
}
// None
return null;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/NameScope.java 100644 765 24 6042 11623215066 25777 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* An enumerated type for file name scope, used when resolving a name relative
* to a file.
*
* @author Commons VFS team
*/
public enum NameScope
{
/**
* Resolve against the children of the base file. The name is resolved
* as described by {@link #FILE_SYSTEM}. However, an exception is
* thrown if the resolved file is not a direct child of the base file.
*/
CHILD("child"),
/**
* Resolve against the descendents of the base file. The name is resolved
* as described by {@link #FILE_SYSTEM}. However, an exception is thrown
* if the resolved file is not a descendent of the base file.
*/
DESCENDENT("descendent"),
/**
* Resolve against the descendents of the base file. The name is resolved
* as described by {@link #FILE_SYSTEM}. However, an exception is thrown
* if the resolved file is not a descendent of the base file, or the base
* files itself.
*/
DESCENDENT_OR_SELF("descendent_or_self"),
/**
* Resolve against files in the same file system as the base file.
*
* If the supplied name is an absolute path, then it is resolved
* relative to the root of the file system that the base file belongs to.
* If a relative name is supplied, then it is resolved relative to the base
* file.
*
* The path may use any mix of /
, \
, or file
* system specific separators to separate elements in the path. It may
* also contain .
and ..
elements.
*
* A path is considered absolute if it starts with a separator character,
* and relative if it does not.
*/
FILE_SYSTEM("filesystem");
/** The name */
private final String realName;
private NameScope(final String name)
{
this.realName = name;
}
/**
* Returns the name of the scope.
* @return The name of the scope.
*/
@Override
public String toString()
{
return realName;
}
/**
* Returns the name of the scope.
* @return The name of the scope.
*/
public String getName()
{
return realName;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperation.java 100644 765 24 2754 11623215064 32540 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations;
import org.apache.commons.vfs2.FileObject;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public abstract class AbstractFileOperation implements FileOperation
{
/**
* FileObject which the FileOperation is operate on.
*/
private final FileObject fileObject;
/**
* @param file The FileObject.
*/
public AbstractFileOperation(final FileObject file)
{
fileObject = file;
}
/**
* @return an instance of FileObject which this FileOperation is operate on.
*/
protected FileObject getFileObject()
{
return fileObject;
}
}
././@LongLink 100644 0 0 151 11623215455 10254 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/AbstractFileOperationProvider.100644 765 24 12611 11623215064 33422 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public abstract class AbstractFileOperationProvider implements FileOperationProvider
{
/**
* Available operations. Operations could be registered for different schemes.
* Some operations can work only for "file" scheme, other - for "svnhttp(s)",
* "svn", "svnssh", but not for "file", etc. The Map has scheme as a key and
* Colleaction of operations that are available for that scheme.
*/
private final Collection> operations =
new ArrayList>();
/**
* Gather available operations for the specified FileObject and put them into
* specified operationsList.
*
* @param operationsList
* the list of available operations for the specivied FileObject.
* The operationList contains classes of available operations, e.g.
* Class objects.
* @param file
* the FileObject for which we want to get the list of available
* operations.
* @throws org.apache.commons.vfs2.FileSystemException
* if list of operations cannto be retrieved.
*/
public final void collectOperations(final Collection> operationsList,
final FileObject file) throws FileSystemException
{
doCollectOperations(operations, operationsList, file);
}
/**
*
* @throws FileSystemException
*/
protected abstract void doCollectOperations(
final Collection> availableOperations,
final Collection> resultList,
final FileObject file) throws FileSystemException;
/**
* @param file
* the FileObject for which we need a operation.
* @param operationClass
* the Class which instance we are needed.
* @return the requried operation instance.
* @throws org.apache.commons.vfs2.FileSystemException
* if operation cannot be retrieved.
*/
public final FileOperation getOperation(FileObject file, Class extends FileOperation> operationClass)
throws FileSystemException
{
Class extends FileOperation> implementation = lookupOperation(operationClass);
FileOperation operationInstance = instantiateOperation(file, implementation);
return operationInstance;
}
/**
*
* @param operationClass
* @return
* @throws FileSystemException
*/
protected abstract FileOperation instantiateOperation(final FileObject file,
final Class extends FileOperation> operationClass) throws FileSystemException;
/**
*
* @param operationClass
* @return never returns null
*/
protected final Class extends FileOperation> lookupOperation(final Class extends FileOperation> operationClass)
throws FileSystemException
{
// check validity of passed class
if (!FileOperation.class.isAssignableFrom(operationClass))
{
throw new FileSystemException("vfs.operation/wrong-type.error", operationClass);
}
// find appropriate class
Class extends FileOperation> foundClass = null;
Iterator> iterator = operations.iterator();
while (iterator.hasNext())
{
Class extends FileOperation> operation = iterator.next();
if (operationClass.isAssignableFrom(operation))
{
foundClass = operation;
break;
}
}
if (foundClass == null)
{
throw new FileSystemException("vfs.operation/not-found.error", operationClass);
}
return foundClass;
}
/**
*
* @param operationClass
* @throws FileSystemException
*/
protected final void addOperation(final Class extends FileOperation> operationClass)
throws FileSystemException
{
// check validity of passed class
if (!FileOperation.class.isAssignableFrom(operationClass))
{
throw new FileSystemException("vfs.operation/cant-register.error", operationClass);
}
// ok, lets add it to the list
operations.add(operationClass);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/DefaultFileOperations.java 100644 765 24 10770 11623215064 32561 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public class DefaultFileOperations implements FileOperations
{
/**
*
*/
private final FileSystemManager fsmanager;
/**
*
*/
private final FileObject fileObject;
/**
*
* @param file The file.
*/
public DefaultFileOperations(final FileObject file)
{
fileObject = file;
fsmanager = file.getFileSystem().getFileSystemManager();
}
/**
* @return The operation classes.
* @throws FileSystemException If an error occurs.
*
*/
public Class extends FileOperation>[] getOperations() throws FileSystemException
{
final String scheme = fileObject.getURL().getProtocol();
final FileOperationProvider[] providers = fsmanager
.getOperationProviders(scheme);
if (providers == null)
{
return null;
}
final List> operations = new ArrayList>();
for (int i = 0; i < providers.length; i++)
{
FileOperationProvider provider = providers[i];
provider.collectOperations(operations, fileObject);
}
@SuppressWarnings("unchecked")
Class extends FileOperation>[] array =
(Class extends FileOperation>[]) operations.toArray(new Class>[] {});
return array;
}
/**
* @param operationClass The Class that performs the operation.
* @return The FileOperation.
* @throws FileSystemException if an error occurs.
*
*/
public FileOperation getOperation(Class extends FileOperation> operationClass)
throws FileSystemException
{
final String scheme = fileObject.getURL().getProtocol();
final FileOperationProvider[] providers = fsmanager
.getOperationProviders(scheme);
if (providers == null)
{
throw new FileSystemException(
"vfs.provider/operation-not-supported.error", operationClass);
}
FileOperation resultOperation = null;
for (int i = 0; i < providers.length; i++)
{
FileOperationProvider provider = providers[i];
resultOperation = provider.getOperation(fileObject, operationClass);
if (resultOperation != null)
{
break;
}
}
if (resultOperation == null)
{
throw new FileSystemException(
"vfs.provider/operation-not-supported.error", operationClass);
}
return resultOperation;
}
/**
* @param operationClass the operation's class.
* @return true if the operation of specified class is supported for current
* FileObject and false otherwise.
*
* @throws FileSystemException if an error occurs.
*
*/
public boolean hasOperation(Class extends FileOperation> operationClass) throws FileSystemException
{
Class extends FileOperation>[] operations = getOperations();
if (operations == null)
{
return false;
}
for (int i = 0; i < operations.length; i++)
{
Class extends FileOperation> operation = operations[i];
if (operationClass.isAssignableFrom(operation))
{
return true;
}
}
return false;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/FileOperation.java 100644 765 24 4317 11623215064 31051 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations;
import org.apache.commons.vfs2.FileSystemException;
/**
*
* A FileOperation is an object that brings an extra functions to a FileObject.
* The VFS provides the basic functionality to deal with FileObject's. Tha is
* create, delete, rename, copy, etc functions. However, if you are working with
* FileSystem and its files are, for example, under Version Control System (VCS)
* you might want to get an access to the versioning framework and to be able to
* manage your files regarding VCS (e.g. commit them, undate, get logs, etc.).
* Such type of extended functionality is provided by FileOperation.
*
*
* The FileOperation interface is a genetic interface that should not be
* implemented directly. It rather should be extended by other interfaces that
* provide some concrete functions.
*
*
* FileOperation is provided by
*
* @see FileOperationProvider Especially the FileOperationProvider is responsible
* for looking up and instantiating any concrete FileOperation.
*
*
* @author Commons VFS team
* @since 0.1
*/
public interface FileOperation
{
/**
* Performs necessary actions that are related to the concrete
* implementation of a FileOperation.
*
* @throws FileSystemException if an error occurs
*/
void process() throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/FileOperationProvider.java 100644 765 24 4603 11623215064 32562 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations;
import java.util.Collection;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
/**
* FileOperationProvider is responsible for dealing with FileOperation's.
*
* @author Commons VFS team
* @since 0.1
*/
public interface FileOperationProvider
{
/**
* Gather available operations for the specified FileObject and put them into
* specified operationsList.
*
* @param operationsList
* the list of available operations for the specivied FileObject.
* The operationList contains classes of available operations, e.g.
* Class objects.
* @param file
* the FileObject for which we want to get the list of available
* operations.
*
* @throws FileSystemException
* if list of operations cannto be retrieved.
*/
void collectOperations(final Collection> operationsList, final FileObject file)
throws FileSystemException;
/**
*
* @param file
* the FileObject for which we need a operation.
* @param operationClass
* the Class which instance we are needed.
* @return the requried operation instance. s
* @throws FileSystemException
* if operation cannot be retrieved.
*/
FileOperation getOperation(final FileObject file, final Class extends FileOperation> operationClass)
throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/FileOperations.java 100644 765 24 3714 11623215064 31234 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations;
import org.apache.commons.vfs2.FileSystemException;
/**
* FileOperations interface provides API to work with operations.
*
* @see FileOperation on what a operation in the context of VFS is.
*
* @author Commons VFS team
* @since 0.1
*/
public interface FileOperations
{
/**
* @return all operations associated with the fileObject
* @throws FileSystemException if an error occurs.
*/
Class extends FileOperation>[] getOperations() throws FileSystemException;
/**
* @param operationClass the operation Class.
* @return a operation implementing the given operationClass
* @throws FileSystemException if an error occus.
*/
FileOperation getOperation(Class extends FileOperation> operationClass) throws FileSystemException;
/**
* @param operationClass the operation Class.
* @return if a operation operationClass
is available
* @throws FileSystemException if an error ocurs.
*/
boolean hasOperation(Class extends FileOperation> operationClass) throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/package.html 100644 765 24 1534 11623215064 27725 0 ustar rgoers staff 0 0
VFS Operations handling.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/package.html 100644 765 24 1543 11623215064 30520 0 ustar rgoers staff 0 0
VFS version control operations.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/readme.html 100644 765 24 2245 11623215064 30362 0 ustar rgoers staff 0 0
This package contains common interfaces for Version Control Systems such as
SVN, CVS, etc.
The implementation of that interfaces it a system-specific deal and all
implementations are located in the corresponding packages for those concrete
systems.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsAdd.java 100644 765 24 2515 11623215064 30246 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.operations.FileOperation;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsAdd extends FileOperation
{
/**
*
* @param makedir true if directories should be created, false otherwise.
*/
void setMakedir(final boolean makedir);
/**
*
* @param recursive true if subdirectories should be processed.
*/
void setRecursive(final boolean recursive);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCheckout.java 100644 765 24 3427 11623215064 31326 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.operations.FileOperation;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsCheckout extends FileOperation
{
/**
*
* @param revision The revision number.
*/
void setRevision(final long revision);
/**
*
* @param recursive true if directories should be traversed.
*/
void setRecursive(final boolean recursive);
/**
*
* @param targetDir directory under which retrieved files should be placed.
*/
void setTargetDirectory(final FileObject targetDir);
/**
* @param export
* if true, administrative .svn directoies will not be created on
* the retrieved tree. The checkout operation in this case is
* equivalent to export function.
*/
void setExport(final boolean export);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommit.java 100644 765 24 3106 11623215064 31003 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.operations.FileOperation;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsCommit extends FileOperation
{
/**
*
* @param isRecursive true if directories should be traversed.
*/
void setRecursive(final boolean isRecursive);
/**
*
* @param message The message.
*/
void setMessage(final String message);
/**
*
* @param listener Listener that is given control when a commit occurs.
*/
void addCommitListener(final VcsCommitListener listener);
/**
*
* @param listener The Listener.
*/
void removeCommitListener(final VcsCommitListener listener);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsCommitListener.java 100644 765 24 2214 11623215064 32510 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsCommitListener
{
/**
*
* @param path The path.
* @param contentStatus The status;
*/
void commited(final String path, final VcsStatus contentStatus);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsDelete.java 100644 765 24 2262 11623215064 30757 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.operations.FileOperation;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsDelete extends FileOperation
{
/**
*
* @param force true if the delete should be unconditional.
*/
void setForce(final boolean force);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLog.java 100644 765 24 2620 11623215064 30274 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.operations.FileOperation;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsLog extends FileOperation
{
/**
*
* @param startRev The start revision.
*/
void setStartRevision(final long startRev);
/**
*
* @param endRev The end revision.
*/
void setEndRevision(final long endRev);
/**
*
* @param handler The LogEntry handler.
*/
void setLogEntryHandler(final VcsLogEntryHandler handler);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntry.java 100644 765 24 4536 11623215064 31326 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import java.util.Calendar;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public class VcsLogEntry
{
/**
*
*/
private final String author;
/**
* Revision.
*/
private final long revision;
/**
* Message.
*/
private final String message;
/**
* Date.
*/
private final Calendar date;
/**
* Path.
*/
private final String path;
/**
*
* @param author The author.
* @param revision The revision.
* @param message The message.
* @param date The date.
* @param path The path.
*/
public VcsLogEntry(final String author, final long revision,
final String message, final Calendar date, final String path)
{
this.author = author;
this.revision = revision;
this.message = message;
this.date = date;
this.path = path;
}
/**
*
* @return The author.
*/
public String getAuthor()
{
return author;
}
/**
*
* @return The revision.
*/
public long getRevision()
{
return revision;
}
/**
*
* @return The message.
*/
public String getMessage()
{
return message;
}
/**
*
* @return The date.
*/
public Calendar getDate()
{
return date;
}
/**
*
* @return The path.
*/
public String getPath()
{
return path;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsLogEntryHandler.java 100644 765 24 2337 11623215064 32621 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.FileSystemException;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsLogEntryHandler
{
/**
*
* @param entry The log entry.
* @throws FileSystemException if an error occurs.
*/
void handleLogEntry(final VcsLogEntry entry) throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsModifyListener.java 100644 765 24 2233 11623215064 32510 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsModifyListener
{
/**
*
* @param path The path String.
* @param contentStatus The content status.
*/
void modified(final String path, final VcsStatus contentStatus);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsRevert.java 100644 765 24 3205 11623215064 31022 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.operations.FileOperation;
/**
*
* Restores pristine working copy file and cancels all local modifications. In
* other words, VcsRevert replaces working copy file with the latest version
* from the repository.
*
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsRevert extends FileOperation
{
/**
*
* @param recursive true if children should be processed.
*/
void setRecursive(final boolean recursive);
/**
*
* @param listener The Listener to add.
*/
void addModifyListener(final VcsModifyListener listener);
/**
*
* @param listener The Listener to remove.
*/
void removeModifyListener(final VcsModifyListener listener);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsStatus.java 100644 765 24 3067 11623215064 31044 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public enum VcsStatus
{
UNKNOWN(-1),
NOT_MODIFIED(0),
ADDED(1),
CONFLICTED(2),
DELETED(3),
MERGED(4),
IGNORED(5),
MODIFIED(6),
REPLACED(7),
UNVERSIONED(8),
MISSING(9),
OBSTRUCTED(10),
REVERTED(11),
RESOLVED(12),
COPIED(13),
MOVED(14),
RESTORED(15),
UPDATED(16),
EXTERNAL(18),
CORRUPTED(19),
NOT_REVERTED(20);
private int status;
private VcsStatus(int status)
{
this.status = status;
}
/**
*
* @return the status of FileObject
*/
public int getStatus()
{
return status;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdate.java 100644 765 24 3035 11623215064 30776 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
import org.apache.commons.vfs2.operations.FileOperation;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsUpdate extends FileOperation
{
/**
*
* @param revision The revision number.
*/
void setRevision(final long revision);
/**
*
* @param isRecursive true if recursive.
*/
void setRecursive(final boolean isRecursive);
/**
*
* @param listener The UpdateListener.
*/
void addUpdateListener(final VcsUpdateListener listener);
/**
*
* @param listener The UpdateListener.
*/
void removeUpdateListener(final VcsUpdateListener listener);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/operations/vcs/VcsUpdateListener.java 100644 765 24 2314 11623215064 32503 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.operations.vcs;
/**
*
* @author Commons VFS team
* @since 0.1
*/
public interface VcsUpdateListener
{
/**
*
* @param path The path.
* @param revision The revision number.
* @param contentStatus The status.
*/
void updated(final String path, final long revision, final VcsStatus contentStatus);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/package.html 100644 765 24 1527 11623215066 25546 0 ustar rgoers staff 0 0
The public VFS API.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileName.java 100644 765 24 35441 11623215065 31147 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.VFS;
/**
* A default file name implementation.
*
* @author Commons VFS team
*/
public abstract class AbstractFileName implements FileName
{
private final String scheme;
private final String absPath;
private FileType type;
// Cached stuff
private String uri;
private String baseName;
private String rootUri;
private String extension;
private String decodedAbsPath;
private String key = null;
public AbstractFileName(final String scheme, final String absPath, FileType type)
{
this.rootUri = null;
this.scheme = scheme;
this.type = type;
if (absPath != null && absPath.length() > 0)
{
if (absPath.length() > 1 && absPath.endsWith("/"))
{
this.absPath = absPath.substring(0, absPath.length() - 1);
}
else
{
this.absPath = absPath;
}
}
else
{
this.absPath = ROOT_PATH;
}
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
AbstractFileName that = (AbstractFileName) o;
return (getKey().equals(that.getKey()));
}
@Override
public int hashCode()
{
return getKey().hashCode();
}
/**
* Implement Comparable.
*
* @param obj another abstractfilename
* @return negative number if less than, 0 if equal, postive if greater than.
*/
public int compareTo(FileName obj)
{
final AbstractFileName name = (AbstractFileName) obj;
return getKey().compareTo(name.getKey());
}
/**
* Returns the URI of the file.
* @return the FileName as a URI.
*/
@Override
public String toString()
{
return getURI();
}
/**
* Factory method for creating name instances.
* @param absPath The absolute path.
* @param type The FileType.
* @return The FileName.
*/
public abstract FileName createName(String absPath, FileType type);
/**
* Builds the root URI for this file name. Note that the root URI must not
* end with a separator character.
* @param buffer A StringBuilder to use to construct the URI.
* @param addPassword true if the password should be added, false otherwise.
*/
protected abstract void appendRootUri(StringBuilder buffer, boolean addPassword);
/**
* Returns the base name of the file.
* @return The base name of the file.
*/
public String getBaseName()
{
if (baseName == null)
{
final int idx = getPath().lastIndexOf(SEPARATOR_CHAR);
if (idx == -1)
{
baseName = getPath();
}
else
{
baseName = getPath().substring(idx + 1);
}
}
return baseName;
}
/**
* Returns the absolute path of the file, relative to the root of the
* file system that the file belongs to.
* @return The path String.
*/
public String getPath()
{
if (VFS.isUriStyle())
{
return absPath + getUriTrailer();
}
return absPath;
}
protected String getUriTrailer()
{
return getType().hasChildren() ? "/" : "";
}
/**
* Returns the decoded path.
* @return The decoded path String.
* @throws FileSystemException If an error occurs.
*/
public String getPathDecoded() throws FileSystemException
{
if (decodedAbsPath == null)
{
decodedAbsPath = UriParser.decode(getPath());
}
return decodedAbsPath;
}
/**
* Returns the name of the parent of the file.
* @return the FileName of the parent.
*/
public FileName getParent()
{
final String parentPath;
final int idx = getPath().lastIndexOf(SEPARATOR_CHAR);
if (idx == -1 || idx == getPath().length() - 1)
{
// No parent
return null;
}
else if (idx == 0)
{
// Root is the parent
parentPath = SEPARATOR;
}
else
{
parentPath = getPath().substring(0, idx);
}
return createName(parentPath, FileType.FOLDER);
}
/**
* find the root of the filesystem.
* @return The root FileName.
*/
public FileName getRoot()
{
FileName root = this;
while (root.getParent() != null)
{
root = root.getParent();
}
return root;
}
/**
* Returns the URI scheme of this file.
* @return The protocol used to access the file.
*/
public String getScheme()
{
return scheme;
}
/**
* Returns the absolute URI of the file.
* @return The absolute URI of the file.
*/
public String getURI()
{
if (uri == null)
{
uri = createURI();
}
return uri;
}
protected String createURI()
{
return createURI(false, true);
}
/**
* Create a path that does not use the FileType since that field is not immutable.
* @return The key.
*/
private String getKey()
{
if (key == null)
{
key = createURI(true, true);
}
return key;
}
/**
* returns a "friendly path", this is a path without a password.
* @return The "friendly" URI.
*/
public String getFriendlyURI()
{
return createURI(false, false);
}
private String createURI(boolean useAbsolutePath, boolean usePassword)
{
final StringBuilder buffer = new StringBuilder();
appendRootUri(buffer, usePassword);
buffer.append(useAbsolutePath ? absPath : getPath());
return buffer.toString();
}
/**
* Converts a file name to a relative name, relative to this file name.
* @param name The FileName.
* @return The relative path to the file.
* @throws FileSystemException if an error occurs.
*/
public String getRelativeName(final FileName name) throws FileSystemException
{
final String path = name.getPath();
// Calculate the common prefix
final int basePathLen = getPath().length();
final int pathLen = path.length();
// Deal with root
if (basePathLen == 1 && pathLen == 1)
{
return ".";
}
else if (basePathLen == 1)
{
return path.substring(1);
}
final int maxlen = Math.min(basePathLen, pathLen);
int pos = 0;
for (; pos < maxlen && getPath().charAt(pos) == path.charAt(pos); pos++)
{
}
if (pos == basePathLen && pos == pathLen)
{
// Same names
return ".";
}
else if (pos == basePathLen && pos < pathLen && path.charAt(pos) == SEPARATOR_CHAR)
{
// A descendent of the base path
return path.substring(pos + 1);
}
// Strip the common prefix off the path
final StringBuilder buffer = new StringBuilder();
if (pathLen > 1 && (pos < pathLen || getPath().charAt(pos) != SEPARATOR_CHAR))
{
// Not a direct ancestor, need to back up
pos = getPath().lastIndexOf(SEPARATOR_CHAR, pos);
buffer.append(path.substring(pos));
}
// Prepend a '../' for each element in the base path past the common
// prefix
buffer.insert(0, "..");
pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
while (pos != -1)
{
buffer.insert(0, "../");
pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
}
return buffer.toString();
}
/**
* Returns the root URI of the file system this file belongs to.
* @return The URI of the root.
*/
public String getRootURI()
{
if (rootUri == null)
{
final StringBuilder buffer = new StringBuilder();
appendRootUri(buffer, true);
buffer.append(SEPARATOR_CHAR);
rootUri = buffer.toString().intern();
}
return rootUri;
}
/**
* Returns the depth of this file name, within its file system.
* @return The depth of the file name.
*/
public int getDepth()
{
final int len = getPath().length();
if (len == 0 || (len == 1 && getPath().charAt(0) == SEPARATOR_CHAR))
{
return 0;
}
int depth = 1;
for (int pos = 0; pos > -1 && pos < len; depth++)
{
pos = getPath().indexOf(SEPARATOR_CHAR, pos + 1);
}
return depth;
}
/**
* Returns the extension of this file name.
* @return The file extension.
*/
public String getExtension()
{
if (extension == null)
{
getBaseName();
final int pos = baseName.lastIndexOf('.');
// if ((pos == -1) || (pos == baseName.length() - 1))
// imario@ops.co.at: Review of patch from adagoubard@chello.nl
// do not treat filenames like
// .bashrc c:\windows\.java c:\windows\.javaws c:\windows\.jedit c:\windows\.appletviewer
// as extension
if ((pos < 1) || (pos == baseName.length() - 1))
{
// No extension
extension = "";
}
else
{
extension = baseName.substring(pos + 1).intern();
}
}
return extension;
}
/**
* Determines if another file name is an ancestor of this file name.
* @param ancestor The FileName to check.
* @return true if the FileName is an ancestor, false otherwise.
*/
public boolean isAncestor(final FileName ancestor)
{
if (!ancestor.getRootURI().equals(getRootURI()))
{
return false;
}
return checkName(ancestor.getPath(), getPath(), NameScope.DESCENDENT);
}
/**
* Determines if another file name is a descendent of this file name.
* @param descendent The FileName to check.
* @return true if the FileName is a descendent, false otherwise.
*/
public boolean isDescendent(final FileName descendent)
{
return isDescendent(descendent, NameScope.DESCENDENT);
}
/**
* Determines if another file name is a descendent of this file name.
* @param descendent The FileName to check.
* @param scope The NameScope.
* @return true if the FileName is a descendent, false otherwise.
*/
public boolean isDescendent(final FileName descendent,
final NameScope scope)
{
if (!descendent.getRootURI().equals(getRootURI()))
{
return false;
}
return checkName(getPath(), descendent.getPath(), scope);
}
/**
* Returns the requested or current type of this name.
*
* The "requested" type is the one determined during resolving the name.
* In this case the name is a {@link FileType#FOLDER} if it ends with an "/" else
* it will be a {@link FileType#FILE}
*
*
* Once attached it will be changed to reflect the real type of this resource.
*
*
* @return {@link FileType#FOLDER} or {@link FileType#FILE}
*/
public FileType getType()
{
return type;
}
/**
* sets the type of this file e.g. when it will be attached.
*
* @param type {@link FileType#FOLDER} or {@link FileType#FILE}
* @throws FileSystemException if an error occurs.
*/
void setType(FileType type) throws FileSystemException
{
if (type != FileType.FOLDER && type != FileType.FILE && type != FileType.FILE_OR_FOLDER)
{
throw new FileSystemException("vfs.provider/filename-type.error");
}
this.type = type;
}
/**
* Checks whether a path fits in a particular scope of another path.
*
* @param basePath An absolute, normalised path.
* @param path An absolute, normalised path.
* @param scope The NameScope.
* @return true if the path fits in the scope, false otherwise.
*/
public static boolean checkName(final String basePath,
final String path,
final NameScope scope)
{
if (scope == NameScope.FILE_SYSTEM)
{
// All good
return true;
}
if (!path.startsWith(basePath))
{
return false;
}
int baseLen = basePath.length();
if (VFS.isUriStyle())
{
// strip the trailing "/"
baseLen--;
}
if (scope == NameScope.CHILD)
{
if (path.length() == baseLen
|| (baseLen > 1 && path.charAt(baseLen) != SEPARATOR_CHAR)
|| path.indexOf(SEPARATOR_CHAR, baseLen + 1) != -1)
{
return false;
}
}
else if (scope == NameScope.DESCENDENT)
{
if (path.length() == baseLen
|| (baseLen > 1 && path.charAt(baseLen) != SEPARATOR_CHAR))
{
return false;
}
}
else if (scope == NameScope.DESCENDENT_OR_SELF)
{
if (baseLen > 1
&& path.length() > baseLen
&& path.charAt(baseLen) != SEPARATOR_CHAR)
{
return false;
}
}
else if (scope != NameScope.FILE_SYSTEM)
{
throw new IllegalArgumentException();
}
return true;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileNameParser.java 100644 765 24 2243 11623215065 32276 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
/**
* Provides methods to parse a filename into a {@link org.apache.commons.vfs2.FileName}.
* @author Commons VFS team
*/
public abstract class AbstractFileNameParser implements FileNameParser
{
public boolean encodeCharacter(char ch)
{
return ch == '%';
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileObject.java 100644 765 24 160311 11623215065 31510 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessController;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.cert.Certificate;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileContentInfoFactory;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileNotFolderException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.FileUtil;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.operations.DefaultFileOperations;
import org.apache.commons.vfs2.operations.FileOperations;
import org.apache.commons.vfs2.util.FileObjectUtils;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* A partial file object implementation.
*
* @author Commons VFS team
* @todo Chop this class up - move all the protected methods to several
* interfaces, so that structure and content can be separately overridden.
* @todo Check caps in methods like getChildren(), etc, and give better error messages
* (eg 'this file type does not support listing children', vs 'this is not a folder')
*/
public abstract class AbstractFileObject implements FileObject
{
// private static final FileObject[] EMPTY_FILE_ARRAY = {};
private static final FileName[] EMPTY_FILE_ARRAY = {};
private static final int INITIAL_LISTSZ = 5;
private final AbstractFileName name;
private final AbstractFileSystem fs;
private FileContent content;
// Cached info
private boolean attached;
private FileType type;
private FileObject parent;
// Changed to hold only the name of the children and let the object
// go into the global files cache
// private FileObject[] children;
private FileName[] children;
private List objects;
/**
* FileServices instance.
*/
private FileOperations operations;
/**
*
* @param name the file name - muse be an instance of {@link AbstractFileName}
* @param fs the file system
* @throws ClassCastException if {@code name} is not an instance of {@link AbstractFileName}
*/
protected AbstractFileObject(final AbstractFileName name,
final AbstractFileSystem fs)
{
this.name = name;
this.fs = fs;
fs.fileObjectHanded(this);
}
/**
* Attaches this file object to its file resource. This method is called
* before any of the doBlah() or onBlah() methods. Sub-classes can use
* this method to perform lazy initialisation.
*
* This implementation does nothing.
* @throws Exception if an error occurs.
*/
protected void doAttach() throws Exception
{
}
/**
* Detaches this file object from its file resource.
*
* Called when this file is closed. Note that the file object may be
* reused later, so should be able to be reattached.
*
* This implementation does nothing.
* @throws Exception if an error occurs.
*/
protected void doDetach() throws Exception
{
}
/**
* Determines the type of this file. Must not return null. The return
* value of this method is cached, so the implementation can be expensive.
* @return the type of the file.
* @throws Exception if an error occurs.
*/
protected abstract FileType doGetType() throws Exception;
/**
* Determines if this file is hidden. Is only called if {@link #doGetType}
* does not return {@link FileType#IMAGINARY}.
*
* This implementation always returns false.
* @return true if the file is hidden, false otherwise.
* @throws Exception if an error occurs.
*/
protected boolean doIsHidden() throws Exception
{
return false;
}
/**
* Determines if this file can be read. Is only called if {@link #doGetType}
* does not return {@link FileType#IMAGINARY}.
*
* This implementation always returns true.
* @return true if the file is readable, false otherwise.
* @throws Exception if an error occurs.
*/
protected boolean doIsReadable() throws Exception
{
return true;
}
/**
* Determines if this file can be written to. Is only called if
* {@link #doGetType} does not return {@link FileType#IMAGINARY}.
*
* This implementation always returns true.
* @return true if the file is writable.
* @throws Exception if an error occurs.
*/
protected boolean doIsWriteable() throws Exception
{
return true;
}
/**
* Lists the children of this file. Is only called if {@link #doGetType}
* returns {@link FileType#FOLDER}. The return value of this method
* is cached, so the implementation can be expensive.
* @return a possible empty String array if the file is a directory or null or an exception if the
* file is not a directory or can't be read.
* @throws Exception if an error occurs.
*/
protected abstract String[] doListChildren() throws Exception;
/**
* Lists the children of this file. Is only called if {@link #doGetType}
* returns {@link FileType#FOLDER}. The return value of this method
* is cached, so the implementation can be expensive.
* Other than doListChildren
you could return FileObject's to e.g. reinitialize the
* type of the file.
* (Introduced for Webdav: "permission denied on resource" during getType())
* @return The children of this FileObject.
* @throws Exception if an error occurs.
*/
protected FileObject[] doListChildrenResolved() throws Exception
{
return null;
}
/**
* Deletes the file. Is only called when:
*
* {@link #doGetType} does not return {@link FileType#IMAGINARY}.
* {@link #doIsWriteable} returns true.
* This file has no children, if a folder.
*
*
* This implementation throws an exception.
* @throws Exception if an error occurs.
*/
protected void doDelete() throws Exception
{
throw new FileSystemException("vfs.provider/delete-not-supported.error");
}
/**
* Renames the file. Is only called when:
*
* {@link #doIsWriteable} returns true.
*
*
* This implementation throws an exception.
* @param newfile A FileObject with the new file name.
* @throws Exception if an error occurs.
*/
protected void doRename(FileObject newfile) throws Exception
{
throw new FileSystemException("vfs.provider/rename-not-supported.error");
}
/**
* Creates this file as a folder. Is only called when:
*
* {@link #doGetType} returns {@link FileType#IMAGINARY}.
* The parent folder exists and is writeable, or this file is the
* root of the file system.
*
*
* This implementation throws an exception.
* @throws Exception if an error occurs.
*/
protected void doCreateFolder() throws Exception
{
throw new FileSystemException("vfs.provider/create-folder-not-supported.error");
}
/**
* Called when the children of this file change. Allows subclasses to
* refresh any cached information about the children of this file.
*
* This implementation does nothing.
* @param child The name of the child that changed.
* @param newType The type of the file.
* @throws Exception if an error occurs.
*/
protected void onChildrenChanged(FileName child, FileType newType) throws Exception
{
}
/**
* Called when the type or content of this file changes.
*
* This implementation does nothing.
* @throws Exception if an error occurs.
*/
protected void onChange() throws Exception
{
}
/**
* Returns the last modified time of this file. Is only called if
* {@link #doGetType} does not return {@link FileType#IMAGINARY}.
*
* This implementation throws an exception.
* @return The last modification time.
* @throws Exception if an error occurs.
*/
protected long doGetLastModifiedTime() throws Exception
{
throw new FileSystemException("vfs.provider/get-last-modified-not-supported.error");
}
/**
* Sets the last modified time of this file. Is only called if
* {@link #doGetType} does not return {@link FileType#IMAGINARY}.
*
* This implementation throws an exception.
* @param modtime The last modification time.
* @return true if the time was set.
* @throws Exception if an error occurs.
*
*/
protected boolean doSetLastModifiedTime(final long modtime) throws Exception
{
throw new FileSystemException("vfs.provider/set-last-modified-not-supported.error");
}
/**
* Returns the attributes of this file. Is only called if {@link #doGetType}
* does not return {@link FileType#IMAGINARY}.
*
* This implementation always returns an empty map.
* @return The attributes of the file.
* @throws Exception if an error occurs.
*/
protected Map doGetAttributes() throws Exception
{
return Collections.emptyMap();
}
/**
* Sets an attribute of this file. Is only called if {@link #doGetType}
* does not return {@link FileType#IMAGINARY}.
*
* This implementation throws an exception.
* @param attrName The attribute name.
* @param value The value to be associated with the attribute name.
* @throws Exception if an error occurs.
*/
protected void doSetAttribute(final String attrName, final Object value) throws Exception
{
throw new FileSystemException("vfs.provider/set-attribute-not-supported.error");
}
/**
* Removes an attribute of this file. Is only called if {@link #doGetType}
* does not return {@link FileType#IMAGINARY}.
*
* This implementation throws an exception.
* @param attrName The name of the attribute to remove.
* @throws Exception if an error occurs.
* @since 2.0
*/
protected void doRemoveAttribute(final String attrName) throws Exception
{
throw new FileSystemException("vfs.provider/remove-attribute-not-supported.error");
}
/**
* Returns the certificates used to sign this file. Is only called if
* {@link #doGetType} does not return {@link FileType#IMAGINARY}.
*
* This implementation always returns null.
* @return The certificates used to sign the file.
* @throws Exception if an error occurs.
*/
protected Certificate[] doGetCertificates() throws Exception
{
return null;
}
/**
* Returns the size of the file content (in bytes). Is only called if
* {@link #doGetType} returns {@link FileType#FILE}.
* @return The size of the file in bytes.
* @throws Exception if an error occurs.
*/
protected abstract long doGetContentSize() throws Exception;
/**
* Creates an input stream to read the file content from. Is only called
* if {@link #doGetType} returns {@link FileType#FILE}.
*
* It is guaranteed that there are no open output streams for this file
* when this method is called.
*
* The returned stream does not have to be buffered.
* @return An InputStream to read the file content.
* @throws Exception if an error occurs.
*/
protected abstract InputStream doGetInputStream() throws Exception;
/**
* Creates access to the file for random i/o. Is only called
* if {@link #doGetType} returns {@link FileType#FILE}.
*
* It is guaranteed that there are no open output streams for this file
* when this method is called.
*
* @param mode The mode to access the file.
* @return The RandomAccessContext.
* @throws Exception if an error occurs.
*/
protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
{
throw new FileSystemException("vfs.provider/random-access-not-supported.error");
}
/**
* Creates an output stream to write the file content to. Is only
* called if:
*
* {@link #doIsWriteable} returns true.
* {@link #doGetType} returns {@link FileType#FILE}, or
* {@link #doGetType} returns {@link FileType#IMAGINARY}, and the file's
* parent exists and is a folder.
*
*
* It is guaranteed that there are no open stream (input or output) for
* this file when this method is called.
*
* The returned stream does not have to be buffered.
*
* This implementation throws an exception.
* @param bAppend true if the file should be appended to, false if it should be overwritten.
* @return An OutputStream to write to the file.
* @throws Exception if an error occurs.
*/
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
throw new FileSystemException("vfs.provider/write-not-supported.error");
}
/**
* Returns the URI of the file.
* @return The URI of the file.
*/
@Override
public String toString()
{
return name.getURI();
}
/**
* Returns the name of the file.
* @return The FileName.
*/
public FileName getName()
{
return name;
}
/**
* Returns the file system this file belongs to.
* @return The FileSystem this file is associated with.
*/
public FileSystem getFileSystem()
{
return fs;
}
/**
* Returns a URL representation of the file.
* @return The URL representation of the file.
* @throws FileSystemException if an error occurs.
*/
public URL getURL() throws FileSystemException
{
final StringBuilder buf = new StringBuilder();
try
{
return AccessController.doPrivileged(new PrivilegedExceptionAction()
{
public URL run() throws MalformedURLException
{
return new URL(UriParser.extractScheme(name.getURI(), buf), "", -1,
buf.toString(), new DefaultURLStreamHandler(fs.getContext(), fs.getFileSystemOptions()));
}
});
}
catch (final PrivilegedActionException e)
{
throw new FileSystemException("vfs.provider/get-url.error", name, e.getException());
}
}
/**
* Determines if the file exists.
* @return true if the file exists, false otherwise,
* @throws FileSystemException if an error occurs.
*/
public boolean exists() throws FileSystemException
{
return getType() != FileType.IMAGINARY;
}
/**
* Returns the file's type.
* @return The FileType.
* @throws FileSystemException if an error occurs.
*/
public FileType getType() throws FileSystemException
{
synchronized (fs)
{
attach();
// VFS-210: get the type only if requested for
try
{
if (type == null)
{
setFileType(doGetType());
}
if (type == null)
{
setFileType(FileType.IMAGINARY);
}
}
catch (Exception e)
{
throw new FileSystemException("vfs.provider/get-type.error", new Object[]{name}, e);
}
return type;
}
}
/**
* Determines if this file can be read.
* @return true if the file is a hidden file, false otherwise.
* @throws FileSystemException if an error occurs.
*/
public boolean isHidden() throws FileSystemException
{
try
{
if (exists())
{
return doIsHidden();
}
else
{
return false;
}
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/check-is-hidden.error", name, exc);
}
}
/**
* Determines if this file can be read.
* @return true if the file can be read, false otherwise.
* @throws FileSystemException if an error occurs.
*/
public boolean isReadable() throws FileSystemException
{
try
{
if (exists())
{
return doIsReadable();
}
else
{
return false;
}
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/check-is-readable.error", name, exc);
}
}
/**
* Determines if this file can be written to.
* @return true if the file can be written to, false otherwise.
* @throws FileSystemException if an error occurs.
*/
public boolean isWriteable() throws FileSystemException
{
try
{
if (exists())
{
return doIsWriteable();
}
else
{
final FileObject parent = getParent();
if (parent != null)
{
return parent.isWriteable();
}
return true;
}
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/check-is-writeable.error", name, exc);
}
}
/**
* Returns the parent of the file.
* @return the parent FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileObject getParent() throws FileSystemException
{
if (this == fs.getRoot())
{
if (fs.getParentLayer() != null)
{
// Return the parent of the parent layer
return fs.getParentLayer().getParent();
}
else
{
// Root file has no parent
return null;
}
}
synchronized (fs)
{
// Locate the parent of this file
if (parent == null)
{
parent = fs.resolveFile(name.getParent());
}
}
return parent;
}
/**
* Returns the children of the file.
* @return an array of FileObjects, one per child.
* @throws FileSystemException if an error occurs.
*/
public FileObject[] getChildren() throws FileSystemException
{
synchronized (fs)
{
// VFS-210
if (!getFileSystem().hasCapability(Capability.LIST_CHILDREN))
{
throw new FileNotFolderException(name);
}
/* VFS-210
if (!getType().hasChildren())
{
throw new FileSystemException("vfs.provider/list-children-not-folder.error", name);
}
*/
attach();
// Use cached info, if present
if (children != null)
{
return resolveFiles(children);
}
// allow the filesystem to return resolved children. e.g. prefill type for webdav
FileObject[] childrenObjects;
try
{
childrenObjects = doListChildrenResolved();
children = extractNames(childrenObjects);
}
catch (FileSystemException exc)
{
// VFS-210
throw exc;
}
catch (Exception exc)
{
throw new FileSystemException("vfs.provider/list-children.error", new Object[]{name}, exc);
}
if (childrenObjects != null)
{
return childrenObjects;
}
// List the children
final String[] files;
try
{
files = doListChildren();
}
catch (FileSystemException exc)
{
// VFS-210
throw exc;
}
catch (Exception exc)
{
throw new FileSystemException("vfs.provider/list-children.error", new Object[]{name}, exc);
}
if (files == null)
{
// VFS-210
// honor the new doListChildren contract
// return null;
throw new FileNotFolderException(name);
}
else if (files.length == 0)
{
// No children
children = EMPTY_FILE_ARRAY;
}
else
{
// Create file objects for the children
// children = new FileObject[files.length];
children = new FileName[files.length];
for (int i = 0; i < files.length; i++)
{
final String file = files[i];
// children[i] = fs.resolveFile(name.resolveName(file, NameScope.CHILD));
// children[i] = name.resolveName(file, NameScope.CHILD);
children[i] = getFileSystem().getFileSystemManager().resolveName(name, file, NameScope.CHILD);
}
}
return resolveFiles(children);
}
}
private FileName[] extractNames(FileObject[] objects)
{
if (objects == null)
{
return null;
}
FileName[] names = new FileName[objects.length];
for (int iterObjects = 0; iterObjects < objects.length; iterObjects++)
{
names[iterObjects] = objects[iterObjects].getName();
}
return names;
}
private FileObject[] resolveFiles(FileName[] children) throws FileSystemException
{
if (children == null)
{
return null;
}
FileObject[] objects = new FileObject[children.length];
for (int iterChildren = 0; iterChildren < children.length; iterChildren++)
{
objects[iterChildren] = resolveFile(children[iterChildren]);
}
return objects;
}
private FileObject resolveFile(FileName child) throws FileSystemException
{
return fs.resolveFile(child);
}
/**
* Returns a child of this file.
* @param name The name of the child to locate.
* @return The FileObject for the file or null if the child does not exist.
* @throws FileSystemException if an error occurs.
*/
public FileObject getChild(final String name) throws FileSystemException
{
// TODO - use a hashtable when there are a large number of children
FileObject[] children = getChildren();
for (int i = 0; i < children.length; i++)
{
// final FileObject child = children[i];
final FileName child = children[i].getName();
// TODO - use a comparator to compare names
// if (child.getName().getBaseName().equals(name))
if (child.getBaseName().equals(name))
{
return resolveFile(child);
}
}
return null;
}
/**
* Returns a child by name.
* @param name The name of the child to locate.
* @param scope the NameScope.
* @return The FileObject for the file or null if the child does not exist.
* @throws FileSystemException if an error occurs.
*/
public FileObject resolveFile(final String name, final NameScope scope)
throws FileSystemException
{
// return fs.resolveFile(this.name.resolveName(name, scope));
return fs.resolveFile(getFileSystem().getFileSystemManager().resolveName(this.name, name, scope));
}
/**
* Finds a file, relative to this file.
*
* @param path The path of the file to locate. Can either be a relative
* path, which is resolved relative to this file, or an
* absolute path, which is resolved relative to the file system
* that contains this file.
* @return The FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileObject resolveFile(final String path) throws FileSystemException
{
final FileName otherName = getFileSystem().getFileSystemManager().resolveName(name, path);
return fs.resolveFile(otherName);
}
/**
* Deletes this file, once all its children have been deleted
*
* @return true if this file has been deleted
* @throws FileSystemException if an error occurs.
*/
private boolean deleteSelf() throws FileSystemException
{
synchronized (fs)
{
/* Its possible to delete a read-only file if you have write-execute access to the directory
if (!isWriteable())
{
throw new FileSystemException("vfs.provider/delete-read-only.error", name);
}
*/
/* VFS-210
if (getType() == FileType.IMAGINARY)
{
// File does not exist
return false;
}
*/
try
{
// Delete the file
doDelete();
// Update cached info
handleDelete();
}
catch (final RuntimeException re)
{
throw re;
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/delete.error", new Object[]{name}, exc);
}
return true;
}
}
/**
* Deletes this file.
*
* @return true if this object has been deleted
* @todo This will not fail if this is a non-empty folder.
* @throws FileSystemException if an error occurs.
*/
public boolean delete() throws FileSystemException
{
return delete(Selectors.SELECT_SELF) > 0;
}
/**
* Deletes this file, and all children.
*
* @param selector The FileSelector.
* @return the number of deleted files.
* @throws FileSystemException if an error occurs.
*/
public int delete(final FileSelector selector) throws FileSystemException
{
int nuofDeleted = 0;
/* VFS-210
if (getType() == FileType.IMAGINARY)
{
// File does not exist
return nuofDeleted;
}
*/
// Locate all the files to delete
ArrayList files = new ArrayList();
findFiles(selector, true, files);
// Delete 'em
final int count = files.size();
for (int i = 0; i < count; i++)
{
final AbstractFileObject file = FileObjectUtils.getAbstractFileObject(files.get(i));
// file.attach();
// VFS-210: It seems impossible to me that findFiles will return a list with hidden files/directories
// in it, else it would not be hidden. Checking for the file-type seems ok in this case
// If the file is a folder, make sure all its children have been deleted
if (file.getType().hasChildren() && file.getChildren().length != 0)
{
// Skip - as the selector forced us not to delete all files
continue;
}
// Delete the file
boolean deleted = file.deleteSelf();
if (deleted)
{
nuofDeleted++;
}
}
return nuofDeleted;
}
/**
* Creates this file, if it does not exist.
* @throws FileSystemException if an error occurs.
*/
public void createFile() throws FileSystemException
{
synchronized (fs)
{
try
{
// VFS-210: We do not want to trunc any existing file, checking for its existence is
// still required
if (exists() && !FileType.FILE.equals(getType()))
{
throw new FileSystemException("vfs.provider/create-file.error", name);
}
if (!exists())
{
getOutputStream().close();
endOutput();
}
}
catch (final RuntimeException re)
{
throw re;
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/create-file.error", name, e);
}
}
}
/**
* Creates this folder, if it does not exist. Also creates any ancestor
* files which do not exist.
* @throws FileSystemException if an error occurs.
*/
public void createFolder() throws FileSystemException
{
synchronized (fs)
{
// VFS-210: we create a folder only if it does not already exist. So this check should be safe.
if (getType().hasChildren())
{
// Already exists as correct type
return;
}
if (getType() != FileType.IMAGINARY)
{
throw new FileSystemException("vfs.provider/create-folder-mismatched-type.error", name);
}
/* VFS-210: checking for writeable is not always possible as the security constraint might
be more complex
if (!isWriteable())
{
throw new FileSystemException("vfs.provider/create-folder-read-only.error", name);
}
*/
// Traverse up the heirarchy and make sure everything is a folder
final FileObject parent = getParent();
if (parent != null)
{
parent.createFolder();
}
try
{
// Create the folder
doCreateFolder();
// Update cached info
handleCreate(FileType.FOLDER);
}
catch (final RuntimeException re)
{
throw re;
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/create-folder.error", name, exc);
}
}
}
/**
* Copies another file to this file.
* @param file The FileObject to copy.
* @param selector The FileSelector.
* @throws FileSystemException if an error occurs.
*/
public void copyFrom(final FileObject file, final FileSelector selector)
throws FileSystemException
{
if (!file.exists())
{
throw new FileSystemException("vfs.provider/copy-missing-file.error", file);
}
/* we do not alway know if a file is writeable
if (!isWriteable())
{
throw new FileSystemException("vfs.provider/copy-read-only.error", new Object[]{file.getType(),
file.getName(), this}, null);
}
*/
// Locate the files to copy across
final ArrayList files = new ArrayList();
file.findFiles(selector, false, files);
// Copy everything across
final int count = files.size();
for (int i = 0; i < count; i++)
{
final FileObject srcFile = files.get(i);
// Determine the destination file
final String relPath = file.getName().getRelativeName(srcFile.getName());
final FileObject destFile = resolveFile(relPath, NameScope.DESCENDENT_OR_SELF);
// Clean up the destination file, if necessary
if (destFile.exists() && destFile.getType() != srcFile.getType())
{
// The destination file exists, and is not of the same type,
// so delete it
// TODO - add a pluggable policy for deleting and overwriting existing files
destFile.delete(Selectors.SELECT_ALL);
}
// Copy across
try
{
if (srcFile.getType().hasContent())
{
FileUtil.copyContent(srcFile, destFile);
}
else if (srcFile.getType().hasChildren())
{
destFile.createFolder();
}
}
catch (final IOException e)
{
throw new FileSystemException("vfs.provider/copy-file.error", new Object[]{srcFile, destFile}, e);
}
}
}
/**
* Moves (rename) the file to another one.
* @param destFile The target FileObject.
* @throws FileSystemException if an error occurs.
*/
public void moveTo(FileObject destFile) throws FileSystemException
{
if (canRenameTo(destFile))
{
if (!getParent().isWriteable())
{
throw new FileSystemException("vfs.provider/rename-parent-read-only.error", new FileName[]{getName(),
getParent().getName()});
}
}
else
{
if (!isWriteable())
{
throw new FileSystemException("vfs.provider/rename-read-only.error", getName());
}
}
if (destFile.exists() && !isSameFile(destFile))
{
destFile.delete(Selectors.SELECT_ALL);
// throw new FileSystemException("vfs.provider/rename-dest-exists.error", destFile.getName());
}
if (canRenameTo(destFile))
{
// issue rename on same filesystem
try
{
attach();
doRename(destFile);
(FileObjectUtils.getAbstractFileObject(destFile)).handleCreate(getType());
destFile.close(); // now the destFile is no longer imaginary. force reattach.
handleDelete(); // fire delete-events. This file-object (src) is like deleted.
}
catch (final RuntimeException re)
{
throw re;
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/rename.error", new Object[]
{
getName(),
destFile.getName()
}, exc);
}
}
else
{
// different fs - do the copy/delete stuff
destFile.copyFrom(this, Selectors.SELECT_SELF);
if (((destFile.getType().hasContent()
&& destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE))
|| (destFile.getType().hasChildren()
&& destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FOLDER)))
&& getFileSystem().hasCapability(Capability.GET_LAST_MODIFIED))
{
destFile.getContent().setLastModifiedTime(this.getContent().getLastModifiedTime());
}
deleteSelf();
}
}
/**
* Checks if this fileObject is the same file as destFile
just with a different
* name.
* E.g. for case insensitive filesystems like windows.
* @param destFile The file to compare to.
* @return true if the FileObjects are the same.
* @throws FileSystemException if an error occurs.
*/
protected boolean isSameFile(FileObject destFile) throws FileSystemException
{
attach();
return doIsSameFile(destFile);
}
/**
* Checks if this fileObject is the same file as destFile
just with a different
* name.
* E.g. for case insensitive filesystems like windows.
* @param destFile The file to compare to.
* @return true if the FileObjects are the same.
* @throws FileSystemException if an error occurs.
*/
protected boolean doIsSameFile(FileObject destFile) throws FileSystemException
{
return false;
}
/**
* Queries the object if a simple rename to the filename of newfile
* is possible.
*
* @param newfile the new filename
* @return true if rename is possible
*/
public boolean canRenameTo(FileObject newfile)
{
return getFileSystem() == newfile.getFileSystem();
}
/**
* Finds the set of matching descendents of this file, in depthwise
* order.
*
* @param selector The FileSelector.
* @return list of files or null if the base file (this object) do not exist
* @throws FileSystemException if an error occurs.
*/
public FileObject[] findFiles(final FileSelector selector) throws FileSystemException
{
if (!exists())
{
return null;
}
final ArrayList list = new ArrayList();
findFiles(selector, true, list);
return list.toArray(new FileObject[list.size()]);
}
/**
* Returns the file's content.
* @return the FileContent for this FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileContent getContent() throws FileSystemException
{
synchronized (fs)
{
attach();
if (content == null)
{
content = doCreateFileContent();
}
return content;
}
}
/**
* Create a FileContent implementation.
* @return The FileContent.
* @throws FileSystemException if an error occurs.
* @since 2.0
*/
protected FileContent doCreateFileContent() throws FileSystemException
{
return new DefaultFileContent(this, getFileContentInfoFactory());
}
/**
* This will prepare the fileObject to get resynchronized with the underlaying filesystem if required.
* @throws FileSystemException if an error occurs.
*/
public void refresh() throws FileSystemException
{
// Detach from the file
try
{
detach();
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/resync.error", name, e);
}
}
/**
* Closes this file, and its content.
* @throws FileSystemException if an error occurs.
*/
public void close() throws FileSystemException
{
FileSystemException exc = null;
// Close the content
if (content != null)
{
try
{
content.close();
content = null;
}
catch (FileSystemException e)
{
exc = e;
}
}
// Detach from the file
try
{
detach();
}
catch (final Exception e)
{
exc = new FileSystemException("vfs.provider/close.error", name, e);
}
if (exc != null)
{
throw exc;
}
}
/**
* Returns an input stream to use to read the content of the file.
* @return The InputStream to access this file's content.
* @throws FileSystemException if an error occurs.
*/
public InputStream getInputStream() throws FileSystemException
{
/* VFS-210
if (!getType().hasContent())
{
throw new FileSystemException("vfs.provider/read-not-file.error", name);
}
if (!isReadable())
{
throw new FileSystemException("vfs.provider/read-not-readable.error", name);
}
*/
// Get the raw input stream
try
{
return doGetInputStream();
}
catch (final org.apache.commons.vfs2.FileNotFoundException exc)
{
throw new org.apache.commons.vfs2.FileNotFoundException(name, exc);
}
catch (final FileNotFoundException exc)
{
throw new org.apache.commons.vfs2.FileNotFoundException(name, exc);
}
catch (final FileSystemException exc)
{
throw exc;
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/read.error", name, exc);
}
}
/**
* Returns an input/output stream to use to read and write the content of the file in and
* random manner.
* @param mode The RandomAccessMode.
* @return The RandomAccessContent.
* @throws FileSystemException if an error occurs.
*/
public RandomAccessContent getRandomAccessContent(final RandomAccessMode mode) throws FileSystemException
{
/* VFS-210
if (!getType().hasContent())
{
throw new FileSystemException("vfs.provider/read-not-file.error", name);
}
*/
if (mode.requestRead())
{
if (!getFileSystem().hasCapability(Capability.RANDOM_ACCESS_READ))
{
throw new FileSystemException("vfs.provider/random-access-read-not-supported.error");
}
if (!isReadable())
{
throw new FileSystemException("vfs.provider/read-not-readable.error", name);
}
}
if (mode.requestWrite())
{
if (!getFileSystem().hasCapability(Capability.RANDOM_ACCESS_WRITE))
{
throw new FileSystemException("vfs.provider/random-access-write-not-supported.error");
}
if (!isWriteable())
{
throw new FileSystemException("vfs.provider/write-read-only.error", name);
}
}
// Get the raw input stream
try
{
return doGetRandomAccessContent(mode);
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/random-access.error", name, exc);
}
}
/**
* Prepares this file for writing. Makes sure it is either a file,
* or its parent folder exists. Returns an output stream to use to
* write the content of the file to.
* @return An OutputStream where the new contents of the file can be written.
* @throws FileSystemException if an error occurs.
*/
public OutputStream getOutputStream() throws FileSystemException
{
return getOutputStream(false);
}
/**
* Prepares this file for writing. Makes sure it is either a file,
* or its parent folder exists. Returns an output stream to use to
* write the content of the file to.
*
* @param bAppend true when append to the file.
* Note: If the underlaying filesystem do not support this, it wont work.
* @return An OutputStream where the new contents of the file can be written.
* @throws FileSystemException if an error occurs.
*/
public OutputStream getOutputStream(boolean bAppend) throws FileSystemException
{
/* VFS-210
if (getType() != FileType.IMAGINARY && !getType().hasContent())
{
throw new FileSystemException("vfs.provider/write-not-file.error", name);
}
if (!isWriteable())
{
throw new FileSystemException("vfs.provider/write-read-only.error", name);
}
*/
if (bAppend && !getFileSystem().hasCapability(Capability.APPEND_CONTENT))
{
throw new FileSystemException("vfs.provider/write-append-not-supported.error", name);
}
if (getType() == FileType.IMAGINARY)
{
// Does not exist - make sure parent does
FileObject parent = getParent();
if (parent != null)
{
parent.createFolder();
}
}
// Get the raw output stream
try
{
return doGetOutputStream(bAppend);
}
catch (RuntimeException re)
{
throw re;
}
catch (Exception exc)
{
throw new FileSystemException("vfs.provider/write.error", new Object[]{name}, exc);
}
}
/**
* Detaches this file, invaliating all cached info. This will force
* a call to {@link #doAttach} next time this file is used.
* @throws Exception if an error occurs.
*/
private void detach() throws Exception
{
synchronized (fs)
{
if (attached)
{
try
{
doDetach();
}
finally
{
attached = false;
setFileType(null);
parent = null;
// fs.fileDetached(this);
removeChildrenCache();
// children = null;
}
}
}
}
private void removeChildrenCache()
{
/*
if (children != null)
{
for (int iterChildren = 0; iterChildren < children.length; iterChildren++)
{
fs.removeFileFromCache(children[iterChildren].getName());
}
children = null;
}
*/
children = null;
}
/**
* Attaches to the file.
* @throws FileSystemException if an error occurs.
*/
private void attach() throws FileSystemException
{
synchronized (fs)
{
if (attached)
{
return;
}
try
{
// Attach and determine the file type
doAttach();
attached = true;
// now the type could already be injected by doAttach (e.g from parent to child)
/* VFS-210: determine the type when really asked fore
if (type == null)
{
setFileType(doGetType());
}
if (type == null)
{
setFileType(FileType.IMAGINARY);
}
*/
}
catch (Exception exc)
{
throw new FileSystemException("vfs.provider/get-type.error", new Object[]{name}, exc);
}
// fs.fileAttached(this);
}
}
/**
* Called when the ouput stream for this file is closed.
* @throws Exception if an error occurs.
*/
protected void endOutput() throws Exception
{
if (getType() == FileType.IMAGINARY)
{
// File was created
handleCreate(FileType.FILE);
}
else
{
// File has changed
onChange();
}
}
/**
* Called when this file is created. Updates cached info and notifies
* the parent and file system.
* @param newType The type of the file.
* @throws Exception if an error occurs.
*/
protected void handleCreate(final FileType newType) throws Exception
{
synchronized (fs)
{
if (attached)
{
// Fix up state
injectType(newType);
removeChildrenCache();
// children = EMPTY_FILE_ARRAY;
// Notify subclass
onChange();
}
// Notify parent that its child list may no longer be valid
notifyParent(this.getName(), newType);
// Notify the file system
fs.fireFileCreated(this);
}
}
/**
* Called when this file is deleted. Updates cached info and notifies
* subclasses, parent and file system.
* @throws Exception if an error occurs.
*/
protected void handleDelete() throws Exception
{
synchronized (fs)
{
if (attached)
{
// Fix up state
injectType(FileType.IMAGINARY);
removeChildrenCache();
// children = null;
// Notify subclass
onChange();
}
// Notify parent that its child list may no longer be valid
notifyParent(this.getName(), FileType.IMAGINARY);
// Notify the file system
fs.fireFileDeleted(this);
}
}
/**
* Called when this file is changed.
* This will only happen if you monitor the file using {@link org.apache.commons.vfs2.FileMonitor}.
* @throws Exception if an error occurs.
*/
protected void handleChanged() throws Exception
{
// Notify the file system
fs.fireFileChanged(this);
}
/**
* Notifies the file that its children have changed.
* @param childName The name of the child.
* @param newType The type of the child.
* @throws Exception if an error occurs.
*/
protected void childrenChanged(FileName childName, FileType newType) throws Exception
{
// TODO - this may be called when not attached
if (children != null)
{
if (childName != null && newType != null)
{
// TODO - figure out if children[] can be replaced by list
ArrayList list = new ArrayList(Arrays.asList(children));
if (newType.equals(FileType.IMAGINARY))
{
list.remove(childName);
}
else
{
list.add(childName);
}
children = new FileName[list.size()];
list.toArray(children);
}
}
// removeChildrenCache();
onChildrenChanged(childName, newType);
}
/**
* Notify the parent of a change to its children, when a child is created
* or deleted.
* @param childName The name of the child.
* @param newType The type of the child.
* @throws Exception if an error occurs.
*/
private void notifyParent(FileName childName, FileType newType) throws Exception
{
if (parent == null)
{
FileName parentName = name.getParent();
if (parentName != null)
{
// Locate the parent, if it is cached
parent = fs.getFileFromCache(parentName);
}
}
if (parent != null)
{
FileObjectUtils.getAbstractFileObject(parent).childrenChanged(childName, newType);
}
}
/**
* Traverses the descendents of this file, and builds a list of selected
* files.
* @param selector The FileSelector.
* @param depthwise if true files are added after their descendants, before otherwise.
* @param selected A List of the located FileObjects.
* @throws FileSystemException if an error occurs.
*/
public void findFiles(final FileSelector selector,
final boolean depthwise,
final List selected) throws FileSystemException
{
try
{
if (exists())
{
// Traverse starting at this file
final DefaultFileSelectorInfo info = new DefaultFileSelectorInfo();
info.setBaseFolder(this);
info.setDepth(0);
info.setFile(this);
traverse(info, selector, depthwise, selected);
}
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/find-files.error", name, e);
}
}
/**
* Traverses a file.
*/
private static void traverse(final DefaultFileSelectorInfo fileInfo,
final FileSelector selector,
final boolean depthwise,
final List selected)
throws Exception
{
// Check the file itself
final FileObject file = fileInfo.getFile();
final int index = selected.size();
// If the file is a folder, traverse it
if (file.getType().hasChildren() && selector.traverseDescendents(fileInfo))
{
final int curDepth = fileInfo.getDepth();
fileInfo.setDepth(curDepth + 1);
// Traverse the children
final FileObject[] children = file.getChildren();
for (int i = 0; i < children.length; i++)
{
final FileObject child = children[i];
fileInfo.setFile(child);
traverse(fileInfo, selector, depthwise, selected);
}
fileInfo.setFile(file);
fileInfo.setDepth(curDepth);
}
// Add the file if doing depthwise traversal
if (selector.includeFile(fileInfo))
{
if (depthwise)
{
// Add this file after its descendents
selected.add(file);
}
else
{
// Add this file before its descendents
selected.add(index, file);
}
}
}
/**
* Check if the content stream is open.
*
* @return true if this is the case
*/
public boolean isContentOpen()
{
if (content == null)
{
return false;
}
return content.isOpen();
}
/**
* Check if the internal state is "attached".
*
* @return true if this is the case
*/
public boolean isAttached()
{
return attached;
}
/**
* create the filecontentinfo implementation.
* @return The FileContentInfoFactory.
*/
protected FileContentInfoFactory getFileContentInfoFactory()
{
return getFileSystem().getFileSystemManager().getFileContentInfoFactory();
}
protected void injectType(FileType fileType)
{
setFileType(fileType);
}
private void setFileType(FileType type)
{
if (type != null && type != FileType.IMAGINARY)
{
try
{
name.setType(type);
}
catch (FileSystemException e)
{
throw new RuntimeException(e.getMessage());
}
}
this.type = type;
}
/**
* This method is meant to add an object where this object holds a strong reference then.
* E.g. a archive-filesystem creates a list of all childs and they shouldnt get
* garbage collected until the container is garbage collected
*
* @param strongRef The Object to add.
*/
// TODO should this be a FileObject?
public void holdObject(Object strongRef)
{
if (objects == null)
{
objects = new ArrayList(INITIAL_LISTSZ);
}
objects.add(strongRef);
}
/**
* will be called after this file-object closed all its streams.
*/
protected void notifyAllStreamsClosed()
{
}
// --- OPERATIONS ---
/**
* @return FileOperations interface that provides access to the operations
* API.
* @throws FileSystemException if an error occurs.
*/
public FileOperations getFileOperations() throws FileSystemException
{
if (operations == null)
{
operations = new DefaultFileOperations(this);
}
return operations;
}
@Override
protected void finalize() throws Throwable
{
fs.fileObjectDestroyed(this);
super.finalize();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileProvider.java 100644 765 24 13256 11623215065 32061 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.local.GenericFileNameParser;
/**
* A partial {@link FileProvider} implementation. Takes care of managing the
* file systems created by the provider.
*
* @author Commons VFS team
*/
public abstract class AbstractFileProvider
extends AbstractVfsContainer
implements FileProvider
{
/**
* The cached file systems. This is a mapping from root URI to
* FileSystem object.
*/
// private final Map fileSystems = new HashMap();
private final Map fileSystems = new TreeMap();
private FileNameParser parser;
public AbstractFileProvider()
{
parser = GenericFileNameParser.getInstance();
}
protected FileNameParser getFileNameParser()
{
return parser;
}
protected void setFileNameParser(FileNameParser parser)
{
this.parser = parser;
}
/**
* Closes the file systems created by this provider.
*/
@Override
public void close()
{
synchronized (this)
{
fileSystems.clear();
}
super.close();
}
/**
* Creates a layered file system. This method throws a 'not supported' exception.
* @param scheme The protocol to use to access the file.
* @param file a FileObject.
* @param properties Options to the file system.
* @return A FileObject associated with the new FileSystem.
* @throws FileSystemException if an error occurs.
*/
public FileObject createFileSystem(final String scheme, final FileObject file, final FileSystemOptions properties)
throws FileSystemException
{
// Can't create a layered file system
throw new FileSystemException("vfs.provider/not-layered-fs.error", scheme);
}
/**
* Adds a file system to those cached by this provider. The file system
* may implement {@link VfsComponent}, in which case it is initialised.
*/
protected void addFileSystem(final Comparable> key, final FileSystem fs)
throws FileSystemException
{
// Add to the cache
addComponent(fs);
FileSystemKey treeKey = new FileSystemKey(key, fs.getFileSystemOptions());
((AbstractFileSystem) fs).setCacheKey(treeKey);
synchronized (this)
{
fileSystems.put(treeKey, fs);
}
}
/**
* Locates a cached file system
*
* @return The provider, or null if it is not cached.
*/
protected FileSystem findFileSystem(final Comparable> key, final FileSystemOptions fileSystemProps)
{
FileSystemKey treeKey = new FileSystemKey(key, fileSystemProps);
synchronized (this)
{
return fileSystems.get(treeKey);
}
}
/**
* Returns the FileSystemConfigBuidler.
* @return the FileSystemConfigBuilder.
*/
public FileSystemConfigBuilder getConfigBuilder()
{
return null;
}
/**
* Free unused resources.
*/
public void freeUnusedResources()
{
Object[] item;
synchronized (this)
{
item = fileSystems.values().toArray();
}
for (int i = 0; i < item.length; ++i)
{
AbstractFileSystem fs = (AbstractFileSystem) item[i];
if (fs.isReleaseable())
{
fs.closeCommunicationLink();
}
}
}
/**
* Close the FileSystem.
* @param filesystem The FileSystem to close.
*/
public void closeFileSystem(final FileSystem filesystem)
{
AbstractFileSystem fs = (AbstractFileSystem) filesystem;
synchronized (this)
{
if (fs.getCacheKey() != null)
{
fileSystems.remove(fs.getCacheKey());
}
}
removeComponent(fs);
fs.close();
}
/**
* Parses an absolute URI.
*
* @param base The base file - if null the uri
needs to be absolute
* @param uri The URI to parse.
* @return The FileName.
* @throws FileSystemException if an error occurs.
*/
public FileName parseUri(FileName base, String uri) throws FileSystemException
{
if (getFileNameParser() != null)
{
return getFileNameParser().parseUri(getContext(), base, uri);
}
throw new FileSystemException("vfs.provider/filename-parser-missing.error");
// return GenericFileName.parseUri(getFileNameParser(), uri, 0);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractFileSystem.java 100644 765 24 46671 11623215065 31562 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.CacheStrategy;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FilesCache;
import org.apache.commons.vfs2.VfsLog;
import org.apache.commons.vfs2.cache.OnCallRefreshFileObject;
import org.apache.commons.vfs2.events.AbstractFileChangeEvent;
import org.apache.commons.vfs2.events.ChangedEvent;
import org.apache.commons.vfs2.events.CreateEvent;
import org.apache.commons.vfs2.events.DeleteEvent;
import org.apache.commons.vfs2.impl.DefaultFileSystemConfigBuilder;
import org.apache.commons.vfs2.util.Messages;
/**
* A partial {@link org.apache.commons.vfs2.FileSystem} implementation.
*
* @author Commons VFS team
*/
public abstract class AbstractFileSystem
extends AbstractVfsComponent
implements FileSystem
{
private static final Log LOG = LogFactory.getLog(AbstractFileSystem.class);
/**
* The "root" of the file system. This is always "/" so it isn't always the "real"
* root.
*/
private final FileName rootName;
/**
* The root URI of the file system. The base path specified as a file system option
* when the file system was created.
*/
private final String rootURI;
private FileObject parentLayer;
// private FileObject root;
private final Collection caps = new HashSet();
/**
* Map from FileName to FileObject.
*/
// private FilesCache files;
/**
* Map from FileName to an ArrayList of listeners for that file.
*/
private final Map> listenerMap = new HashMap>();
/**
* FileSystemOptions used for configuration
*/
private final FileSystemOptions fileSystemOptions;
/**
* How many fileObjects are handed out
*/
private final AtomicLong useCount = new AtomicLong(0);
private FileSystemKey cacheKey;
/**
* open streams counter for this filesystem
*/
private final AtomicInteger openStreams = new AtomicInteger(0);
protected AbstractFileSystem(final FileName rootName,
final FileObject parentLayer,
final FileSystemOptions fileSystemOptions)
{
// this.parentLayer = parentLayer;
this.parentLayer = parentLayer;
this.rootName = rootName;
this.fileSystemOptions = fileSystemOptions;
FileSystemConfigBuilder builder = DefaultFileSystemConfigBuilder.getInstance();
String uri = builder.getRootURI(fileSystemOptions);
if (uri == null)
{
uri = rootName.getURI();
}
this.rootURI = uri;
}
/**
* Initialises this component.
* @throws FileSystemException if an error occurs.
*/
@Override
public void init() throws FileSystemException
{
addCapabilities(caps);
}
/**
* Closes this component.
*/
@Override
public void close()
{
closeCommunicationLink();
parentLayer = null;
}
/**
* Close the underlaying link used to access the files.
*/
public void closeCommunicationLink()
{
synchronized (this)
{
doCloseCommunicationLink();
}
}
/**
* Close the underlaying link used to access the files
*/
protected void doCloseCommunicationLink()
{
}
/**
* Creates a file object. This method is called only if the requested
* file is not cached.
*/
protected abstract FileObject createFile(final AbstractFileName name) throws Exception;
/**
* Adds the capabilities of this file system.
*/
protected abstract void addCapabilities(Collection caps);
/**
* Returns the name of the root of this file system.
* @return the root FileName.
*/
public FileName getRootName()
{
return rootName;
}
/**
* Returns the root URI specified for this file System.
* @return The root URI used in this file system.
* @since 2.0
*/
public String getRootURI()
{
return rootURI;
}
/**
* Adds a file object to the cache.
*/
protected void putFileToCache(final FileObject file)
{
getCache().putFile(file);
// files.put(file.getName(), file);
}
private FilesCache getCache()
{
FilesCache files;
//if (this.files == null)
//{
files = getContext().getFileSystemManager().getFilesCache();
if (files == null)
{
throw new RuntimeException(Messages.getString("vfs.provider/files-cache-missing.error"));
}
//}
return files;
}
/**
* Returns a cached file.
*/
protected FileObject getFileFromCache(final FileName name)
{
return getCache().getFile(this, name);
// return (FileObject) files.get(name);
}
/**
* remove a cached file.
*/
protected void removeFileFromCache(final FileName name)
{
getCache().removeFile(this, name);
}
/**
* Determines if this file system has a particular capability.
* @param capability the Capability to check for.
* @return true if the FileSystem has the Capability, false otherwise.
*/
public boolean hasCapability(final Capability capability)
{
return caps.contains(capability);
}
/**
* Retrieves the attribute with the specified name. The default
* implementation simply throws an exception.
* @param attrName The name of the attribute.
* @return the Object associated with the attribute or null if no object is.
* @throws FileSystemException if an error occurs.
*/
public Object getAttribute(final String attrName) throws FileSystemException
{
throw new FileSystemException("vfs.provider/get-attribute-not-supported.error");
}
/**
* Sets the attribute with the specified name. The default
* implementation simply throws an exception.
* @param attrName the attribute name.
* @param value The object to associate with the attribute.
* @throws FileSystemException if an error occurs.
*/
public void setAttribute(final String attrName, final Object value)
throws FileSystemException
{
throw new FileSystemException("vfs.provider/set-attribute-not-supported.error");
}
/**
* Returns the parent layer if this is a layered file system.
* @return The FileObject for the parent layer.
* @throws FileSystemException if an error occurs.
*/
public FileObject getParentLayer() throws FileSystemException
{
return parentLayer;
}
/**
* Returns the root file of this file system.
* @return The root FileObject of the FileSystem
* @throws FileSystemException if an error occurs.
*/
public FileObject getRoot() throws FileSystemException
{
return resolveFile(rootName);
/*
if (root == null)
{
root = resolveFile(rootName);
}
return root;
*/
}
/**
* Finds a file in this file system.
* @param nameStr The name of the file to resolve.
* @return The located FileObject or null if none could be located.
* @throws FileSystemException if an error occurs.
*/
public FileObject resolveFile(final String nameStr) throws FileSystemException
{
// Resolve the name, and create the file
final FileName name = getFileSystemManager().resolveName(rootName, nameStr);
return resolveFile(name);
}
/**
* Finds a file in this file system.
* @param name The name of the file to locate.
* @return The located FileObject or null if none could be located.
* @throws FileSystemException if an error occurs.
*/
public FileObject resolveFile(final FileName name) throws FileSystemException
{
return resolveFile(name, true);
}
private synchronized FileObject resolveFile(final FileName name, final boolean useCache) throws FileSystemException
{
if (!rootName.getRootURI().equals(name.getRootURI()))
{
throw new FileSystemException("vfs.provider/mismatched-fs-for-name.error",
new Object[]{
name, rootName, name.getRootURI()});
}
// imario@apache.org ==> use getFileFromCache
FileObject file;
if (useCache)
{
file = getFileFromCache(name);
}
else
{
file = null;
}
// FileObject file = (FileObject) files.get(name);
if (file == null)
{
try
{
file = createFile((AbstractFileName) name);
}
catch (Exception e)
{
throw new FileSystemException("vfs.provider/resolve-file.error", name, e);
}
file = decorateFileObject(file);
// imario@apache.org ==> use putFileToCache
if (useCache)
{
putFileToCache(file);
}
// files.put(name, file);
}
/**
* resync the file information if requested
*/
if (getFileSystemManager().getCacheStrategy().equals(CacheStrategy.ON_RESOLVE))
{
file.refresh();
}
return file;
}
protected FileObject decorateFileObject(FileObject file) throws FileSystemException
{
if (getFileSystemManager().getCacheStrategy().equals(CacheStrategy.ON_CALL))
{
file = new OnCallRefreshFileObject(file);
}
if (getFileSystemManager().getFileObjectDecoratorConst() != null)
{
try
{
file = (FileObject) getFileSystemManager().getFileObjectDecoratorConst().
newInstance(new Object[]{file});
}
catch (InstantiationException e)
{
throw new FileSystemException("vfs.impl/invalid-decorator.error",
getFileSystemManager().getFileObjectDecorator().getName(), e);
}
catch (IllegalAccessException e)
{
throw new FileSystemException("vfs.impl/invalid-decorator.error",
getFileSystemManager().getFileObjectDecorator().getName(), e);
}
catch (InvocationTargetException e)
{
throw new FileSystemException("vfs.impl/invalid-decorator.error",
getFileSystemManager().getFileObjectDecorator().getName(), e);
}
}
return file;
}
/**
* Creates a temporary local copy of a file and its descendents.
* @param file The FileObject to replicate.
* @param selector The FileSelector.
* @return The replicated File.
* @throws FileSystemException if an error occurs.
*/
public File replicateFile(final FileObject file,
final FileSelector selector)
throws FileSystemException
{
if (!file.exists())
{
throw new FileSystemException("vfs.provider/replicate-missing-file.error", file.getName());
}
try
{
return doReplicateFile(file, selector);
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/replicate-file.error", file.getName(), e);
}
}
/**
* Return the FileSystemOptions used to instantiate this filesystem.
* @return the FileSystemOptions.
*/
public FileSystemOptions getFileSystemOptions()
{
return fileSystemOptions;
}
/**
* Return the FileSystemManager used to instantiate this filesystem.
* @return the FileSystemManager.
*/
public FileSystemManager getFileSystemManager()
{
return getContext().getFileSystemManager();
// return manager;
}
/**
* Returns the accuracy of the last modification time.
*
* @return ms 0 perfectly accurate, >0 might be off by this value e.g. sftp 1000ms
*/
public double getLastModTimeAccuracy()
{
return 0;
}
/**
* Creates a temporary local copy of a file and its descendents.
*/
protected File doReplicateFile(final FileObject file,
final FileSelector selector)
throws Exception
{
return getContext().getReplicator().replicateFile(file, selector);
}
/**
* Adds a junction to this file system.
* @param junctionPoint The junction point.
* @param targetFile The target to add.
* @throws FileSystemException if an error occurs.
*/
public void addJunction(final String junctionPoint,
final FileObject targetFile)
throws FileSystemException
{
throw new FileSystemException("vfs.provider/junctions-not-supported.error", rootName);
}
/**
* Removes a junction from this file system.
* @param junctionPoint The junction point.
* @throws FileSystemException if an error occurs
*/
public void removeJunction(final String junctionPoint) throws FileSystemException
{
throw new FileSystemException("vfs.provider/junctions-not-supported.error", rootName);
}
/**
* Adds a listener on a file in this file system.
* @param file The FileObject to be monitored.
* @param listener The FileListener
*/
public void addListener(final FileObject file,
final FileListener listener)
{
synchronized (listenerMap)
{
ArrayList listeners = listenerMap.get(file.getName());
if (listeners == null)
{
listeners = new ArrayList();
listenerMap.put(file.getName(), listeners);
}
listeners.add(listener);
}
}
/**
* Removes a listener from a file in this file system.
* @param file The FileObject to be monitored.
* @param listener The FileListener
*/
public void removeListener(final FileObject file,
final FileListener listener)
{
synchronized (listenerMap)
{
final ArrayList> listeners = listenerMap.get(file.getName());
if (listeners != null)
{
listeners.remove(listener);
if (listeners.isEmpty())
{
listenerMap.remove(file.getName());
}
}
}
}
/**
* Fires a file create event.
* @param file The FileObject that was created.
*/
public void fireFileCreated(final FileObject file)
{
fireEvent(new CreateEvent(file));
}
/**
* Fires a file delete event.
* @param file The FileObject that was deleted.
*/
public void fireFileDeleted(final FileObject file)
{
fireEvent(new DeleteEvent(file));
}
/**
* Fires a file changed event.
* This will only happen if you monitor the file using {@link org.apache.commons.vfs2.FileMonitor}.
* @param file The FileObject that changed.
*/
public void fireFileChanged(final FileObject file)
{
fireEvent(new ChangedEvent(file));
}
/**
* returns true if no file is using this filesystem.
* @return true of no file is using this FileSystem.
*/
public boolean isReleaseable()
{
return useCount.get() < 1;
}
void freeResources()
{
}
/**
* Fires an event.
*/
private void fireEvent(final AbstractFileChangeEvent event)
{
FileListener[] fileListeners = null;
final FileObject file = event.getFile();
synchronized (listenerMap)
{
final ArrayList> listeners = listenerMap.get(file.getName());
if (listeners != null)
{
fileListeners = listeners.toArray(new FileListener[listeners.size()]);
}
}
if (fileListeners != null)
{
for (int i = 0; i < fileListeners.length; i++)
{
final FileListener fileListener = fileListeners[i];
try
{
event.notify(fileListener);
}
catch (final Exception e)
{
final String message = Messages.getString("vfs.provider/notify-listener.warn", file);
// getLogger().warn(message, e);
VfsLog.warn(getLogger(), LOG, message, e);
}
}
}
}
/*
void fileDetached(FileObject fileObject)
{
useCount--;
}
void fileAttached(FileObject fileObject)
{
useCount++;
}
*/
void fileObjectHanded(FileObject fileObject)
{
useCount.incrementAndGet();
}
void fileObjectDestroyed(FileObject fileObject)
{
useCount.decrementAndGet();
}
void setCacheKey(FileSystemKey cacheKey)
{
this.cacheKey = cacheKey;
}
FileSystemKey getCacheKey()
{
return this.cacheKey;
}
void streamOpened()
{
openStreams.incrementAndGet();
}
void streamClosed()
{
int count;
do
{
count = openStreams.get();
if (count < 1)
{
return;
}
} while(openStreams.compareAndSet(count, count - 1));
if (count == 1)
{
notifyAllStreamsClosed();
}
}
/**
* will be called after all file-objects closed their streams.
*/
protected void notifyAllStreamsClosed()
{
}
/**
* check if this filesystem has open streams.
* @return true if the FileSystem has open streams.
*/
public boolean isOpen()
{
return openStreams.get() > 0;
}
}
././@LongLink 100644 0 0 145 11623215455 10257 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractLayeredFileProvider.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractLayeredFileProvider.java100644 765 24 10213 11623215065 33355 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* A {@link FileProvider} that is layered on top of another, such as the
* contents of a zip or tar file.
*
* @author Commons VFS team
*/
public abstract class AbstractLayeredFileProvider
extends AbstractFileProvider
implements FileProvider
{
public AbstractLayeredFileProvider()
{
super();
setFileNameParser(LayeredFileNameParser.getInstance());
}
/**
* Locates a file object, by absolute URI.
* @param baseFile The base FileObject.
* @param uri The name of the file to locate.
* @param properties The FileSystemOptions.
* @return The FileObject if it is located, null otherwise.
* @throws FileSystemException if an error occurs.
*/
public FileObject findFile(final FileObject baseFile,
final String uri,
final FileSystemOptions properties) throws FileSystemException
{
// Split the URI up into its parts
final LayeredFileName name = (LayeredFileName) parseUri(baseFile != null ? baseFile.getName() : null, uri);
// Make the URI canonical
// Resolve the outer file name
final FileName fileName = name.getOuterName();
final FileObject file = getContext().resolveFile(baseFile, fileName.getURI(), properties);
// Create the file system
final FileObject rootFile = createFileSystem(name.getScheme(), file, properties);
// Resolve the file
return rootFile.resolveFile(name.getPath());
}
/**
* Creates a layered file system.
* @param scheme The protocol to use.
* @param file a FileObject.
* @param fileSystemOptions Options to access the FileSystem.
* @return A FileObject associated with the new FileSystem.
* @throws FileSystemException if an error occurs.
*/
@Override
public synchronized FileObject createFileSystem(final String scheme,
final FileObject file,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Check if cached
final FileName rootName = file.getName();
FileSystem fs = findFileSystem(rootName, null);
if (fs == null)
{
// Create the file system
fs = doCreateFileSystem(scheme, file, fileSystemOptions);
addFileSystem(rootName, fs);
}
return fs.getRoot();
}
/**
* Creates a layered file system. This method is called if the file system
* is not cached. The file system may implement {@link VfsComponent}.
*
* @param scheme The URI scheme.
* @param file The file to create the file system on top of.
* @return The file system.
*/
protected abstract FileSystem doCreateFileSystem(final String scheme,
final FileObject file,
final FileSystemOptions fileSystemOptions)
throws FileSystemException;
}
././@LongLink 100644 0 0 151 11623215455 10254 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractOriginatingFileProvider.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractOriginatingFileProvider.100644 765 24 10601 11623215065 33401 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* A {@link FileProvider} that handles physical files, such as the files in a
* local fs, or on an FTP server. An originating file system cannot be
* layered on top of another file system.
*
* @author Commons VFS team
*/
public abstract class AbstractOriginatingFileProvider
extends AbstractFileProvider
{
public AbstractOriginatingFileProvider()
{
super();
}
/**
* Locates a file object, by absolute URI.
*
* @param baseFile The base file object.
* @param uri The URI of the file to locate
* @param fileSystemOptions The FileSystem options.
* @return The located FileObject
* @throws FileSystemException if an error occurs.
*/
public FileObject findFile(final FileObject baseFile,
final String uri,
final FileSystemOptions fileSystemOptions) throws FileSystemException
{
// Parse the URI
final FileName name;
try
{
name = parseUri(baseFile != null ? baseFile.getName() : null, uri);
}
catch (FileSystemException exc)
{
throw new FileSystemException("vfs.provider/invalid-absolute-uri.error", uri, exc);
}
// Locate the file
return findFile(name, fileSystemOptions);
}
/**
* Locates a file from its parsed URI.
* @param name The file name.
* @param fileSystemOptions FileSystem options.
* @return A FileObject associated with the file.
* @throws FileSystemException if an error occurs.
*/
protected FileObject findFile(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Check in the cache for the file system
final FileName rootName = getContext().getFileSystemManager().resolveName(name, FileName.ROOT_PATH);
FileSystem fs = getFileSystem(rootName, fileSystemOptions);
// Locate the file
// return fs.resolveFile(name.getPath());
return fs.resolveFile(name);
}
/**
* Returns the FileSystem associated with the specified root.
* @param rootName The root path.
* @param fileSystemOptions The FileSystem options.
* @return The FileSystem.
* @throws FileSystemException if an error occurs.
* @since 2.0
*/
protected synchronized FileSystem getFileSystem(FileName rootName, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
FileSystem fs = findFileSystem(rootName, fileSystemOptions);
if (fs == null)
{
// Need to create the file system, and cache it
fs = doCreateFileSystem(rootName, fileSystemOptions);
addFileSystem(rootName, fs);
}
return fs;
}
/**
* Creates a {@link FileSystem}. If the returned FileSystem implements
* {@link VfsComponent}, it will be initialised.
*
* @param rootName The name of the root file of the file system to create.
* @param fileSystemOptions The FileSystem options.
* @return The FileSystem.
* @throws FileSystemException if an error occurs.
*/
protected abstract FileSystem doCreateFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
throws FileSystemException;
}
././@LongLink 100644 0 0 145 11623215455 10257 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessContent.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessContent.java100644 765 24 7053 11623215065 33342 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.IOException;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* Implements the DataOutput part of the RandomAccessContent interface and throws
* UnsupportedOperationException if one of those methods are called.
* (for read-only random access implementations)
*
* @author Commons VFS team
*/
public abstract class AbstractRandomAccessContent implements RandomAccessContent
{
private final RandomAccessMode mode;
protected AbstractRandomAccessContent(final RandomAccessMode mode)
{
this.mode = mode;
}
public void writeDouble(double v) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeFloat(float v) throws IOException
{
throw new UnsupportedOperationException();
}
public void write(int b) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeByte(int v) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeChar(int v) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeInt(int v) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeShort(int v) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeLong(long v) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeBoolean(boolean v) throws IOException
{
throw new UnsupportedOperationException();
}
public void write(byte[] b) throws IOException
{
throw new UnsupportedOperationException();
}
public void write(byte[] b, int off, int len) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeBytes(String s) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeChars(String s) throws IOException
{
throw new UnsupportedOperationException();
}
public void writeUTF(String str) throws IOException
{
throw new UnsupportedOperationException();
}
/**
* @deprecated see {@link java.io.DataInputStream#readLine()} This method will be removed when it is
* removed from the DataInput interface this class implements (which will probably never happen).
* @return The line as a String.
* @throws IOException if an error occurs.
*/
@Deprecated
public String readLine() throws IOException
{
throw new UnsupportedOperationException("deprecated");
}
}
././@LongLink 100644 0 0 153 11623215455 10256 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessStreamContent.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractRandomAccessStreamConten100644 765 24 6621 11623215065 33412 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.DataInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* Implements the part usable for all stream base random access implementations.
*
* @author Commons VFS team
*/
public abstract class AbstractRandomAccessStreamContent extends AbstractRandomAccessContent
{
protected AbstractRandomAccessStreamContent(final RandomAccessMode mode)
{
super(mode);
}
protected abstract DataInputStream getDataInputStream() throws IOException;
public byte readByte() throws IOException
{
byte data = getDataInputStream().readByte();
return data;
}
public char readChar() throws IOException
{
char data = getDataInputStream().readChar();
return data;
}
public double readDouble() throws IOException
{
double data = getDataInputStream().readDouble();
return data;
}
public float readFloat() throws IOException
{
float data = getDataInputStream().readFloat();
return data;
}
public int readInt() throws IOException
{
int data = getDataInputStream().readInt();
return data;
}
public int readUnsignedByte() throws IOException
{
int data = getDataInputStream().readUnsignedByte();
return data;
}
public int readUnsignedShort() throws IOException
{
int data = getDataInputStream().readUnsignedShort();
return data;
}
public long readLong() throws IOException
{
long data = getDataInputStream().readLong();
return data;
}
public short readShort() throws IOException
{
short data = getDataInputStream().readShort();
return data;
}
public boolean readBoolean() throws IOException
{
boolean data = getDataInputStream().readBoolean();
return data;
}
public int skipBytes(int n) throws IOException
{
int data = getDataInputStream().skipBytes(n);
return data;
}
public void readFully(byte[] b) throws IOException
{
getDataInputStream().readFully(b);
}
public void readFully(byte[] b, int off, int len) throws IOException
{
getDataInputStream().readFully(b, off, len);
}
public String readUTF() throws IOException
{
String data = getDataInputStream().readUTF();
return data;
}
public InputStream getInputStream() throws IOException
{
return getDataInputStream();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsComponent.java 100644 765 24 4310 11623215065 32057 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.logging.Log;
import org.apache.commons.vfs2.FileSystemException;
/**
* A partial {@link VfsComponent} implementation.
*
* @author Commons VFS team
*/
public abstract class AbstractVfsComponent
implements VfsComponent
{
private VfsComponentContext context;
private Log log;
/**
* Sets the Logger to use for the component.
* @param log The Log to use.
*/
public final void setLogger(final Log log)
{
this.log = log;
}
/**
* Sets the context for this file system provider.
* @param context The VfsComponentContext.
*/
public final void setContext(final VfsComponentContext context)
{
this.context = context;
}
/**
* Initialises the component. This implementation does nothing.
* @throws FileSystemException if an error occurs.
*/
public void init() throws FileSystemException
{
}
/**
* Closes the provider. This implementation does nothing.
*/
public void close()
{
}
/**
* Returns the logger for this file system to use.
*/
protected final Log getLogger()
{
return log;
}
/**
* Returns the context for this provider.
*/
protected final VfsComponentContext getContext()
{
return context;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/AbstractVfsContainer.java 100644 765 24 5407 11623215065 32047 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.util.ArrayList;
import org.apache.commons.vfs2.FileSystemException;
/**
* A {@link VfsComponent} that contains a set of sub-components.
*
* @author Commons VFS team
*/
public abstract class AbstractVfsContainer
extends AbstractVfsComponent
{
/**
* The components contained by this component.
*/
private final ArrayList components = new ArrayList();
/**
* Adds a sub-component to this component. If the sub-component implements
* {@link VfsComponent}, it is initialised. All sub-components are closed
* when this component is closed.
*/
protected void addComponent(final Object component)
throws FileSystemException
{
if (!components.contains(component))
{
// Initialise
if (component instanceof VfsComponent)
{
VfsComponent vfsComponent = (VfsComponent) component;
vfsComponent.setLogger(getLogger());
vfsComponent.setContext(getContext());
vfsComponent.init();
}
// Keep track of component, to close it later
components.add(component);
}
}
/**
* Removes a sub-component from this component.
*/
protected void removeComponent(final Object component)
{
components.remove(component);
}
/**
* Closes the sub-components of this component.
*/
@Override
public void close()
{
// Close all components
final int count = components.size();
for (int i = 0; i < count; i++)
{
final Object component = components.get(i);
if (component instanceof VfsComponent)
{
final VfsComponent vfsComponent = (VfsComponent) component;
vfsComponent.close();
}
}
components.clear();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/BZip2Constants.java 100644 765 24 11336 11623215064 31650 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.bzip2;
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* to whom the Ant project is very grateful for his
* great code.
*/
/**
* Base class for both the compress and decompress classes. Holds common arrays,
* and static data.
*
* @author Commons VFS team
*/
final class BZip2Constants
{
public static final int BASE_BLOCK_SIZE = 100000;
public static final int MAX_ALPHA_SIZE = 258;
public static final int MAX_CODE_LEN = 23;
public static final int RUNA = 0;
public static final int RUNB = 1;
public static final int N_GROUPS = 6;
public static final int G_SIZE = 50;
public static final int N_ITERS = 4;
public static final int MAX_SELECTORS = (2 + (900000 / G_SIZE));
public static final int NUM_OVERSHOOT_BYTES = 20;
public static final int[] RAND_NUMS = new int[]
{
619, 720, 127, 481, 931, 816, 813, 233, 566, 247,
985, 724, 205, 454, 863, 491, 741, 242, 949, 214,
733, 859, 335, 708, 621, 574, 73, 654, 730, 472,
419, 436, 278, 496, 867, 210, 399, 680, 480, 51,
878, 465, 811, 169, 869, 675, 611, 697, 867, 561,
862, 687, 507, 283, 482, 129, 807, 591, 733, 623,
150, 238, 59, 379, 684, 877, 625, 169, 643, 105,
170, 607, 520, 932, 727, 476, 693, 425, 174, 647,
73, 122, 335, 530, 442, 853, 695, 249, 445, 515,
909, 545, 703, 919, 874, 474, 882, 500, 594, 612,
641, 801, 220, 162, 819, 984, 589, 513, 495, 799,
161, 604, 958, 533, 221, 400, 386, 867, 600, 782,
382, 596, 414, 171, 516, 375, 682, 485, 911, 276,
98, 553, 163, 354, 666, 933, 424, 341, 533, 870,
227, 730, 475, 186, 263, 647, 537, 686, 600, 224,
469, 68, 770, 919, 190, 373, 294, 822, 808, 206,
184, 943, 795, 384, 383, 461, 404, 758, 839, 887,
715, 67, 618, 276, 204, 918, 873, 777, 604, 560,
951, 160, 578, 722, 79, 804, 96, 409, 713, 940,
652, 934, 970, 447, 318, 353, 859, 672, 112, 785,
645, 863, 803, 350, 139, 93, 354, 99, 820, 908,
609, 772, 154, 274, 580, 184, 79, 626, 630, 742,
653, 282, 762, 623, 680, 81, 927, 626, 789, 125,
411, 521, 938, 300, 821, 78, 343, 175, 128, 250,
170, 774, 972, 275, 999, 639, 495, 78, 352, 126,
857, 956, 358, 619, 580, 124, 737, 594, 701, 612,
669, 112, 134, 694, 363, 992, 809, 743, 168, 974,
944, 375, 748, 52, 600, 747, 642, 182, 862, 81,
344, 805, 988, 739, 511, 655, 814, 334, 249, 515,
897, 955, 664, 981, 649, 113, 974, 459, 893, 228,
433, 837, 553, 268, 926, 240, 102, 654, 459, 51,
686, 754, 806, 760, 493, 403, 415, 394, 687, 700,
946, 670, 656, 610, 738, 392, 760, 799, 887, 653,
978, 321, 576, 617, 626, 502, 894, 679, 243, 440,
680, 879, 194, 572, 640, 724, 926, 56, 204, 700,
707, 151, 457, 449, 797, 195, 791, 558, 945, 679,
297, 59, 87, 824, 713, 663, 412, 693, 342, 606,
134, 108, 571, 364, 631, 212, 174, 643, 304, 329,
343, 97, 430, 751, 497, 314, 983, 374, 822, 928,
140, 206, 73, 263, 980, 736, 876, 478, 430, 305,
170, 514, 364, 692, 829, 82, 855, 953, 676, 246,
369, 970, 294, 750, 807, 827, 150, 790, 288, 923,
804, 378, 215, 828, 592, 281, 565, 555, 710, 82,
896, 831, 547, 261, 524, 462, 293, 465, 502, 56,
661, 821, 976, 991, 658, 869, 905, 758, 745, 193,
768, 550, 608, 933, 378, 286, 215, 979, 792, 961,
61, 688, 793, 644, 986, 403, 106, 366, 905, 644,
372, 567, 466, 434, 645, 210, 389, 550, 919, 135,
780, 773, 635, 389, 707, 100, 626, 958, 165, 504,
920, 176, 193, 713, 857, 265, 203, 50, 668, 108,
645, 990, 626, 197, 510, 357, 358, 850, 858, 364,
936, 638
};
/**
* Prevent instantiation.
*/
private BZip2Constants()
{
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileObject.java 100644 765 24 5124 11623215064 31720 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.bzip2;
//TODO: Revert to [compress]
//import org.apache.commons.compress.bzip2.CBZip2InputStream;
//import org.apache.commons.compress.bzip2.CBZip2OutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileObject;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
/**
* the bzip2 file.
*
* @author Commons VFS team
*/
public class Bzip2FileObject extends CompressedFileFileObject
{
protected Bzip2FileObject(AbstractFileName name, FileObject container, CompressedFileFileSystem fs)
{
super(name, container, fs);
}
@Override
protected InputStream doGetInputStream() throws Exception
{
// check file
InputStream is = getContainer().getContent().getInputStream();
return wrapInputStream(getName().getURI(), is);
}
public static InputStream wrapInputStream(final String name, final InputStream is) throws IOException
{
final int b1 = is.read();
final int b2 = is.read();
if (b1 != 'B' || b2 != 'Z')
{
throw new FileSystemException("vfs.provider.compressedFile/not-a-compressedFile-file.error", name);
}
return new CBZip2InputStream(is);
}
@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
OutputStream os = getContainer().getContent().getOutputStream(false);
os.write('B');
os.write('Z');
return new CBZip2OutputStream(os);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileProvider.java 100644 765 24 5002 11623215064 32277 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.bzip2;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileProvider;
/**
* Provides access to the content of bzip2 compressed files.
*
* @author Commons VFS team
*/
public class Bzip2FileProvider extends CompressedFileFileProvider
{
/** The provider's capabilities */
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.GET_LAST_MODIFIED,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.WRITE_CONTENT,
Capability.URI,
Capability.COMPRESS
}));
public Bzip2FileProvider()
{
super();
}
@Override
protected FileSystem createFileSystem(FileName name, FileObject file,
FileSystemOptions fileSystemOptions)
throws FileSystemException
{
return new Bzip2FileSystem(name, file, fileSystemOptions);
}
@Override
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/Bzip2FileSystem.java 100644 765 24 3677 11623215064 32011 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.bzip2;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
/**
* Filesytem to handle compressed files using the bzip2 method.
*
* @author Commons VFS team
*/
public class Bzip2FileSystem extends CompressedFileFileSystem
{
protected Bzip2FileSystem(FileName rootName, FileObject parentLayer, FileSystemOptions fileSystemOptions)
{
super(rootName, parentLayer, fileSystemOptions);
}
@Override
protected FileObject createFile(AbstractFileName name) throws FileSystemException
{
return new Bzip2FileObject(name, getParentLayer(), this);
}
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(Bzip2FileProvider.capabilities);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/CBZip2InputStream.java 100644 765 24 61331 11623215064 32252 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.bzip2;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.BASE_BLOCK_SIZE;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.G_SIZE;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.MAX_ALPHA_SIZE;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.MAX_CODE_LEN;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.MAX_SELECTORS;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.N_GROUPS;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.RAND_NUMS;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.RUNA;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.RUNB;
import java.io.IOException;
import java.io.InputStream;
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* to whom the Ant project is very grateful for his
* great code.
*/
/**
* An input stream that decompresses from the BZip2 format (without the file
* header chars) to be read as any other stream.
*
* @author Commons VFS team
*/
class CBZip2InputStream extends InputStream
{
private static final int START_BLOCK_STATE = 1;
private static final int RAND_PART_A_STATE = 2;
private static final int RAND_PART_B_STATE = 3;
private static final int RAND_PART_C_STATE = 4;
private static final int NO_RAND_PART_A_STATE = 5;
private static final int NO_RAND_PART_B_STATE = 6;
private static final int NO_RAND_PART_C_STATE = 7;
private CRC crc = new CRC();
private boolean[] inUse = new boolean[256];
private char[] seqToUnseq = new char[256];
private char[] unseqToSeq = new char[256];
private char[] selector = new char[MAX_SELECTORS];
private char[] selectorMtf = new char[MAX_SELECTORS];
/*
* freq table collected to save a pass over the data
* during decompression.
*/
private int[] unzftab = new int[256];
private int[][] limit = new int[N_GROUPS][MAX_ALPHA_SIZE];
private int[][] base = new int[N_GROUPS][MAX_ALPHA_SIZE];
private int[][] perm = new int[N_GROUPS][MAX_ALPHA_SIZE];
private int[] minLens = new int[N_GROUPS];
private boolean streamEnd;
private int currentChar = -1;
private int currentState = START_BLOCK_STATE;
private int rNToGo;
private int rTPos;
private int tPos;
private int i2;
private int count;
private int chPrev;
private int ch2;
private int j2;
private char z;
private boolean blockRandomised;
/*
* always: in the range 0 .. 9.
* The current block size is 100000 * this number.
*/
private int blockSize100k;
private int bsBuff;
private int bsLive;
private InputStream inputStream;
private int computedBlockCRC;
private int computedCombinedCRC;
/*
* index of the last char in the block, so
* the block size == last + 1.
*/
private int last;
private char[] mll8;
private int nInUse;
/*
* index in zptr[] of original string after sorting.
*/
private int origPtr;
private int storedBlockCRC;
private int storedCombinedCRC;
private int[] tt;
CBZip2InputStream(final InputStream input)
{
bsSetStream(input);
initialize();
initBlock();
setupBlock();
}
private static void badBlockHeader()
{
cadvise();
}
private static void blockOverrun()
{
cadvise();
}
private static void cadvise()
{
System.out.println("CRC Error");
//throw new CCoruptionError();
}
private static void compressedStreamEOF()
{
cadvise();
}
private static void crcError()
{
cadvise();
}
/**
* a fake available
which always returns 1 as long as the stream is not at end.
* This is required to make this stream work if wrapped in an BufferedInputStream.
*
*/
@Override
public int available() throws IOException
{
if (!streamEnd)
{
return 1;
}
return 0;
}
@Override
public int read()
{
if (streamEnd)
{
return -1;
}
else
{
int retChar = currentChar;
switch (currentState)
{
case START_BLOCK_STATE:
break;
case RAND_PART_A_STATE:
break;
case RAND_PART_B_STATE:
setupRandPartB();
break;
case RAND_PART_C_STATE:
setupRandPartC();
break;
case NO_RAND_PART_A_STATE:
break;
case NO_RAND_PART_B_STATE:
setupNoRandPartB();
break;
case NO_RAND_PART_C_STATE:
setupNoRandPartC();
break;
default:
break;
}
return retChar;
}
}
private void setDecompressStructureSizes(int newSize100k)
{
if (!(0 <= newSize100k && newSize100k <= 9 && 0 <= blockSize100k
&& blockSize100k <= 9))
{
// throw new IOException("Invalid block size");
}
blockSize100k = newSize100k;
if (newSize100k == 0)
{
return;
}
int n = BASE_BLOCK_SIZE * newSize100k;
mll8 = new char[n];
tt = new int[n];
}
private void setupBlock()
{
int[] cftab = new int[257];
char ch;
cftab[0] = 0;
for (int i = 1; i <= 256; i++)
{
cftab[i] = unzftab[i - 1];
}
for (int i = 1; i <= 256; i++)
{
cftab[i] += cftab[i - 1];
}
for (int i = 0; i <= last; i++)
{
ch = mll8[i];
tt[cftab[ch]] = i;
cftab[ch]++;
}
cftab = null;
tPos = tt[origPtr];
count = 0;
i2 = 0;
ch2 = 256;
/*
* not a char and not EOF
*/
if (blockRandomised)
{
rNToGo = 0;
rTPos = 0;
setupRandPartA();
}
else
{
setupNoRandPartA();
}
}
private void setupNoRandPartA()
{
if (i2 <= last)
{
chPrev = ch2;
ch2 = mll8[tPos];
tPos = tt[tPos];
i2++;
currentChar = ch2;
currentState = NO_RAND_PART_B_STATE;
crc.updateCRC(ch2);
}
else
{
endBlock();
initBlock();
setupBlock();
}
}
private void setupNoRandPartB()
{
if (ch2 != chPrev)
{
currentState = NO_RAND_PART_A_STATE;
count = 1;
setupNoRandPartA();
}
else
{
count++;
if (count >= 4)
{
z = mll8[tPos];
tPos = tt[tPos];
currentState = NO_RAND_PART_C_STATE;
j2 = 0;
setupNoRandPartC();
}
else
{
currentState = NO_RAND_PART_A_STATE;
setupNoRandPartA();
}
}
}
private void setupNoRandPartC()
{
if (j2 < z)
{
currentChar = ch2;
crc.updateCRC(ch2);
j2++;
}
else
{
currentState = NO_RAND_PART_A_STATE;
i2++;
count = 0;
setupNoRandPartA();
}
}
private void setupRandPartA()
{
if (i2 <= last)
{
chPrev = ch2;
ch2 = mll8[tPos];
tPos = tt[tPos];
if (rNToGo == 0)
{
rNToGo = RAND_NUMS[rTPos];
rTPos++;
if (rTPos == 512)
{
rTPos = 0;
}
}
rNToGo--;
ch2 ^= ((rNToGo == 1) ? 1 : 0);
i2++;
currentChar = ch2;
currentState = RAND_PART_B_STATE;
crc.updateCRC(ch2);
}
else
{
endBlock();
initBlock();
setupBlock();
}
}
private void setupRandPartB()
{
if (ch2 != chPrev)
{
currentState = RAND_PART_A_STATE;
count = 1;
setupRandPartA();
}
else
{
count++;
if (count >= 4)
{
z = mll8[tPos];
tPos = tt[tPos];
if (rNToGo == 0)
{
rNToGo = RAND_NUMS[rTPos];
rTPos++;
if (rTPos == 512)
{
rTPos = 0;
}
}
rNToGo--;
z ^= ((rNToGo == 1) ? 1 : 0);
j2 = 0;
currentState = RAND_PART_C_STATE;
setupRandPartC();
}
else
{
currentState = RAND_PART_A_STATE;
setupRandPartA();
}
}
}
private void setupRandPartC()
{
if (j2 < z)
{
currentChar = ch2;
crc.updateCRC(ch2);
j2++;
}
else
{
currentState = RAND_PART_A_STATE;
i2++;
count = 0;
setupRandPartA();
}
}
private void getAndMoveToFrontDecode()
{
int nextSym;
int limitLast = BASE_BLOCK_SIZE * blockSize100k;
origPtr = readVariableSizedInt(24);
recvDecodingTables();
int eob = nInUse + 1;
int groupNo = -1;
int groupPos = 0;
/*
* Setting up the unzftab entries here is not strictly
* necessary, but it does save having to do it later
* in a separate pass, and so saves a block's worth of
* cache misses.
*/
for (int i = 0; i <= 255; i++)
{
unzftab[i] = 0;
}
final char[] yy = new char[256];
for (int i = 0; i <= 255; i++)
{
yy[i] = (char) i;
}
last = -1;
int zt;
int zn;
int zvec;
int zj;
groupNo++;
groupPos = G_SIZE - 1;
zt = selector[groupNo];
zn = minLens[zt];
zvec = bsR(zn);
while (zvec > limit[zt][zn])
{
zn++;
while (bsLive < 1)
{
int zzi = 0;
try
{
zzi = inputStream.read();
}
catch (IOException e)
{
compressedStreamEOF();
}
if (zzi == -1)
{
compressedStreamEOF();
}
bsBuff = (bsBuff << 8) | (zzi & 0xff);
bsLive += 8;
}
zj = (bsBuff >> (bsLive - 1)) & 1;
bsLive--;
zvec = (zvec << 1) | zj;
}
nextSym = perm[zt][zvec - base[zt][zn]];
while (true)
{
if (nextSym == eob)
{
break;
}
if (nextSym == RUNA || nextSym == RUNB)
{
char ch;
int s = -1;
int n = 1;
do
{
if (nextSym == RUNA)
{
s = s + (0 + 1) * n;
}
else // if( nextSym == RUNB )
{
s = s + (1 + 1) * n;
}
n = n * 2;
if (groupPos == 0)
{
groupNo++;
groupPos = G_SIZE;
}
groupPos--;
zt = selector[groupNo];
zn = minLens[zt];
zvec = bsR(zn);
while (zvec > limit[zt][zn])
{
zn++;
while (bsLive < 1)
{
int zzi = 0;
try
{
zzi = inputStream.read();
}
catch (IOException e)
{
compressedStreamEOF();
}
if (zzi == -1)
{
compressedStreamEOF();
}
bsBuff = (bsBuff << 8) | (zzi & 0xff);
bsLive += 8;
}
zj = (bsBuff >> (bsLive - 1)) & 1;
bsLive--;
zvec = (zvec << 1) | zj;
}
nextSym = perm[zt][zvec - base[zt][zn]];
}
while (nextSym == RUNA || nextSym == RUNB);
s++;
ch = seqToUnseq[yy[0]];
unzftab[ch] += s;
while (s > 0)
{
last++;
mll8[last] = ch;
s--;
}
if (last >= limitLast)
{
blockOverrun();
}
continue;
}
else
{
char tmp;
last++;
if (last >= limitLast)
{
blockOverrun();
}
tmp = yy[nextSym - 1];
unzftab[seqToUnseq[tmp]]++;
mll8[last] = seqToUnseq[tmp];
/*
* This loop is hammered during decompression,
* hence the unrolling.
* for (j = nextSym-1; j > 0; j--) yy[j] = yy[j-1];
*/
int j = nextSym - 1;
for (; j > 3; j -= 4)
{
yy[j] = yy[j - 1];
yy[j - 1] = yy[j - 2];
yy[j - 2] = yy[j - 3];
yy[j - 3] = yy[j - 4];
}
for (; j > 0; j--)
{
yy[j] = yy[j - 1];
}
yy[0] = tmp;
if (groupPos == 0)
{
groupNo++;
groupPos = G_SIZE;
}
groupPos--;
zt = selector[groupNo];
zn = minLens[zt];
zvec = bsR(zn);
while (zvec > limit[zt][zn])
{
zn++;
while (bsLive < 1)
{
char ch = 0;
try
{
ch = (char) inputStream.read();
}
catch (IOException e)
{
compressedStreamEOF();
}
bsBuff = (bsBuff << 8) | (ch & 0xff);
bsLive += 8;
}
zj = (bsBuff >> (bsLive - 1)) & 1;
bsLive--;
zvec = (zvec << 1) | zj;
}
nextSym = perm[zt][zvec - base[zt][zn]];
continue;
}
}
}
private void bsFinishedWithStream()
{
if (inputStream != null)
{
try
{
inputStream.close();
}
catch (IOException e)
{
// Ignore the exception.
}
}
inputStream = null;
}
private int readVariableSizedInt(final int numBits)
{
return bsR(numBits);
}
private char readUnsignedChar()
{
return (char) bsR(8);
}
private int readInt()
{
int u = 0;
u = (u << 8) | bsR(8);
u = (u << 8) | bsR(8);
u = (u << 8) | bsR(8);
u = (u << 8) | bsR(8);
return u;
}
private int bsR(final int n)
{
while (bsLive < n)
{
int ch = 0;
try
{
ch = inputStream.read();
}
catch (final IOException ioe)
{
compressedStreamEOF();
}
if (ch == -1)
{
compressedStreamEOF();
}
bsBuff = (bsBuff << 8) | (ch & 0xff);
bsLive += 8;
}
final int result = (bsBuff >> (bsLive - n)) & ((1 << n) - 1);
bsLive -= n;
return result;
}
private void bsSetStream(final InputStream input)
{
inputStream = input;
bsLive = 0;
bsBuff = 0;
}
private void complete()
{
storedCombinedCRC = readInt();
if (storedCombinedCRC != computedCombinedCRC)
{
crcError();
}
bsFinishedWithStream();
streamEnd = true;
}
private void endBlock()
{
computedBlockCRC = crc.getFinalCRC();
/*
* A bad CRC is considered a fatal error.
*/
if (storedBlockCRC != computedBlockCRC)
{
crcError();
}
computedCombinedCRC = (computedCombinedCRC << 1)
| (computedCombinedCRC >>> 31);
computedCombinedCRC ^= computedBlockCRC;
}
private void hbCreateDecodeTables(final int[] limit,
final int[] base,
final int[] perm,
final char[] length,
final int minLen,
final int maxLen,
final int alphaSize)
{
int pp = 0;
for (int i = minLen; i <= maxLen; i++)
{
for (int j = 0; j < alphaSize; j++)
{
if (length[j] == i)
{
perm[pp] = j;
pp++;
}
}
}
for (int i = 0; i < MAX_CODE_LEN; i++)
{
base[i] = 0;
}
for (int i = 0; i < alphaSize; i++)
{
base[length[i] + 1]++;
}
for (int i = 1; i < MAX_CODE_LEN; i++)
{
base[i] += base[i - 1];
}
for (int i = 0; i < MAX_CODE_LEN; i++)
{
limit[i] = 0;
}
int vec = 0;
for (int i = minLen; i <= maxLen; i++)
{
vec += (base[i + 1] - base[i]);
limit[i] = vec - 1;
vec <<= 1;
}
for (int i = minLen + 1; i <= maxLen; i++)
{
base[i] = ((limit[i - 1] + 1) << 1) - base[i];
}
}
private void initBlock()
{
final char magic1 = readUnsignedChar();
final char magic2 = readUnsignedChar();
final char magic3 = readUnsignedChar();
final char magic4 = readUnsignedChar();
final char magic5 = readUnsignedChar();
final char magic6 = readUnsignedChar();
if (magic1 == 0x17 && magic2 == 0x72 && magic3 == 0x45 &&
magic4 == 0x38 && magic5 == 0x50 && magic6 == 0x90)
{
complete();
return;
}
if (magic1 != 0x31 || magic2 != 0x41 || magic3 != 0x59 ||
magic4 != 0x26 || magic5 != 0x53 || magic6 != 0x59)
{
badBlockHeader();
streamEnd = true;
return;
}
storedBlockCRC = readInt();
if (bsR(1) == 1)
{
blockRandomised = true;
}
else
{
blockRandomised = false;
}
// currBlockNo++;
getAndMoveToFrontDecode();
crc.initialiseCRC();
currentState = START_BLOCK_STATE;
}
private void initialize()
{
final char magic3 = readUnsignedChar();
final char magic4 = readUnsignedChar();
if (magic3 != 'h' || magic4 < '1' || magic4 > '9')
{
bsFinishedWithStream();
streamEnd = true;
return;
}
setDecompressStructureSizes(magic4 - '0');
computedCombinedCRC = 0;
}
private void makeMaps()
{
nInUse = 0;
for (int i = 0; i < 256; i++)
{
if (inUse[i])
{
seqToUnseq[nInUse] = (char) i;
unseqToSeq[i] = (char) nInUse;
nInUse++;
}
}
}
private void recvDecodingTables()
{
buildInUseTable();
makeMaps();
final int alphaSize = nInUse + 2;
/*
* Now the selectors
*/
final int groupCount = bsR(3);
final int selectorCount = bsR(15);
for (int i = 0; i < selectorCount; i++)
{
int run = 0;
while (bsR(1) == 1)
{
run++;
}
selectorMtf[i] = (char) run;
}
/*
* Undo the MTF values for the selectors.
*/
final char[] pos = new char[N_GROUPS];
for (char v = 0; v < groupCount; v++)
{
pos[v] = v;
}
for (int i = 0; i < selectorCount; i++)
{
int v = selectorMtf[i];
final char tmp = pos[v];
while (v > 0)
{
pos[v] = pos[v - 1];
v--;
}
pos[0] = tmp;
selector[i] = tmp;
}
final char[][] len = new char[N_GROUPS][MAX_ALPHA_SIZE];
/*
* Now the coding tables
*/
for (int i = 0; i < groupCount; i++)
{
int curr = bsR(5);
for (int j = 0; j < alphaSize; j++)
{
while (bsR(1) == 1)
{
if (bsR(1) == 0)
{
curr++;
}
else
{
curr--;
}
}
len[i][j] = (char) curr;
}
}
/*
* Create the Huffman decoding tables
*/
for (int k = 0; k < groupCount; k++)
{
int minLen = 32;
int maxLen = 0;
for (int i = 0; i < alphaSize; i++)
{
if (len[k][i] > maxLen)
{
maxLen = len[k][i];
}
if (len[k][i] < minLen)
{
minLen = len[k][i];
}
}
hbCreateDecodeTables(limit[k], base[k], perm[k], len[k], minLen,
maxLen, alphaSize);
minLens[k] = minLen;
}
}
private void buildInUseTable()
{
final boolean[] inUse16 = new boolean[16];
/*
* Receive the mapping table
*/
for (int i = 0; i < 16; i++)
{
if (bsR(1) == 1)
{
inUse16[i] = true;
}
else
{
inUse16[i] = false;
}
}
for (int i = 0; i < 256; i++)
{
inUse[i] = false;
}
for (int i = 0; i < 16; i++)
{
if (inUse16[i])
{
for (int j = 0; j < 16; j++)
{
if (bsR(1) == 1)
{
inUse[i * 16 + j] = true;
}
}
}
}
}
@Override
public void close() throws IOException
{
bsFinishedWithStream();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/CBZip2OutputStream.java 100644 765 24 147370 11623215064 32503 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.bzip2;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.BASE_BLOCK_SIZE;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.G_SIZE;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.MAX_ALPHA_SIZE;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.MAX_SELECTORS;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.NUM_OVERSHOOT_BYTES;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.N_GROUPS;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.N_ITERS;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.RAND_NUMS;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.RUNA;
import static org.apache.commons.vfs2.provider.bzip2.BZip2Constants.RUNB;
import java.io.IOException;
import java.io.OutputStream;
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* to whom the Ant project is very grateful for his
* great code.
*/
/**
* An output stream that compresses into the BZip2 format (without the file
* header chars) into another stream. TODO: Update to BZip2 1.0.1
*
* @author Commons VFS team
*/
class CBZip2OutputStream extends OutputStream
{
private static final int LOWER_BYTE_MASK = 0x000000ff;
private static final int UPPER_BYTE_MASK = 0xffffff00;
private static final int SETMASK = (1 << 21);
private static final int CLEARMASK = (~SETMASK);
private static final int GREATER_ICOST = 15;
private static final int LESSER_ICOST = 0;
private static final int SMALL_THRESH = 20;
private static final int DEPTH_THRESH = 10;
/*
* If you are ever unlucky/improbable enough
* to get a stack overflow whilst sorting,
* increase the following constant and try
* again. In practice I have never seen the
* stack go above 27 elems, so the following
* limit seems very generous.
*/
private static final int QSORT_STACK_SIZE = 1000;
private CRC crc = new CRC();
private boolean[] inUse = new boolean[256];
private char[] seqToUnseq = new char[256];
private char[] unseqToSeq = new char[256];
private char[] selector = new char[MAX_SELECTORS];
private char[] selectorMtf = new char[MAX_SELECTORS];
private int[] mtfFreq = new int[MAX_ALPHA_SIZE];
private int currentChar = -1;
private int runLength;
private boolean closed;
/*
* Knuth's increments seem to work better
* than Incerpi-Sedgewick here. Possibly
* because the number of elems to sort is
* usually small, typically <= 20.
*/
private int[] incs = new int[]
{
1, 4, 13, 40, 121, 364, 1093, 3280,
9841, 29524, 88573, 265720,
797161, 2391484
};
private boolean blockRandomised;
/*
* always: in the range 0 .. 9.
* The current block size is 100000 * this number.
*/
private int blockSize100k;
private int bsBuff;
private int bsLive;
/*
* index of the last char in the block, so
* the block size == last + 1.
*/
private int last;
/*
* index in zptr[] of original string after sorting.
*/
private int origPtr;
private int allowableBlockSize;
private char[] block;
private int blockCRC;
private int combinedCRC;
private OutputStream bsStream;
private boolean firstAttempt;
private int[] ftab;
private int nInUse;
private int nMTF;
private int[] quadrant;
private short[] szptr;
private int workDone;
/*
* Used when sorting. If too many long comparisons
* happen, we stop sorting, randomise the block
* slightly, and try again.
*/
private int workFactor;
private int workLimit;
private int[] zptr;
CBZip2OutputStream(final OutputStream output)
throws IOException
{
this(output, 9);
}
CBZip2OutputStream(final OutputStream output, final int blockSize)
throws IOException
{
bsSetStream(output);
workFactor = 50;
int outBlockSize = blockSize;
if (outBlockSize > 9)
{
outBlockSize = 9;
}
if (outBlockSize < 1)
{
outBlockSize = 1;
}
blockSize100k = outBlockSize;
allocateCompressStructures();
initialize();
initBlock();
}
private static void hbMakeCodeLengths(char[] len, int[] freq,
int alphaSize, int maxLen)
{
/*
* Nodes and heap entries run from 1. Entry 0
* for both the heap and nodes is a sentinel.
*/
int nNodes;
/*
* Nodes and heap entries run from 1. Entry 0
* for both the heap and nodes is a sentinel.
*/
int nHeap;
/*
* Nodes and heap entries run from 1. Entry 0
* for both the heap and nodes is a sentinel.
*/
int n1;
/*
* Nodes and heap entries run from 1. Entry 0
* for both the heap and nodes is a sentinel.
*/
int n2;
/*
* Nodes and heap entries run from 1. Entry 0
* for both the heap and nodes is a sentinel.
*/
int i;
/*
* Nodes and heap entries run from 1. Entry 0
* for both the heap and nodes is a sentinel.
*/
int j;
/*
* Nodes and heap entries run from 1. Entry 0
* for both the heap and nodes is a sentinel.
*/
int k;
boolean tooLong;
int[] heap = new int[MAX_ALPHA_SIZE + 2];
int[] weights = new int[MAX_ALPHA_SIZE * 2];
int[] parent = new int[MAX_ALPHA_SIZE * 2];
for (i = 0; i < alphaSize; i++)
{
weights[i + 1] = (freq[i] == 0 ? 1 : freq[i]) << 8;
}
while (true)
{
nNodes = alphaSize;
nHeap = 0;
heap[0] = 0;
weights[0] = 0;
parent[0] = -2;
for (i = 1; i <= alphaSize; i++)
{
parent[i] = -1;
nHeap++;
heap[nHeap] = i;
{
int zz;
int tmp;
zz = nHeap;
tmp = heap[zz];
while (weights[tmp] < weights[heap[zz >> 1]])
{
heap[zz] = heap[zz >> 1];
zz >>= 1;
}
heap[zz] = tmp;
}
}
if (!(nHeap < (MAX_ALPHA_SIZE + 2)))
{
panic();
}
while (nHeap > 1)
{
n1 = heap[1];
heap[1] = heap[nHeap];
nHeap--;
{
int zz = 0;
int yy = 0;
int tmp = 0;
zz = 1;
tmp = heap[zz];
while (true)
{
yy = zz << 1;
if (yy > nHeap)
{
break;
}
if (yy < nHeap &&
weights[heap[yy + 1]] < weights[heap[yy]])
{
yy++;
}
if (weights[tmp] < weights[heap[yy]])
{
break;
}
heap[zz] = heap[yy];
zz = yy;
}
heap[zz] = tmp;
}
n2 = heap[1];
heap[1] = heap[nHeap];
nHeap--;
{
int zz = 0;
int yy = 0;
int tmp = 0;
zz = 1;
tmp = heap[zz];
while (true)
{
yy = zz << 1;
if (yy > nHeap)
{
break;
}
if (yy < nHeap &&
weights[heap[yy + 1]] < weights[heap[yy]])
{
yy++;
}
if (weights[tmp] < weights[heap[yy]])
{
break;
}
heap[zz] = heap[yy];
zz = yy;
}
heap[zz] = tmp;
}
nNodes++;
parent[n1] = nNodes;
parent[n2] = nNodes;
final int v1 = weights[n1];
final int v2 = weights[n2];
final int weight = calculateWeight(v1, v2);
weights[nNodes] = weight;
parent[nNodes] = -1;
nHeap++;
heap[nHeap] = nNodes;
{
int zz = 0;
int tmp = 0;
zz = nHeap;
tmp = heap[zz];
while (weights[tmp] < weights[heap[zz >> 1]])
{
heap[zz] = heap[zz >> 1];
zz >>= 1;
}
heap[zz] = tmp;
}
}
if (!(nNodes < (MAX_ALPHA_SIZE * 2)))
{
panic();
}
tooLong = false;
for (i = 1; i <= alphaSize; i++)
{
j = 0;
k = i;
while (parent[k] >= 0)
{
k = parent[k];
j++;
}
len[i - 1] = (char) j;
if (j > maxLen)
{
tooLong = true;
}
}
if (!tooLong)
{
break;
}
for (i = 1; i < alphaSize; i++)
{
j = weights[i] >> 8;
j = 1 + (j / 2);
weights[i] = j << 8;
}
}
}
private static int calculateWeight(final int v1, final int v2)
{
final int upper = (v1 & UPPER_BYTE_MASK) + (v2 & UPPER_BYTE_MASK);
final int v1Lower = (v1 & LOWER_BYTE_MASK);
final int v2Lower = (v2 & LOWER_BYTE_MASK);
final int nnnn = (v1Lower > v2Lower) ? v1Lower : v2Lower;
return upper | (1 + nnnn);
}
private static void panic()
{
System.out.println("panic");
//throw new CError();
}
@Override
public void close()
throws IOException
{
if (closed)
{
return;
}
if (runLength > 0)
{
writeRun();
}
currentChar = -1;
endBlock();
endCompression();
closed = true;
super.close();
bsStream.close();
}
@Override
public void finalize()
throws Throwable
{
close();
}
@Override
public void flush()
throws IOException
{
super.flush();
bsStream.flush();
}
/**
* modified by Oliver Merkel, 010128
*
* @param bv Description of Parameter
* @throws java.io.IOException Description of Exception
*/
@Override
public void write(int bv)
throws IOException
{
int b = (256 + bv) % 256;
if (currentChar != -1)
{
if (currentChar == b)
{
runLength++;
if (runLength > 254)
{
writeRun();
currentChar = -1;
runLength = 0;
}
}
else
{
writeRun();
runLength = 1;
currentChar = b;
}
}
else
{
currentChar = b;
runLength++;
}
}
private void allocateCompressStructures()
{
int n = BASE_BLOCK_SIZE * blockSize100k;
block = new char[(n + 1 + NUM_OVERSHOOT_BYTES)];
quadrant = new int[(n + NUM_OVERSHOOT_BYTES)];
zptr = new int[n];
ftab = new int[65537];
if (block == null || quadrant == null || zptr == null
|| ftab == null)
{
//int totalDraw = (n + 1 + NUM_OVERSHOOT_BYTES) + (n + NUM_OVERSHOOT_BYTES) + n + 65537;
//compressOutOfMemory ( totalDraw, n );
}
/*
* The back end needs a place to store the MTF values
* whilst it calculates the coding tables. We could
* put them in the zptr array. However, these values
* will fit in a short, so we overlay szptr at the
* start of zptr, in the hope of reducing the number
* of cache misses induced by the multiple traversals
* of the MTF values when calculating coding tables.
* Seems to improve compression speed by about 1%.
*/
// szptr = zptr;
szptr = new short[2 * n];
}
private void bsFinishedWithStream()
throws IOException
{
while (bsLive > 0)
{
int ch = (bsBuff >> 24);
try
{
bsStream.write(ch); // write 8-bit
}
catch (IOException e)
{
throw e;
}
bsBuff <<= 8;
bsLive -= 8;
}
}
private void bsPutIntVS(int numBits, int c)
throws IOException
{
bsW(numBits, c);
}
private void bsPutUChar(int c)
throws IOException
{
bsW(8, c);
}
private void bsPutint(int u)
throws IOException
{
bsW(8, (u >> 24) & 0xff);
bsW(8, (u >> 16) & 0xff);
bsW(8, (u >> 8) & 0xff);
bsW(8, u & 0xff);
}
private void bsSetStream(OutputStream f)
{
bsStream = f;
bsLive = 0;
bsBuff = 0;
}
private void bsW(int n, int v)
throws IOException
{
while (bsLive >= 8)
{
int ch = (bsBuff >> 24);
try
{
bsStream.write(ch); // write 8-bit
}
catch (IOException e)
{
throw e;
}
bsBuff <<= 8;
bsLive -= 8;
}
bsBuff |= (v << (32 - bsLive - n));
bsLive += n;
}
private void doReversibleTransformation()
{
int i;
workLimit = workFactor * last;
workDone = 0;
blockRandomised = false;
firstAttempt = true;
mainSort();
if (workDone > workLimit && firstAttempt)
{
randomiseBlock();
workLimit = 0;
workDone = 0;
blockRandomised = true;
firstAttempt = false;
mainSort();
}
origPtr = -1;
for (i = 0; i <= last; i++)
{
if (zptr[i] == 0)
{
origPtr = i;
break;
}
}
if (origPtr == -1)
{
panic();
}
}
private void endBlock()
throws IOException
{
blockCRC = crc.getFinalCRC();
combinedCRC = (combinedCRC << 1) | (combinedCRC >>> 31);
combinedCRC ^= blockCRC;
/*
* sort the block and establish posn of original string
*/
doReversibleTransformation();
/*
* A 6-byte block header, the value chosen arbitrarily
* as 0x314159265359 :-). A 32 bit value does not really
* give a strong enough guarantee that the value will not
* appear by chance in the compressed datastream. Worst-case
* probability of this event, for a 900k block, is about
* 2.0e-3 for 32 bits, 1.0e-5 for 40 bits and 4.0e-8 for 48 bits.
* For a compressed file of size 100Gb -- about 100000 blocks --
* only a 48-bit marker will do. NB: normal compression/
* decompression do *not* rely on these statistical properties.
* They are only important when trying to recover blocks from
* damaged files.
*/
bsPutUChar(0x31);
bsPutUChar(0x41);
bsPutUChar(0x59);
bsPutUChar(0x26);
bsPutUChar(0x53);
bsPutUChar(0x59);
/*
* Now the block's CRC, so it is in a known place.
*/
bsPutint(blockCRC);
/*
* Now a single bit indicating randomisation.
*/
if (blockRandomised)
{
bsW(1, 1);
}
else
{
bsW(1, 0);
}
/*
* Finally, block's contents proper.
*/
moveToFrontCodeAndSend();
}
private void endCompression()
throws IOException
{
/*
* Now another magic 48-bit number, 0x177245385090, to
* indicate the end of the last block. (sqrt(pi), if
* you want to know. I did want to use e, but it contains
* too much repetition -- 27 18 28 18 28 46 -- for me
* to feel statistically comfortable. Call me paranoid.)
*/
bsPutUChar(0x17);
bsPutUChar(0x72);
bsPutUChar(0x45);
bsPutUChar(0x38);
bsPutUChar(0x50);
bsPutUChar(0x90);
bsPutint(combinedCRC);
bsFinishedWithStream();
}
private boolean fullGtU(int i1, int i2)
{
int k;
char c1;
char c2;
int s1;
int s2;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
i1++;
i2++;
k = last + 1;
do
{
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
s1 = quadrant[i1];
s2 = quadrant[i2];
if (s1 != s2)
{
return (s1 > s2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
s1 = quadrant[i1];
s2 = quadrant[i2];
if (s1 != s2)
{
return (s1 > s2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
s1 = quadrant[i1];
s2 = quadrant[i2];
if (s1 != s2)
{
return (s1 > s2);
}
i1++;
i2++;
c1 = block[i1 + 1];
c2 = block[i2 + 1];
if (c1 != c2)
{
return (c1 > c2);
}
s1 = quadrant[i1];
s2 = quadrant[i2];
if (s1 != s2)
{
return (s1 > s2);
}
i1++;
i2++;
if (i1 > last)
{
i1 -= last;
i1--;
}
if (i2 > last)
{
i2 -= last;
i2--;
}
k -= 4;
workDone++;
}
while (k >= 0);
return false;
}
private void generateMTFValues()
{
char[] yy = new char[256];
int i;
int j;
char tmp;
char tmp2;
int zPend;
int wr;
int eob;
makeMaps();
eob = nInUse + 1;
for (i = 0; i <= eob; i++)
{
mtfFreq[i] = 0;
}
wr = 0;
zPend = 0;
for (i = 0; i < nInUse; i++)
{
yy[i] = (char) i;
}
for (i = 0; i <= last; i++)
{
char ll_i;
ll_i = unseqToSeq[block[zptr[i]]];
j = 0;
tmp = yy[j];
while (ll_i != tmp)
{
j++;
tmp2 = tmp;
tmp = yy[j];
yy[j] = tmp2;
}
yy[0] = tmp;
if (j == 0)
{
zPend++;
}
else
{
if (zPend > 0)
{
zPend--;
while (true)
{
switch (zPend % 2)
{
case 0:
szptr[wr] = (short) RUNA;
wr++;
mtfFreq[RUNA]++;
break;
case 1:
szptr[wr] = (short) RUNB;
wr++;
mtfFreq[RUNB]++;
break;
}
if (zPend < 2)
{
break;
}
zPend = (zPend - 2) / 2;
}
zPend = 0;
}
szptr[wr] = (short) (j + 1);
wr++;
mtfFreq[j + 1]++;
}
}
if (zPend > 0)
{
zPend--;
while (true)
{
switch (zPend % 2)
{
case 0:
szptr[wr] = (short) RUNA;
wr++;
mtfFreq[RUNA]++;
break;
case 1:
szptr[wr] = (short) RUNB;
wr++;
mtfFreq[RUNB]++;
break;
}
if (zPend < 2)
{
break;
}
zPend = (zPend - 2) / 2;
}
}
szptr[wr] = (short) eob;
wr++;
mtfFreq[eob]++;
nMTF = wr;
}
private void hbAssignCodes(int[] code, char[] length, int minLen,
int maxLen, int alphaSize)
{
int n;
int vec;
int i;
vec = 0;
for (n = minLen; n <= maxLen; n++)
{
for (i = 0; i < alphaSize; i++)
{
if (length[i] == n)
{
code[i] = vec;
vec++;
}
}
vec <<= 1;
}
}
private void initBlock()
{
// blockNo++;
crc.initialiseCRC();
last = -1;
// ch = 0;
for (int i = 0; i < 256; i++)
{
inUse[i] = false;
}
/*
* 20 is just a paranoia constant
*/
allowableBlockSize = BASE_BLOCK_SIZE * blockSize100k - 20;
}
private void initialize()
throws IOException
{
/*
* Write `magic' bytes h indicating file-format == huffmanised,
* followed by a digit indicating blockSize100k.
*/
bsPutUChar('h');
bsPutUChar('0' + blockSize100k);
combinedCRC = 0;
}
private void mainSort()
{
int i;
int j;
int ss;
int sb;
int[] runningOrder = new int[256];
int[] copy = new int[256];
boolean[] bigDone = new boolean[256];
int c1;
int c2;
/*
* In the various block-sized structures, live data runs
* from 0 to last+NUM_OVERSHOOT_BYTES inclusive. First,
* set up the overshoot area for block.
*/
// if (verbosity >= 4) fprintf ( stderr, " sort initialise ...\n" );
for (i = 0; i < NUM_OVERSHOOT_BYTES; i++)
{
block[last + i + 2] = block[(i % (last + 1)) + 1];
}
for (i = 0; i <= last + NUM_OVERSHOOT_BYTES; i++)
{
quadrant[i] = 0;
}
block[0] = block[last + 1];
if (last < 4000)
{
/*
* Use simpleSort(), since the full sorting mechanism
* has quite a large constant overhead.
*/
for (i = 0; i <= last; i++)
{
zptr[i] = i;
}
firstAttempt = false;
workDone = 0;
workLimit = 0;
simpleSort(0, last, 0);
}
else
{
for (i = 0; i <= 255; i++)
{
bigDone[i] = false;
}
for (i = 0; i <= 65536; i++)
{
ftab[i] = 0;
}
c1 = block[0];
for (i = 0; i <= last; i++)
{
c2 = block[i + 1];
ftab[(c1 << 8) + c2]++;
c1 = c2;
}
for (i = 1; i <= 65536; i++)
{
ftab[i] += ftab[i - 1];
}
c1 = block[1];
for (i = 0; i < last; i++)
{
c2 = block[i + 2];
j = (c1 << 8) + c2;
c1 = c2;
ftab[j]--;
zptr[ftab[j]] = i;
}
j = ((block[last + 1]) << 8) + (block[1]);
ftab[j]--;
zptr[ftab[j]] = last;
/*
* Now ftab contains the first loc of every small bucket.
* Calculate the running order, from smallest to largest
* big bucket.
*/
for (i = 0; i <= 255; i++)
{
runningOrder[i] = i;
}
{
int vv;
int h = 1;
do
{
h = 3 * h + 1;
}
while (h <= 256);
do
{
h = h / 3;
for (i = h; i <= 255; i++)
{
vv = runningOrder[i];
j = i;
while ((ftab[((runningOrder[j - h]) + 1) << 8]
- ftab[(runningOrder[j - h]) << 8]) >
(ftab[((vv) + 1) << 8] - ftab[(vv) << 8]))
{
runningOrder[j] = runningOrder[j - h];
j = j - h;
if (j <= (h - 1))
{
break;
}
}
runningOrder[j] = vv;
}
}
while (h != 1);
}
/*
* The main sorting loop.
*/
for (i = 0; i <= 255; i++)
{
/*
* Process big buckets, starting with the least full.
*/
ss = runningOrder[i];
/*
* Complete the big bucket [ss] by quicksorting
* any unsorted small buckets [ss, j]. Hopefully
* previous pointer-scanning phases have already
* completed many of the small buckets [ss, j], so
* we don't have to sort them at all.
*/
for (j = 0; j <= 255; j++)
{
sb = (ss << 8) + j;
if (!((ftab[sb] & SETMASK) == SETMASK))
{
int lo = ftab[sb] & CLEARMASK;
int hi = (ftab[sb + 1] & CLEARMASK) - 1;
if (hi > lo)
{
qSort3(lo, hi, 2);
if (workDone > workLimit && firstAttempt)
{
return;
}
}
ftab[sb] |= SETMASK;
}
}
/*
* The ss big bucket is now done. Record this fact,
* and update the quadrant descriptors. Remember to
* update quadrants in the overshoot area too, if
* necessary. The "if (i < 255)" test merely skips
* this updating for the last bucket processed, since
* updating for the last bucket is pointless.
*/
bigDone[ss] = true;
if (i < 255)
{
int bbStart = ftab[ss << 8] & CLEARMASK;
int bbSize = (ftab[(ss + 1) << 8] & CLEARMASK) - bbStart;
int shifts = 0;
while ((bbSize >> shifts) > 65534)
{
shifts++;
}
for (j = 0; j < bbSize; j++)
{
int a2update = zptr[bbStart + j];
int qVal = (j >> shifts);
quadrant[a2update] = qVal;
if (a2update < NUM_OVERSHOOT_BYTES)
{
quadrant[a2update + last + 1] = qVal;
}
}
if (!(((bbSize - 1) >> shifts) <= 65535))
{
panic();
}
}
/*
* Now scan this big bucket so as to synthesise the
* sorted order for small buckets [t, ss] for all t != ss.
*/
for (j = 0; j <= 255; j++)
{
copy[j] = ftab[(j << 8) + ss] & CLEARMASK;
}
for (j = ftab[ss << 8] & CLEARMASK;
j < (ftab[(ss + 1) << 8] & CLEARMASK); j++)
{
c1 = block[zptr[j]];
if (!bigDone[c1])
{
zptr[copy[c1]] = zptr[j] == 0 ? last : zptr[j] - 1;
copy[c1]++;
}
}
for (j = 0; j <= 255; j++)
{
ftab[(j << 8) + ss] |= SETMASK;
}
}
}
}
private void makeMaps()
{
int i;
nInUse = 0;
for (i = 0; i < 256; i++)
{
if (inUse[i])
{
seqToUnseq[nInUse] = (char) i;
unseqToSeq[i] = (char) nInUse;
nInUse++;
}
}
}
private char med3(char a, char b, char c)
{
char t;
if (a > b)
{
t = a;
a = b;
b = t;
}
if (b > c)
{
t = b;
b = c;
c = t;
}
if (a > b)
{
b = a;
}
return b;
}
private void moveToFrontCodeAndSend()
throws IOException
{
bsPutIntVS(24, origPtr);
generateMTFValues();
sendMTFValues();
}
private void qSort3(int loSt, int hiSt, int dSt)
{
int unLo;
int unHi;
int ltLo;
int gtHi;
int med;
int n;
int m;
int sp;
int lo;
int hi;
int d;
StackElem[] stack = new StackElem[QSORT_STACK_SIZE];
for (int count = 0; count < QSORT_STACK_SIZE; count++)
{
stack[count] = new StackElem();
}
sp = 0;
stack[sp].ll = loSt;
stack[sp].hh = hiSt;
stack[sp].dd = dSt;
sp++;
while (sp > 0)
{
if (sp >= QSORT_STACK_SIZE)
{
panic();
}
sp--;
lo = stack[sp].ll;
hi = stack[sp].hh;
d = stack[sp].dd;
if (hi - lo < SMALL_THRESH || d > DEPTH_THRESH)
{
simpleSort(lo, hi, d);
if (workDone > workLimit && firstAttempt)
{
return;
}
continue;
}
med = med3(block[zptr[lo] + d + 1],
block[zptr[hi] + d + 1],
block[zptr[(lo + hi) >> 1] + d + 1]);
unLo = lo;
ltLo = lo;
unHi = hi;
gtHi = hi;
while (true)
{
while (true)
{
if (unLo > unHi)
{
break;
}
n = block[zptr[unLo] + d + 1] - med;
if (n == 0)
{
int temp = 0;
temp = zptr[unLo];
zptr[unLo] = zptr[ltLo];
zptr[ltLo] = temp;
ltLo++;
unLo++;
continue;
}
if (n > 0)
{
break;
}
unLo++;
}
while (true)
{
if (unLo > unHi)
{
break;
}
n = block[zptr[unHi] + d + 1] - med;
if (n == 0)
{
int temp = 0;
temp = zptr[unHi];
zptr[unHi] = zptr[gtHi];
zptr[gtHi] = temp;
gtHi--;
unHi--;
continue;
}
if (n < 0)
{
break;
}
unHi--;
}
if (unLo > unHi)
{
break;
}
int temp = 0;
temp = zptr[unLo];
zptr[unLo] = zptr[unHi];
zptr[unHi] = temp;
unLo++;
unHi--;
}
if (gtHi < ltLo)
{
stack[sp].ll = lo;
stack[sp].hh = hi;
stack[sp].dd = d + 1;
sp++;
continue;
}
n = ((ltLo - lo) < (unLo - ltLo)) ? (ltLo - lo) : (unLo - ltLo);
vswap(lo, unLo - n, n);
m = ((hi - gtHi) < (gtHi - unHi)) ? (hi - gtHi) : (gtHi - unHi);
vswap(unLo, hi - m + 1, m);
n = lo + unLo - ltLo - 1;
m = hi - (gtHi - unHi) + 1;
stack[sp].ll = lo;
stack[sp].hh = n;
stack[sp].dd = d;
sp++;
stack[sp].ll = n + 1;
stack[sp].hh = m - 1;
stack[sp].dd = d + 1;
sp++;
stack[sp].ll = m;
stack[sp].hh = hi;
stack[sp].dd = d;
sp++;
}
}
private void randomiseBlock()
{
int i;
int rNToGo = 0;
int rTPos = 0;
for (i = 0; i < 256; i++)
{
inUse[i] = false;
}
for (i = 0; i <= last; i++)
{
if (rNToGo == 0)
{
rNToGo = (char) RAND_NUMS[rTPos];
rTPos++;
if (rTPos == 512)
{
rTPos = 0;
}
}
rNToGo--;
block[i + 1] ^= ((rNToGo == 1) ? 1 : 0);
// handle 16 bit signed numbers
block[i + 1] &= 0xFF;
inUse[block[i + 1]] = true;
}
}
private void sendMTFValues()
throws IOException
{
char[][] len = new char[N_GROUPS][MAX_ALPHA_SIZE];
int v;
int t;
int i;
int j;
int gs;
int ge;
int bt;
int bc;
int iter;
int nSelectors = 0;
int alphaSize;
int minLen;
int maxLen;
int selCtr;
int nGroups;
alphaSize = nInUse + 2;
for (t = 0; t < N_GROUPS; t++)
{
for (v = 0; v < alphaSize; v++)
{
len[t][v] = (char) GREATER_ICOST;
}
}
/*
* Decide how many coding tables to use
*/
if (nMTF <= 0)
{
panic();
}
if (nMTF < 200)
{
nGroups = 2;
}
else if (nMTF < 600)
{
nGroups = 3;
}
else if (nMTF < 1200)
{
nGroups = 4;
}
else if (nMTF < 2400)
{
nGroups = 5;
}
else
{
nGroups = 6;
}
{
/*
* Generate an initial set of coding tables
*/
int nPart;
int remF;
int tFreq;
int aFreq;
nPart = nGroups;
remF = nMTF;
gs = 0;
while (nPart > 0)
{
tFreq = remF / nPart;
ge = gs - 1;
aFreq = 0;
while (aFreq < tFreq && ge < alphaSize - 1)
{
ge++;
aFreq += mtfFreq[ge];
}
if (ge > gs && nPart != nGroups && nPart != 1
&& ((nGroups - nPart) % 2 == 1))
{
aFreq -= mtfFreq[ge];
ge--;
}
for (v = 0; v < alphaSize; v++)
{
if (v >= gs && v <= ge)
{
len[nPart - 1][v] = (char) LESSER_ICOST;
}
else
{
len[nPart - 1][v] = (char) GREATER_ICOST;
}
}
nPart--;
gs = ge + 1;
remF -= aFreq;
}
}
int[][] rfreq = new int[N_GROUPS][MAX_ALPHA_SIZE];
int[] fave = new int[N_GROUPS];
short[] cost = new short[N_GROUPS];
/*
* Iterate up to N_ITERS times to improve the tables.
*/
for (iter = 0; iter < N_ITERS; iter++)
{
for (t = 0; t < nGroups; t++)
{
fave[t] = 0;
}
for (t = 0; t < nGroups; t++)
{
for (v = 0; v < alphaSize; v++)
{
rfreq[t][v] = 0;
}
}
nSelectors = 0;
gs = 0;
while (true)
{
/*
* Set group start & end marks.
*/
if (gs >= nMTF)
{
break;
}
ge = gs + G_SIZE - 1;
if (ge >= nMTF)
{
ge = nMTF - 1;
}
/*
* Calculate the cost of this group as coded
* by each of the coding tables.
*/
for (t = 0; t < nGroups; t++)
{
cost[t] = 0;
}
if (nGroups == 6)
{
short cost0 = 0;
short cost1 = 0;
short cost2 = 0;
short cost3 = 0;
short cost4 = 0;
short cost5 = 0;
for (i = gs; i <= ge; i++)
{
short icv = szptr[i];
cost0 += len[0][icv];
cost1 += len[1][icv];
cost2 += len[2][icv];
cost3 += len[3][icv];
cost4 += len[4][icv];
cost5 += len[5][icv];
}
cost[0] = cost0;
cost[1] = cost1;
cost[2] = cost2;
cost[3] = cost3;
cost[4] = cost4;
cost[5] = cost5;
}
else
{
for (i = gs; i <= ge; i++)
{
short icv = szptr[i];
for (t = 0; t < nGroups; t++)
{
cost[t] += len[t][icv];
}
}
}
/*
* Find the coding table which is best for this group,
* and record its identity in the selector table.
*/
bc = 999999999;
bt = -1;
for (t = 0; t < nGroups; t++)
{
if (cost[t] < bc)
{
bc = cost[t];
bt = t;
}
}
fave[bt]++;
selector[nSelectors] = (char) bt;
nSelectors++;
/*
* Increment the symbol frequencies for the selected table.
*/
for (i = gs; i <= ge; i++)
{
rfreq[bt][szptr[i]]++;
}
gs = ge + 1;
}
/*
* Recompute the tables based on the accumulated frequencies.
*/
for (t = 0; t < nGroups; t++)
{
hbMakeCodeLengths(len[t], rfreq[t], alphaSize, 20);
}
}
rfreq = null;
fave = null;
cost = null;
if (!(nGroups < 8))
{
panic();
}
if (!(nSelectors < 32768 && nSelectors <= (2 + (900000 / G_SIZE))))
{
panic();
}
{
/*
* Compute MTF values for the selectors.
*/
char[] pos = new char[N_GROUPS];
char ll_i;
char tmp2;
char tmp;
for (i = 0; i < nGroups; i++)
{
pos[i] = (char) i;
}
for (i = 0; i < nSelectors; i++)
{
ll_i = selector[i];
j = 0;
tmp = pos[j];
while (ll_i != tmp)
{
j++;
tmp2 = tmp;
tmp = pos[j];
pos[j] = tmp2;
}
pos[0] = tmp;
selectorMtf[i] = (char) j;
}
}
int[][] code = new int[N_GROUPS][MAX_ALPHA_SIZE];
/*
* Assign actual codes for the tables.
*/
for (t = 0; t < nGroups; t++)
{
minLen = 32;
maxLen = 0;
for (i = 0; i < alphaSize; i++)
{
if (len[t][i] > maxLen)
{
maxLen = len[t][i];
}
if (len[t][i] < minLen)
{
minLen = len[t][i];
}
}
if (maxLen > 20)
{
panic();
}
if (minLen < 1)
{
panic();
}
hbAssignCodes(code[t], len[t], minLen, maxLen, alphaSize);
}
{
/*
* Transmit the mapping table.
*/
boolean[] inUse16 = new boolean[16];
for (i = 0; i < 16; i++)
{
inUse16[i] = false;
for (j = 0; j < 16; j++)
{
if (inUse[i * 16 + j])
{
inUse16[i] = true;
}
}
}
for (i = 0; i < 16; i++)
{
if (inUse16[i])
{
bsW(1, 1);
}
else
{
bsW(1, 0);
}
}
for (i = 0; i < 16; i++)
{
if (inUse16[i])
{
for (j = 0; j < 16; j++)
{
if (inUse[i * 16 + j])
{
bsW(1, 1);
}
else
{
bsW(1, 0);
}
}
}
}
}
/*
* Now the selectors.
*/
bsW(3, nGroups);
bsW(15, nSelectors);
for (i = 0; i < nSelectors; i++)
{
for (j = 0; j < selectorMtf[i]; j++)
{
bsW(1, 1);
}
bsW(1, 0);
}
for (t = 0; t < nGroups; t++)
{
int curr = len[t][0];
bsW(5, curr);
for (i = 0; i < alphaSize; i++)
{
while (curr < len[t][i])
{
bsW(2, 2);
curr++;
/*
* 10
*/
}
while (curr > len[t][i])
{
bsW(2, 3);
curr--;
/*
* 11
*/
}
bsW(1, 0);
}
}
/*
* And finally, the block data proper
*/
selCtr = 0;
gs = 0;
while (true)
{
if (gs >= nMTF)
{
break;
}
ge = gs + G_SIZE - 1;
if (ge >= nMTF)
{
ge = nMTF - 1;
}
for (i = gs; i <= ge; i++)
{
bsW(len[selector[selCtr]][szptr[i]],
code[selector[selCtr]][szptr[i]]);
}
gs = ge + 1;
selCtr++;
}
if (!(selCtr == nSelectors))
{
panic();
}
}
private void simpleSort(int lo, int hi, int d)
{
int i;
int j;
int h;
int bigN;
int hp;
int v;
bigN = hi - lo + 1;
if (bigN < 2)
{
return;
}
hp = 0;
while (incs[hp] < bigN)
{
hp++;
}
hp--;
for (; hp >= 0; hp--)
{
h = incs[hp];
i = lo + h;
while (true)
{
/*
* copy 1
*/
if (i > hi)
{
break;
}
v = zptr[i];
j = i;
while (fullGtU(zptr[j - h] + d, v + d))
{
zptr[j] = zptr[j - h];
j = j - h;
if (j <= (lo + h - 1))
{
break;
}
}
zptr[j] = v;
i++;
/*
* copy 2
*/
if (i > hi)
{
break;
}
v = zptr[i];
j = i;
while (fullGtU(zptr[j - h] + d, v + d))
{
zptr[j] = zptr[j - h];
j = j - h;
if (j <= (lo + h - 1))
{
break;
}
}
zptr[j] = v;
i++;
/*
* copy 3
*/
if (i > hi)
{
break;
}
v = zptr[i];
j = i;
while (fullGtU(zptr[j - h] + d, v + d))
{
zptr[j] = zptr[j - h];
j = j - h;
if (j <= (lo + h - 1))
{
break;
}
}
zptr[j] = v;
i++;
if (workDone > workLimit && firstAttempt)
{
return;
}
}
}
}
private void vswap(int p1, int p2, int n)
{
int temp = 0;
while (n > 0)
{
temp = zptr[p1];
zptr[p1] = zptr[p2];
zptr[p2] = temp;
p1++;
p2++;
n--;
}
}
private void writeRun()
throws IOException
{
if (last < allowableBlockSize)
{
inUse[currentChar] = true;
for (int i = 0; i < runLength; i++)
{
crc.updateCRC((char) currentChar);
}
switch (runLength)
{
case 1:
last++;
block[last + 1] = (char) currentChar;
break;
case 2:
last++;
block[last + 1] = (char) currentChar;
last++;
block[last + 1] = (char) currentChar;
break;
case 3:
last++;
block[last + 1] = (char) currentChar;
last++;
block[last + 1] = (char) currentChar;
last++;
block[last + 1] = (char) currentChar;
break;
default:
inUse[runLength - 4] = true;
last++;
block[last + 1] = (char) currentChar;
last++;
block[last + 1] = (char) currentChar;
last++;
block[last + 1] = (char) currentChar;
last++;
block[last + 1] = (char) currentChar;
last++;
block[last + 1] = (char) (runLength - 4);
break;
}
}
else
{
endBlock();
initBlock();
writeRun();
}
}
/**
* A Stack element
*/
private static class StackElem
{
int dd;
int hh;
int ll;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/CRC.java 100644 765 24 12302 11623215064 27426 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.bzip2;
/*
* This package is based on the work done by Keiron Liddle, Aftex Software
* to whom the Ant project is very grateful for his
* great code.
*/
/**
* A simple class the hold and calculate the CRC for sanity checking of the
* data.
*
* @author Commons VFS team
*/
class CRC
{
private static final int[] CRC32_TABLE = new int[]
{
0x00000000, 0x04c11db7, 0x09823b6e, 0x0d4326d9,
0x130476dc, 0x17c56b6b, 0x1a864db2, 0x1e475005,
0x2608edb8, 0x22c9f00f, 0x2f8ad6d6, 0x2b4bcb61,
0x350c9b64, 0x31cd86d3, 0x3c8ea00a, 0x384fbdbd,
0x4c11db70, 0x48d0c6c7, 0x4593e01e, 0x4152fda9,
0x5f15adac, 0x5bd4b01b, 0x569796c2, 0x52568b75,
0x6a1936c8, 0x6ed82b7f, 0x639b0da6, 0x675a1011,
0x791d4014, 0x7ddc5da3, 0x709f7b7a, 0x745e66cd,
0x9823b6e0, 0x9ce2ab57, 0x91a18d8e, 0x95609039,
0x8b27c03c, 0x8fe6dd8b, 0x82a5fb52, 0x8664e6e5,
0xbe2b5b58, 0xbaea46ef, 0xb7a96036, 0xb3687d81,
0xad2f2d84, 0xa9ee3033, 0xa4ad16ea, 0xa06c0b5d,
0xd4326d90, 0xd0f37027, 0xddb056fe, 0xd9714b49,
0xc7361b4c, 0xc3f706fb, 0xceb42022, 0xca753d95,
0xf23a8028, 0xf6fb9d9f, 0xfbb8bb46, 0xff79a6f1,
0xe13ef6f4, 0xe5ffeb43, 0xe8bccd9a, 0xec7dd02d,
0x34867077, 0x30476dc0, 0x3d044b19, 0x39c556ae,
0x278206ab, 0x23431b1c, 0x2e003dc5, 0x2ac12072,
0x128e9dcf, 0x164f8078, 0x1b0ca6a1, 0x1fcdbb16,
0x018aeb13, 0x054bf6a4, 0x0808d07d, 0x0cc9cdca,
0x7897ab07, 0x7c56b6b0, 0x71159069, 0x75d48dde,
0x6b93dddb, 0x6f52c06c, 0x6211e6b5, 0x66d0fb02,
0x5e9f46bf, 0x5a5e5b08, 0x571d7dd1, 0x53dc6066,
0x4d9b3063, 0x495a2dd4, 0x44190b0d, 0x40d816ba,
0xaca5c697, 0xa864db20, 0xa527fdf9, 0xa1e6e04e,
0xbfa1b04b, 0xbb60adfc, 0xb6238b25, 0xb2e29692,
0x8aad2b2f, 0x8e6c3698, 0x832f1041, 0x87ee0df6,
0x99a95df3, 0x9d684044, 0x902b669d, 0x94ea7b2a,
0xe0b41de7, 0xe4750050, 0xe9362689, 0xedf73b3e,
0xf3b06b3b, 0xf771768c, 0xfa325055, 0xfef34de2,
0xc6bcf05f, 0xc27dede8, 0xcf3ecb31, 0xcbffd686,
0xd5b88683, 0xd1799b34, 0xdc3abded, 0xd8fba05a,
0x690ce0ee, 0x6dcdfd59, 0x608edb80, 0x644fc637,
0x7a089632, 0x7ec98b85, 0x738aad5c, 0x774bb0eb,
0x4f040d56, 0x4bc510e1, 0x46863638, 0x42472b8f,
0x5c007b8a, 0x58c1663d, 0x558240e4, 0x51435d53,
0x251d3b9e, 0x21dc2629, 0x2c9f00f0, 0x285e1d47,
0x36194d42, 0x32d850f5, 0x3f9b762c, 0x3b5a6b9b,
0x0315d626, 0x07d4cb91, 0x0a97ed48, 0x0e56f0ff,
0x1011a0fa, 0x14d0bd4d, 0x19939b94, 0x1d528623,
0xf12f560e, 0xf5ee4bb9, 0xf8ad6d60, 0xfc6c70d7,
0xe22b20d2, 0xe6ea3d65, 0xeba91bbc, 0xef68060b,
0xd727bbb6, 0xd3e6a601, 0xdea580d8, 0xda649d6f,
0xc423cd6a, 0xc0e2d0dd, 0xcda1f604, 0xc960ebb3,
0xbd3e8d7e, 0xb9ff90c9, 0xb4bcb610, 0xb07daba7,
0xae3afba2, 0xaafbe615, 0xa7b8c0cc, 0xa379dd7b,
0x9b3660c6, 0x9ff77d71, 0x92b45ba8, 0x9675461f,
0x8832161a, 0x8cf30bad, 0x81b02d74, 0x857130c3,
0x5d8a9099, 0x594b8d2e, 0x5408abf7, 0x50c9b640,
0x4e8ee645, 0x4a4ffbf2, 0x470cdd2b, 0x43cdc09c,
0x7b827d21, 0x7f436096, 0x7200464f, 0x76c15bf8,
0x68860bfd, 0x6c47164a, 0x61043093, 0x65c52d24,
0x119b4be9, 0x155a565e, 0x18197087, 0x1cd86d30,
0x029f3d35, 0x065e2082, 0x0b1d065b, 0x0fdc1bec,
0x3793a651, 0x3352bbe6, 0x3e119d3f, 0x3ad08088,
0x2497d08d, 0x2056cd3a, 0x2d15ebe3, 0x29d4f654,
0xc5a92679, 0xc1683bce, 0xcc2b1d17, 0xc8ea00a0,
0xd6ad50a5, 0xd26c4d12, 0xdf2f6bcb, 0xdbee767c,
0xe3a1cbc1, 0xe760d676, 0xea23f0af, 0xeee2ed18,
0xf0a5bd1d, 0xf464a0aa, 0xf9278673, 0xfde69bc4,
0x89b8fd09, 0x8d79e0be, 0x803ac667, 0x84fbdbd0,
0x9abc8bd5, 0x9e7d9662, 0x933eb0bb, 0x97ffad0c,
0xafb010b1, 0xab710d06, 0xa6322bdf, 0xa2f33668,
0xbcb4666d, 0xb8757bda, 0xb5365d03, 0xb1f740b4
};
private int globalCrc;
protected CRC()
{
initialiseCRC();
}
int getFinalCRC()
{
return ~globalCrc;
}
void initialiseCRC()
{
globalCrc = 0xffffffff;
}
void updateCRC(final int inCh)
{
int temp = (globalCrc >> 24) ^ inCh;
if (temp < 0)
{
temp = 256 + temp;
}
globalCrc = (globalCrc << 8) ^ CRC32_TABLE[temp];
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/bzip2/package.html 100644 765 24 1533 11623215064 30421 0 ustar rgoers staff 0 0
The BZIP2 File Provider
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/CompositeFileProvider.java 100644 765 24 4533 11623215065 32236 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* Description.
*
* @author Commons VFS team
*/
public abstract class CompositeFileProvider extends AbstractFileProvider
{
private static final int INITIAL_BUFSZ = 80;
public CompositeFileProvider()
{
super();
}
/**
* The schemes to use for resolve
*/
protected abstract String[] getSchemes();
/**
* Locates a file object, by absolute URI.
* @param baseFile The base FileObject.
* @param uri The file to find.
* @param fileSystemOptions The options for the FileSystem.
* @return A FileObject for the located file.
* @throws FileSystemException if an error occurs.
*/
public FileObject findFile(final FileObject baseFile,
final String uri,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
StringBuilder buf = new StringBuilder(INITIAL_BUFSZ);
UriParser.extractScheme(uri, buf);
String[] schemes = getSchemes();
for (int iterSchemes = 0; iterSchemes < schemes.length; iterSchemes++)
{
buf.insert(0, ":");
buf.insert(0, schemes[iterSchemes]);
}
FileObject fo = getContext().getFileSystemManager().resolveFile(buf.toString(), fileSystemOptions);
return fo;
}
}
././@LongLink 100644 0 0 155 11623215455 10260 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObject.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileObj100644 765 24 6703 11623215065 33345 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.compressed;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
/**
* A compressed file.
* Such a file do only have one child (the compressed filename with stripped last extension)
*
* @author Commons VFS team
*/
public abstract class CompressedFileFileObject extends AbstractFileObject implements FileObject
{
private final FileObject container;
private final String[] children;
protected CompressedFileFileObject(AbstractFileName name, FileObject container, CompressedFileFileSystem fs)
{
super(name, fs);
this.container = container;
// todo, add getBaseName(String) to FileName
String basename = container.getName().getBaseName();
int pos = basename.lastIndexOf('.');
basename = basename.substring(0, pos);
children = new String[]
{
basename
};
}
/**
* Determines if this file can be written to.
*
* @return true
if this file is writeable, false
if not.
* @throws FileSystemException if an error occurs.
*/
@Override
public boolean isWriteable() throws FileSystemException
{
return getFileSystem().hasCapability(Capability.WRITE_CONTENT);
}
/**
* Returns the file's type.
*/
@Override
protected FileType doGetType() throws FileSystemException
{
if (getName().getPath().endsWith("/"))
{
return FileType.FOLDER;
}
else
{
return FileType.FILE;
}
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren()
{
return children;
}
/**
* Returns the size of the file content (in bytes). Is only called if
* {@link #doGetType} returns {@link FileType#FILE}.
*/
@Override
protected long doGetContentSize()
{
return -1;
}
/**
* Returns the last modified time of this file.
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
return container.getContent().getLastModifiedTime();
}
protected FileObject getContainer()
{
return container;
}
@Override
public void createFile() throws FileSystemException
{
container.createFile();
injectType(FileType.FILE);
}
}
././@LongLink 100644 0 0 157 11623215455 10262 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileProvider.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFilePro100644 765 24 5706 11623215065 33375 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.compressed;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractLayeredFileProvider;
import org.apache.commons.vfs2.provider.FileProvider;
import org.apache.commons.vfs2.provider.LayeredFileName;
/**
* A file system provider for compressed files. Provides read-only file
* systems.
*
* @author Commons VFS team
*/
public abstract class CompressedFileFileProvider
extends AbstractLayeredFileProvider
implements FileProvider
{
public CompressedFileFileProvider()
{
super();
}
/**
* Parses an absolute URI.
*
* @param uri The URI to parse.
*/
/*
public FileName parseUri(final String uri)
throws FileSystemException
{
return ZipFileName.parseUri(uri);
}
*/
/**
* Creates a layered file system. This method is called if the file system
* is not cached.
*
* @param scheme The URI scheme.
* @param file The file to create the file system on top of.
* @return The file system.
*/
@Override
protected FileSystem doCreateFileSystem(final String scheme,
final FileObject file,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
final FileName name =
new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
return createFileSystem(name, file, fileSystemOptions);
}
protected abstract FileSystem createFileSystem(final FileName name, final FileObject file,
final FileSystemOptions fileSystemOptions)
throws FileSystemException;
public abstract Collection getCapabilities();
}
././@LongLink 100644 0 0 155 11623215455 10260 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileSystem.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/compressed/CompressedFileFileSys100644 765 24 4304 11623215065 33404 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.compressed;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
/**
* A read-only file system for compressed files.
*
* @author Commons VFS team
*/
public abstract class CompressedFileFileSystem
extends AbstractFileSystem
implements FileSystem
{
protected CompressedFileFileSystem(final FileName rootName,
final FileObject parentLayer,
final FileSystemOptions fileSystemOptions)
{
super(rootName, parentLayer, fileSystemOptions);
}
@Override
public void init() throws FileSystemException
{
super.init();
}
/**
* Returns the capabilities of this file system.
*/
@Override
protected abstract void addCapabilities(final Collection caps);
/**
* Creates a file object.
*/
@Override
protected abstract FileObject createFile(final AbstractFileName name) throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/compressed/package.html 100644 765 24 1540 11623215065 31536 0 ustar rgoers staff 0 0
The compressed file provider
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileContent.java 100644 765 24 51525 11623215065 31523 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.Certificate;
import java.util.Collections;
import java.util.Map;
import java.util.Set;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileContentInfo;
import org.apache.commons.vfs2.FileContentInfoFactory;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.util.MonitorInputStream;
import org.apache.commons.vfs2.util.MonitorOutputStream;
import org.apache.commons.vfs2.util.MonitorRandomAccessContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* The content of a file.
*
* @author Commons VFS team
*/
public final class DefaultFileContent implements FileContent
{
/*
static final int STATE_NONE = 0;
static final int STATE_READING = 1;
static final int STATE_WRITING = 2;
static final int STATE_RANDOM_ACCESS = 3;
*/
static final int STATE_CLOSED = 0;
static final int STATE_OPENED = 1;
private final AbstractFileObject fileObject;
private Map attrs;
private Map roAttrs;
private FileContentInfo fileContentInfo;
private final FileContentInfoFactory fileContentInfoFactory;
private final ThreadLocal threadData = new ThreadLocal();
private boolean resetAttributes;
/**
* open streams counter for this file
*/
private int openStreams;
public DefaultFileContent(final AbstractFileObject file, final FileContentInfoFactory fileContentInfoFactory)
{
this.fileObject = file;
this.fileContentInfoFactory = fileContentInfoFactory;
}
private FileContentThreadData getThreadData()
{
FileContentThreadData data = this.threadData.get();
if (data == null)
{
data = new FileContentThreadData();
this.threadData.set(data);
}
return data;
}
void streamOpened()
{
synchronized (this)
{
openStreams++;
}
((AbstractFileSystem) fileObject.getFileSystem()).streamOpened();
}
void streamClosed()
{
synchronized (this)
{
if (openStreams > 0)
{
openStreams--;
if (openStreams < 1)
{
fileObject.notifyAllStreamsClosed();
}
}
}
((AbstractFileSystem) fileObject.getFileSystem()).streamClosed();
}
/**
* Returns the file that this is the content of.
* @return the FileObject.
*/
public FileObject getFile()
{
return fileObject;
}
/**
* Returns the size of the content (in bytes).
* @return The size of the content (in bytes).
* @throws FileSystemException if an error occurs.
*/
public long getSize() throws FileSystemException
{
// Do some checking
if (!fileObject.getType().hasContent())
{
throw new FileSystemException("vfs.provider/get-size-not-file.error", fileObject);
}
/*
if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
{
throw new FileSystemException("vfs.provider/get-size-write.error", file);
}
*/
try
{
// Get the size
return fileObject.doGetContentSize();
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider/get-size.error", new Object[]{fileObject}, exc);
}
}
/**
* Returns the last-modified timestamp.
* @return The last modified timestamp.
* @throws FileSystemException if an error occurs.
*/
public long getLastModifiedTime() throws FileSystemException
{
/*
if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
{
throw new FileSystemException("vfs.provider/get-last-modified-writing.error", file);
}
*/
if (!fileObject.getType().hasAttributes())
{
throw new FileSystemException("vfs.provider/get-last-modified-no-exist.error", fileObject);
}
try
{
return fileObject.doGetLastModifiedTime();
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/get-last-modified.error", fileObject, e);
}
}
/**
* Sets the last-modified timestamp.
* @param modTime The last modified timestamp.
* @throws FileSystemException if an error occurs.
*/
public void setLastModifiedTime(final long modTime) throws FileSystemException
{
/*
if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
{
throw new FileSystemException("vfs.provider/set-last-modified-writing.error", file);
}
*/
if (!fileObject.getType().hasAttributes())
{
throw new FileSystemException("vfs.provider/set-last-modified-no-exist.error", fileObject);
}
try
{
if (!fileObject.doSetLastModifiedTime(modTime))
{
throw new FileSystemException("vfs.provider/set-last-modified.error", fileObject);
}
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/set-last-modified.error", fileObject, e);
}
}
/**
* Checks if an attribute exists.
* @param attrName The name of the attribute to check.
* @return true if the attribute is associated with the file.
* @throws FileSystemException if an error occurs.
* @since 2.0
*/
public boolean hasAttribute(final String attrName) throws FileSystemException
{
if (!fileObject.getType().hasAttributes())
{
throw new FileSystemException("vfs.provider/exists-attributes-no-exist.error", fileObject);
}
getAttributes();
return attrs.containsKey(attrName);
}
/**
* Returns a read-only map of this file's attributes.
* @return a Map of the file's attributes.
* @throws FileSystemException if an error occurs.
*/
public Map getAttributes() throws FileSystemException
{
if (!fileObject.getType().hasAttributes())
{
throw new FileSystemException("vfs.provider/get-attributes-no-exist.error", fileObject);
}
if (resetAttributes || roAttrs == null)
{
try
{
synchronized (this)
{
attrs = fileObject.doGetAttributes();
roAttrs = Collections.unmodifiableMap(attrs);
resetAttributes = false;
}
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/get-attributes.error", fileObject, e);
}
}
return roAttrs;
}
/**
* Used internally to flag situations where the file attributes should be
* reretrieved.
* @since 2.0
*/
public void resetAttributes()
{
resetAttributes = true;
}
/**
* Lists the attributes of this file.
* @return An array of attribute names.
* @throws FileSystemException if an error occurs.
*/
public String[] getAttributeNames() throws FileSystemException
{
getAttributes();
final Set names = attrs.keySet();
return names.toArray(new String[names.size()]);
}
/**
* Gets the value of an attribute.
* @param attrName The attribute name.
* @return The value of the attribute or null.
* @throws FileSystemException if an error occurs.
*/
public Object getAttribute(final String attrName)
throws FileSystemException
{
getAttributes();
return attrs.get(attrName);
}
/**
* Sets the value of an attribute.
* @param attrName The name of the attribute to add.
* @param value The value of the attribute.
* @throws FileSystemException if an error occurs.
*/
public void setAttribute(final String attrName, final Object value)
throws FileSystemException
{
if (!fileObject.getType().hasAttributes())
{
throw new FileSystemException("vfs.provider/set-attribute-no-exist.error", new Object[]{attrName, fileObject});
}
try
{
fileObject.doSetAttribute(attrName, value);
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/set-attribute.error", new Object[]{attrName, fileObject}, e);
}
if (attrs != null)
{
attrs.put(attrName, value);
}
}
/**
* Removes an attribute.
* @param attrName The name of the attribute to remove.
* @throws FileSystemException if an error occurs.
* @since 2.0
*/
public void removeAttribute(final String attrName) throws FileSystemException
{
if (!fileObject.getType().hasAttributes())
{
throw new FileSystemException("vfs.provider/remove-attribute-no-exist.error", fileObject);
}
try
{
fileObject.doRemoveAttribute(attrName);
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/remove-attribute.error", new Object[]{attrName, fileObject}, e);
}
if (attrs != null)
{
attrs.remove(attrName);
}
}
/**
* Returns the certificates used to sign this file.
* @return An array of Certificates.
* @throws FileSystemException if an error occurs.
*/
public Certificate[] getCertificates() throws FileSystemException
{
if (!fileObject.exists())
{
throw new FileSystemException("vfs.provider/get-certificates-no-exist.error", fileObject);
}
/*
if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
{
throw new FileSystemException("vfs.provider/get-certificates-writing.error", file);
}
*/
try
{
final Certificate[] certs = fileObject.doGetCertificates();
if (certs != null)
{
return certs;
}
else
{
return new Certificate[0];
}
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider/get-certificates.error", fileObject, e);
}
}
/**
* Returns an input stream for reading the content.
* @return The InputStream
* @throws FileSystemException if an error occurs.
*/
public InputStream getInputStream() throws FileSystemException
{
/*
if (getThreadData().getState() == STATE_WRITING || getThreadData().getState() == STATE_RANDOM_ACCESS)
{
throw new FileSystemException("vfs.provider/read-in-use.error", file);
}
*/
// Get the raw input stream
final InputStream instr = fileObject.getInputStream();
final InputStream wrappedInstr = new FileContentInputStream(fileObject, instr);
this.getThreadData().addInstr(wrappedInstr);
streamOpened();
// setState(STATE_OPENED);
return wrappedInstr;
}
/**
* Returns an input/output stream to use to read and write the content of the file in an
* random manner.
* @param mode The RandomAccessMode.
* @return A RandomAccessContent object to access the file.
* @throws FileSystemException if an error occurs.
*/
public RandomAccessContent getRandomAccessContent(final RandomAccessMode mode) throws FileSystemException
{
/*
if (getThreadData().getState() != STATE_NONE)
{
throw new FileSystemException("vfs.provider/read-in-use.error", file);
}
*/
// Get the content
final RandomAccessContent rastr = fileObject.getRandomAccessContent(mode);
FileRandomAccessContent rac = new FileRandomAccessContent(fileObject, rastr);
this.getThreadData().addRastr(rac);
streamOpened();
// setState(STATE_OPENED);
return rac;
}
/**
* Returns an output stream for writing the content.
* @return The OutputStream for the file.
* @throws FileSystemException if an error occurs.
*/
public OutputStream getOutputStream() throws FileSystemException
{
return getOutputStream(false);
}
/**
* Returns an output stream for writing the content in append mode.
* @param bAppend true if the data written should be appended.
* @return The OutputStream for the file.
* @throws FileSystemException if an error occurs.
*/
public OutputStream getOutputStream(boolean bAppend) throws FileSystemException
{
/*
if (getThreadData().getState() != STATE_NONE)
*/
if (this.getThreadData().getOutstr() != null)
{
throw new FileSystemException("vfs.provider/write-in-use.error", fileObject);
}
// Get the raw output stream
final OutputStream outstr = fileObject.getOutputStream(bAppend);
// Create wrapper
this.getThreadData().setOutstr(new FileContentOutputStream(fileObject, outstr));
streamOpened();
// setState(STATE_OPENED);
return this.getThreadData().getOutstr();
}
/**
* Closes all resources used by the content, including all streams, readers
* and writers.
* @throws FileSystemException if an error occurs.
*/
public void close() throws FileSystemException
{
try
{
// Close the input stream
while (getThreadData().getInstrsSize() > 0)
{
final FileContentInputStream instr = (FileContentInputStream) getThreadData().removeInstr(0);
instr.close();
}
// Close the randomAccess stream
while (getThreadData().getRastrsSize() > 0)
{
final RandomAccessContent ra = (RandomAccessContent) getThreadData().removeRastr(0);
try
{
ra.close();
}
catch (IOException e)
{
throw new FileSystemException(e);
}
}
// Close the output stream
if (this.getThreadData().getOutstr() != null)
{
this.getThreadData().closeOutstr();
}
}
finally
{
threadData.set(null);
}
}
/**
* Handles the end of input stream.
*/
private void endInput(final FileContentInputStream instr)
{
getThreadData().removeInstr(instr);
streamClosed();
/*
if (!getThreadData().hasStreams())
{
setState(STATE_CLOSED);
}
*/
}
/**
* Handles the end of random access.
*/
private void endRandomAccess(RandomAccessContent rac)
{
getThreadData().removeRastr(rac);
streamClosed();
// setState(STATE_CLOSED);
}
/**
* Handles the end of output stream.
*/
private void endOutput() throws Exception
{
streamClosed();
this.getThreadData().setOutstr(null);
// setState(STATE_CLOSED);
fileObject.endOutput();
}
/*
private void setState(int state)
{
getThreadData().setState(state);
}
*/
/**
* check if a input and/or output stream is open.
* This checks only the scope of the current thread.
*
* @return true if this is the case
*/
public boolean isOpen()
{
// return getThreadData().getState() == STATE_OPENED;
return getThreadData().hasStreams();
}
/**
* check if a input and/or output stream is open.
* This checks all threads.
*
* @return true if this is the case
*/
public boolean isOpenGlobal()
{
synchronized (this)
{
return openStreams > 0;
}
}
/**
* An input stream for reading content. Provides buffering, and
* end-of-stream monitoring.
*/
private final class FileContentInputStream extends MonitorInputStream
{
// avoid gc
private final FileObject file;
FileContentInputStream(final FileObject file, final InputStream instr)
{
super(instr);
this.file = file;
}
/**
* Closes this input stream.
*/
@Override
public void close() throws FileSystemException
{
try
{
super.close();
}
catch (final IOException e)
{
throw new FileSystemException("vfs.provider/close-instr.error", file, e);
}
}
/**
* Called after the stream has been closed.
*/
@Override
protected void onClose() throws IOException
{
try
{
super.onClose();
}
finally
{
endInput(this);
}
}
}
/**
* An input/output stream for reading/writing content on random positions
*/
private final class FileRandomAccessContent extends MonitorRandomAccessContent
{
// avoid gc
@SuppressWarnings("unused")
private final FileObject file;
@SuppressWarnings("unused")
private final RandomAccessContent content;
FileRandomAccessContent(final FileObject file, final RandomAccessContent content)
{
super(content);
this.file = file;
this.content = content;
}
/**
* Called after the stream has been closed.
*/
@Override
protected void onClose() throws IOException
{
try
{
super.onClose();
}
finally
{
endRandomAccess(this);
}
}
}
/**
* An output stream for writing content.
*/
final class FileContentOutputStream extends MonitorOutputStream
{
// avoid gc
private final FileObject file;
FileContentOutputStream(final FileObject file, final OutputStream outstr)
{
super(outstr);
this.file = file;
}
/**
* Closes this output stream.
*/
@Override
public void close() throws FileSystemException
{
try
{
super.close();
}
catch (final IOException e)
{
throw new FileSystemException("vfs.provider/close-outstr.error", file, e);
}
}
/**
* Called after this stream is closed.
*/
@Override
protected void onClose() throws IOException
{
try
{
super.onClose();
}
finally
{
try
{
endOutput();
}
catch (Exception e)
{
throw new FileSystemException("vfs.provider/close-outstr.error", file, e);
}
}
}
}
/**
* get the content info. e.g. content-type, content-encoding
* @return The FileContentInfo.
* @throws FileSystemException if an error occurs.
*/
public FileContentInfo getContentInfo() throws FileSystemException
{
if (fileContentInfo == null)
{
fileContentInfo = fileContentInfoFactory.create(this);
}
return fileContentInfo;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/DefaultFileSelectorInfo.java 100644 765 24 3300 11623215065 32451 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelectInfo;
/**
* A default {@link FileSelectInfo} implementation.
*
* @author Commons VFS team
*/
final class DefaultFileSelectorInfo
implements FileSelectInfo
{
private FileObject baseFolder;
private FileObject file;
private int depth;
public FileObject getBaseFolder()
{
return baseFolder;
}
public void setBaseFolder(final FileObject baseFolder)
{
this.baseFolder = baseFolder;
}
public FileObject getFile()
{
return file;
}
public void setFile(final FileObject file)
{
this.file = file;
}
public int getDepth()
{
return depth;
}
public void setDepth(final int depth)
{
this.depth = depth;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLConnection.java 100644 765 24 6603 11623215065 31750 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileSystemException;
/**
* A default URL connection that will work for most file systems.
*
* @author Commons VFS team
*/
public final class DefaultURLConnection
extends URLConnection
{
private final FileContent content;
public DefaultURLConnection(final URL url,
final FileContent content)
{
super(url);
this.content = content;
}
@Override
public void connect()
{
connected = true;
}
@Override
public InputStream getInputStream()
throws IOException
{
return content.getInputStream();
}
@Override
public OutputStream getOutputStream()
throws IOException
{
return content.getOutputStream();
}
@Override
public long getLastModified()
{
try
{
return content.getLastModifiedTime();
}
catch (FileSystemException fse)
{
// Ignore the exception
}
return -1;
}
@Override
public int getContentLength()
{
try
{
return (int) content.getSize();
}
catch (FileSystemException fse)
{
// Ignore the exception
}
return -1;
}
@Override
public String getContentType()
{
try
{
return content.getContentInfo().getContentType();
}
catch (FileSystemException e)
{
throw new RuntimeException(e.getMessage());
}
}
@Override
public String getContentEncoding()
{
try
{
return content.getContentInfo().getContentEncoding();
}
catch (FileSystemException e)
{
throw new RuntimeException(e.getMessage());
}
}
/*
public String getHeaderField(String name)
{
try
{
if (content.getFile().getFileSystem().hasCapability(Capability.ATTRIBUTES))
{
String value = (String) content.getAttribute(name);
if (value != null)
{
return value;
}
}
return null;
}
catch (FileSystemException e)
{
throw new RuntimeException(e);
}
}
*/
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/DefaultURLStreamHandler.java 100644 765 24 7032 11623215065 32377 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
/**
* A default URL stream handler that will work for most file systems.
*
* @author Commons VFS team
*/
public class DefaultURLStreamHandler
extends URLStreamHandler
{
private final VfsComponentContext context;
private final FileSystemOptions fileSystemOptions;
public DefaultURLStreamHandler(final VfsComponentContext context)
{
this(context, null);
}
public DefaultURLStreamHandler(final VfsComponentContext context, final FileSystemOptions fileSystemOptions)
{
this.context = context;
this.fileSystemOptions = fileSystemOptions;
}
@Override
protected URLConnection openConnection(final URL url)
throws IOException
{
final FileObject entry = context.resolveFile(url.toExternalForm(), fileSystemOptions);
return new DefaultURLConnection(url, entry.getContent());
}
@Override
protected void parseURL(final URL u,
final String spec,
final int start,
final int limit)
{
try
{
FileObject old = context.resolveFile(u.toExternalForm(), fileSystemOptions);
FileObject newURL;
if (start > 0 && spec.charAt(start - 1) == ':')
{
newURL = context.resolveFile(old, spec, fileSystemOptions);
}
else
{
if (old.getType() == FileType.FILE && old.getParent() != null)
{
// for files we have to resolve relative
newURL = old.getParent().resolveFile(spec);
}
else
{
newURL = old.resolveFile(spec);
}
}
final String url = newURL.getName().getURI();
final StringBuilder filePart = new StringBuilder();
final String protocolPart = UriParser.extractScheme(url, filePart);
setURL(u, protocolPart, "", -1, null, null, filePart.toString(), null, null);
}
catch (FileSystemException fse)
{
// This is rethrown to MalformedURLException in URL anyway
throw new RuntimeException(fse.getMessage());
}
}
@Override
protected String toExternalForm(final URL u)
{
return u.getProtocol() + ":" + u.getFile();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/DelegateFileObject.java 100644 765 24 26152 11623215065 31443 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.cert.Certificate;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import org.apache.commons.vfs2.FileChangeEvent;
import org.apache.commons.vfs2.FileContentInfo;
import org.apache.commons.vfs2.FileListener;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileNotFolderException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
import org.apache.commons.vfs2.util.WeakRefFileListener;
/**
* A file backed by another file.
*
* @author Commons VFS team
* @todo Extract subclass that overlays the children
*/
public class DelegateFileObject extends AbstractFileObject implements FileListener
{
private FileObject file;
private final Set children = new HashSet();
private boolean ignoreEvent;
public DelegateFileObject(final AbstractFileName name,
final AbstractFileSystem fileSystem,
final FileObject file) throws FileSystemException
{
super(name, fileSystem);
this.file = file;
if (file != null)
{
WeakRefFileListener.installListener(file, this);
}
}
/**
* Get access to the delegated file.
* @return The FileObject.
* @since 2.0
*/
public FileObject getDelegateFile()
{
return file;
}
/**
* Adds a child to this file.
* @param baseName The base FileName.
* @param type The FileType.
* @throws Exception if an error occurs.
*/
public void attachChild(final FileName baseName, final FileType type) throws Exception
{
final FileType oldType = doGetType();
if (children.add(baseName.getBaseName()))
{
childrenChanged(baseName, type);
}
maybeTypeChanged(oldType);
}
/**
* Attaches or detaches the target file.
* @param file The FileObject.
* @throws Exception if an error occurs.
*/
public void setFile(final FileObject file) throws Exception
{
final FileType oldType = doGetType();
if (file != null)
{
WeakRefFileListener.installListener(file, this);
}
this.file = file;
maybeTypeChanged(oldType);
}
/**
* Checks whether the file's type has changed, and fires the appropriate
* events.
* @param oldType The old FileType.
* @throws Exception if an error occurs.
*/
private void maybeTypeChanged(final FileType oldType) throws Exception
{
final FileType newType = doGetType();
if (oldType == FileType.IMAGINARY && newType != FileType.IMAGINARY)
{
handleCreate(newType);
}
else if (oldType != FileType.IMAGINARY && newType == FileType.IMAGINARY)
{
handleDelete();
}
}
/**
* Determines the type of the file, returns null if the file does not
* exist.
*/
@Override
protected FileType doGetType() throws FileSystemException
{
if (file != null)
{
return file.getType();
}
else if (children.size() > 0)
{
return FileType.FOLDER;
}
else
{
return FileType.IMAGINARY;
}
}
/**
* Determines if this file can be read.
*/
@Override
protected boolean doIsReadable() throws FileSystemException
{
if (file != null)
{
return file.isReadable();
}
else
{
return true;
}
}
/**
* Determines if this file can be written to.
*/
@Override
protected boolean doIsWriteable() throws FileSystemException
{
if (file != null)
{
return file.isWriteable();
}
else
{
return false;
}
}
/**
* Determines if this file is hidden.
*/
@Override
protected boolean doIsHidden() throws FileSystemException
{
if (file != null)
{
return file.isHidden();
}
else
{
return false;
}
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren() throws Exception
{
if (file != null)
{
final FileObject[] children;
try
{
children = file.getChildren();
}
// VFS-210
catch (FileNotFolderException e)
{
throw new FileNotFolderException(getName(), e);
}
final String[] childNames = new String[children.length];
for (int i = 0; i < children.length; i++)
{
childNames[i] = children[i].getName().getBaseName();
}
return childNames;
}
else
{
return children.toArray(new String[children.size()]);
}
}
/**
* Creates this file as a folder.
*/
@Override
protected void doCreateFolder() throws Exception
{
ignoreEvent = true;
try
{
file.createFolder();
}
finally
{
ignoreEvent = false;
}
}
/**
* Deletes the file.
*/
@Override
protected void doDelete() throws Exception
{
ignoreEvent = true;
try
{
file.delete();
}
finally
{
ignoreEvent = false;
}
}
/**
* Returns the size of the file content (in bytes). Is only called if
* {@link #doGetType} returns {@link FileType#FILE}.
*/
@Override
protected long doGetContentSize() throws Exception
{
return file.getContent().getSize();
}
/**
* Returns the attributes of this file.
*/
@Override
protected Map doGetAttributes()
throws Exception
{
return file.getContent().getAttributes();
}
/**
* Sets an attribute of this file.
*/
@Override
protected void doSetAttribute(final String atttrName,
final Object value)
throws Exception
{
file.getContent().setAttribute(atttrName, value);
}
/**
* Returns the certificates of this file.
*/
@Override
protected Certificate[] doGetCertificates() throws Exception
{
return file.getContent().getCertificates();
}
/**
* Returns the last-modified time of this file.
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
return file.getContent().getLastModifiedTime();
}
/**
* Sets the last-modified time of this file.
* @since 2.0
*/
@Override
protected boolean doSetLastModifiedTime(final long modtime)
throws Exception
{
file.getContent().setLastModifiedTime(modtime);
return true;
}
/**
* Creates an input stream to read the file content from.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
return file.getContent().getInputStream();
}
/**
* Creates an output stream to write the file content to.
*/
@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
return file.getContent().getOutputStream(bAppend);
}
/**
* Called when a file is created.
* @param event The FileChangeEvent.
* @throws Exception if an error occurs.
*/
public void fileCreated(final FileChangeEvent event) throws Exception
{
if (event.getFile() != file)
{
return;
}
if (!ignoreEvent)
{
handleCreate(file.getType());
}
}
/**
* Called when a file is deleted.
* @param event The FileChangeEvent.
* @throws Exception if an error occurs.
*/
public void fileDeleted(final FileChangeEvent event) throws Exception
{
if (event.getFile() != file)
{
return;
}
if (!ignoreEvent)
{
handleDelete();
}
}
/**
* Called when a file is changed.
*
* This will only happen if you monitor the file using {@link org.apache.commons.vfs2.FileMonitor}.
* @param event The FileChangeEvent.
* @throws Exception if an error occurs.
*/
public void fileChanged(FileChangeEvent event) throws Exception
{
if (event.getFile() != file)
{
return;
}
if (!ignoreEvent)
{
handleChanged();
}
}
/**
* Close the delegated file.
* @throws FileSystemException if an error occurs.
*/
@Override
public void close() throws FileSystemException
{
super.close();
if (file != null)
{
file.close();
}
}
/**
* Refresh file information.
* @throws FileSystemException if an error occurs.
* @since 2.0
*/
@Override
public void refresh() throws FileSystemException
{
super.refresh();
if (file != null)
{
file.refresh();
}
}
/** @since 2.0 */
protected FileContentInfo doGetContentInfo() throws Exception
{
return file.getContent().getContentInfo();
}
/**
* Renames the file.
* @since 2.0
*/
@Override
protected void doRename(FileObject newFile)
throws Exception
{
file.moveTo(((DelegateFileObject) newFile).file);
}
/**
* Removes an attribute of this file.
* @since 2.0
*/
@Override
protected void doRemoveAttribute(final String atttrName)
throws Exception
{
file.getContent().removeAttribute(atttrName);
}
/**
* Creates access to the file for random i/o.
* @since 2.0
*/
@Override
protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
{
return file.getContent().getRandomAccessContent(mode);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/FileContentThreadData.java 100644 765 24 5355 11623215065 32120 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.InputStream;
import java.util.ArrayList;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.RandomAccessContent;
/**
* Holds the data which needs to be local to the current thread
* @author Commons VFS team
*/
class FileContentThreadData
{
// private int state = DefaultFileContent.STATE_CLOSED;
private final ArrayList instrs = new ArrayList();
private final ArrayList rastrs = new ArrayList();
private DefaultFileContent.FileContentOutputStream outstr;
FileContentThreadData()
{
}
/*
int getState()
{
return state;
}
void setState(int state)
{
this.state = state;
}
*/
void addInstr(InputStream is)
{
this.instrs.add(is);
}
void setOutstr(DefaultFileContent.FileContentOutputStream os)
{
this.outstr = os;
}
DefaultFileContent.FileContentOutputStream getOutstr()
{
return this.outstr;
}
void addRastr(RandomAccessContent ras)
{
this.rastrs.add(ras);
}
int getInstrsSize()
{
return this.instrs.size();
}
public Object removeInstr(int pos)
{
return this.instrs.remove(pos);
}
public void removeInstr(InputStream instr)
{
this.instrs.remove(instr);
}
public Object removeRastr(int pos)
{
return this.rastrs.remove(pos);
}
public void removeRastr(RandomAccessContent ras)
{
this.rastrs.remove(ras);
}
public boolean hasStreams()
{
return instrs.size() > 0 || outstr != null || rastrs.size() > 0;
}
public void closeOutstr() throws FileSystemException
{
outstr.close();
outstr = null;
}
int getRastrsSize()
{
return rastrs.size();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/FileNameParser.java 100644 765 24 3411 11623215065 30610 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
/**
* Provides methods to parse a filename into a {@link org.apache.commons.vfs2.FileName}.
* @author Commons VFS team
*/
public interface FileNameParser
{
/**
* Check if a character needs encoding (%nn).
* @param ch the character
* @return true if character should be encoded
*/
boolean encodeCharacter(char ch);
/**
* parses a String into a filename.
* @param context The component context.
* @param base The base FileName.
* @param filename The target file name.
* @return A FileName that represents the taret file.
* @throws FileSystemException if an error occurs parsing the URI.
*/
FileName parseUri(final VfsComponentContext context, final FileName base, final String filename)
throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/FileProvider.java 100644 765 24 6471 11623215065 30356 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* A file provider. Each file provider is responsible for handling files for
* a particular URI scheme.
*
* A file provider may also implement {@link VfsComponent}.
*
* @author Commons VFS team
*/
public interface FileProvider
{
/**
* Locates a file object, by absolute URI.
*
* @param baseFile The base file to use for resolving the individual parts of
* a compound URI.
* @param uri The absolute URI of the file to find.
* @param fileSystemOptions The FileSystemOptions
* @return The FileObject.
* @throws FileSystemException if an error occurs locating the file.
*/
FileObject findFile(final FileObject baseFile, final String uri, final FileSystemOptions fileSystemOptions)
throws FileSystemException;
/**
* Creates a layered file system.
*
* @param scheme The URI scheme for the layered file system.
* @param file The file to build the file system on.
* @param fileSystemOptions The FileSystemOptions.
* @return A FileObject in the file system.
* @throws FileSystemException if an error occurs.
*/
FileObject createFileSystem(String scheme, FileObject file, FileSystemOptions fileSystemOptions)
throws FileSystemException;
/**
* Gets the configbuilder useable to collect the needed fileSystemOptions.
* @return a FileSystemConfigBuilder for the particular file system.
*/
FileSystemConfigBuilder getConfigBuilder();
/**
* Get the filesystem capabilities.
* These are the same as on the filesystem, but available before the first filesystem was
* instanciated.
* @return a Collection of the file systems Capabilities.
*/
Collection getCapabilities();
/**
* Parse the URI into a FileName.
* @param root The base FileName.
* @param uri The file to be accessed.
* @return A FileName representing the target file.
* @throws FileSystemException if an error occurs.
*/
FileName parseUri(FileName root, String uri) throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/FileReplicator.java 100644 765 24 3233 11623215065 30661 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.File;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystemException;
/**
* Responsible for making local replicas of files.
*
* A file replicator may also implement {@link VfsComponent}.
*
* @author Commons VFS team
*/
public interface FileReplicator
{
/**
* Creates a local copy of the file, and all its descendents.
*
* @param srcFile The file to copy.
* @param selector Selects the files to copy.
* @return The local copy of the source file.
* @throws FileSystemException If the source files does not exist, or on error copying.
*/
File replicateFile(FileObject srcFile, FileSelector selector)
throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/FileSystemKey.java 100644 765 24 4250 11623215065 30512 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* Used to identify a filesystem
*
* @author Commons VFS team
*/
class FileSystemKey implements Comparable
{
private static final FileSystemOptions EMPTY_OPTIONS = new FileSystemOptions();
private final Comparable> key;
private final FileSystemOptions fileSystemOptions;
/**
* Create the FS key.
*
* @param key must implement Comparable, and must be self-comparable
* @param fileSystemOptions the required options
*/
FileSystemKey(final Comparable> key, final FileSystemOptions fileSystemOptions)
{
this.key = key;
if (fileSystemOptions != null)
{
this.fileSystemOptions = fileSystemOptions;
}
else
{
this.fileSystemOptions = EMPTY_OPTIONS;
}
}
public int compareTo(FileSystemKey o)
{
@SuppressWarnings("unchecked") // Keys must implement comparable, and be comparable to themselves
Comparable> comparable = (Comparable>) key;
int ret = comparable.compareTo(o.key);
if (ret != 0)
{
// other filesystem
return ret;
}
return fileSystemOptions.compareTo(o.fileSystemOptions);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClient.java 100644 765 24 4040 11623215064 30432 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.vfs2.FileSystemException;
/**
* What VFS expects from an ftp client to provide.
* @author Commons VFS team
*/
public interface FtpClient
{
boolean isConnected() throws FileSystemException;
void disconnect() throws IOException;
FTPFile[] listFiles(String relPath) throws IOException;
boolean removeDirectory(String relPath) throws IOException;
boolean deleteFile(String relPath) throws IOException;
boolean rename(String oldName, String newName) throws IOException;
boolean makeDirectory(String relPath) throws IOException;
boolean completePendingCommand() throws IOException;
InputStream retrieveFileStream(String relPath) throws IOException;
InputStream retrieveFileStream(String relPath, long restartOffset) throws IOException;
OutputStream appendFileStream(String relPath) throws IOException;
OutputStream storeFileStream(String relPath) throws IOException;
boolean abort() throws IOException;
String getReplyString() throws IOException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpClientFactory.java 100644 765 24 20130 11623215064 32000 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* Create a FtpClient instance.
*
* @author Commons VFS team
*/
public final class FtpClientFactory
{
private static final int BUFSZ = 40;
private FtpClientFactory()
{
}
/**
* Creates a new connection to the server.
*
* @param hostname The host name of the server.
* @param port The port to connect to.
* @param username The name of the user for authentication.
* @param password The user's password.
* @param workingDirectory The base directory.
* @param fileSystemOptions The FileSystemOptions.
* @return An FTPClient.
* @throws FileSystemException if an error occurs while connecting.
*/
public static FTPClient createConnection(String hostname, int port, char[] username, char[] password,
String workingDirectory, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Determine the username and password to use
if (username == null)
{
username = "anonymous".toCharArray();
}
if (password == null)
{
password = "anonymous".toCharArray();
}
try
{
final FTPClient client = new FTPClient();
configureClient(fileSystemOptions, client);
FTPFileEntryParserFactory myFactory =
FtpFileSystemConfigBuilder.getInstance().getEntryParserFactory(fileSystemOptions);
if (myFactory != null)
{
client.setParserFactory(myFactory);
}
try
{
client.connect(hostname, port);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname);
}
// Login
if (!client.login(
UserAuthenticatorUtils.toString(username),
UserAuthenticatorUtils.toString(password)))
{
throw new FileSystemException("vfs.provider.ftp/login.error",
new Object[]{hostname, UserAuthenticatorUtils.toString(username)}, null);
}
// Set binary mode
if (!client.setFileType(FTP.BINARY_FILE_TYPE))
{
throw new FileSystemException("vfs.provider.ftp/set-binary.error", hostname);
}
// Set dataTimeout value
Integer dataTimeout = FtpFileSystemConfigBuilder.getInstance().getDataTimeout(fileSystemOptions);
if (dataTimeout != null)
{
client.setDataTimeout(dataTimeout.intValue());
}
Integer socketTimeout = FtpFileSystemConfigBuilder.getInstance().getSoTimeout(fileSystemOptions);
if (socketTimeout != null)
{
client.setSoTimeout(socketTimeout.intValue());
}
// Change to root by default
// All file operations a relative to the filesystem-root
// String root = getRoot().getName().getPath();
Boolean userDirIsRoot = FtpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(fileSystemOptions);
if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
{
if (!client.changeWorkingDirectory(workingDirectory))
{
throw new FileSystemException("vfs.provider.ftp/change-work-directory.error", workingDirectory);
}
}
Boolean passiveMode = FtpFileSystemConfigBuilder.getInstance().getPassiveMode(fileSystemOptions);
if (passiveMode != null && passiveMode.booleanValue())
{
client.enterLocalPassiveMode();
}
String controlEncoding = FtpFileSystemConfigBuilder.getInstance().getControlEncoding(fileSystemOptions);
if (controlEncoding != null)
{
client.setControlEncoding(controlEncoding);
}
}
catch (final IOException e)
{
if (client.isConnected())
{
client.disconnect();
}
throw e;
}
return client;
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider.ftp/connect.error", new Object[]{hostname}, exc);
}
}
private static void configureClient(FileSystemOptions fileSystemOptions, FTPClient client)
{
String key = FtpFileSystemConfigBuilder.getInstance().getEntryParser(fileSystemOptions);
if (key != null)
{
FTPClientConfig config = new FTPClientConfig(key);
String serverLanguageCode =
FtpFileSystemConfigBuilder.getInstance().getServerLanguageCode(fileSystemOptions);
if (serverLanguageCode != null)
{
config.setServerLanguageCode(serverLanguageCode);
}
String defaultDateFormat =
FtpFileSystemConfigBuilder.getInstance().getDefaultDateFormat(fileSystemOptions);
if (defaultDateFormat != null)
{
config.setDefaultDateFormatStr(defaultDateFormat);
}
String recentDateFormat =
FtpFileSystemConfigBuilder.getInstance().getRecentDateFormat(fileSystemOptions);
if (recentDateFormat != null)
{
config.setRecentDateFormatStr(recentDateFormat);
}
String serverTimeZoneId =
FtpFileSystemConfigBuilder.getInstance().getServerTimeZoneId(fileSystemOptions);
if (serverTimeZoneId != null)
{
config.setServerTimeZoneId(serverTimeZoneId);
}
String[] shortMonthNames =
FtpFileSystemConfigBuilder.getInstance().getShortMonthNames(fileSystemOptions);
if (shortMonthNames != null)
{
StringBuilder shortMonthNamesStr = new StringBuilder(BUFSZ);
for (int i = 0; i < shortMonthNames.length; i++)
{
if (shortMonthNamesStr.length() > 0)
{
shortMonthNamesStr.append("|");
}
shortMonthNamesStr.append(shortMonthNames[i]);
}
config.setShortMonthNames(shortMonthNamesStr.toString());
}
client.configure(config);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FTPClientWrapper.java 100644 765 24 21324 11623215064 31717 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* A wrapper to the FTPClient to allow automatic reconnect on connection loss.
* I decided to not to use eg. noop() to determine the state of the connection to avoid
* unnecesary server round-trips.
* @author Commons VFS team
*/
class FTPClientWrapper implements FtpClient
{
private final GenericFileName root;
private final FileSystemOptions fileSystemOptions;
private FTPClient ftpClient;
FTPClientWrapper(final GenericFileName root, final FileSystemOptions fileSystemOptions) throws FileSystemException
{
this.root = root;
this.fileSystemOptions = fileSystemOptions;
getFtpClient(); // fail-fast
}
public GenericFileName getRoot()
{
return root;
}
public FileSystemOptions getFileSystemOptions()
{
return fileSystemOptions;
}
private FTPClient createClient() throws FileSystemException
{
final GenericFileName rootName = getRoot();
UserAuthenticationData authData = null;
try
{
authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpFileProvider.AUTHENTICATOR_TYPES);
return FtpClientFactory.createConnection(rootName.getHostName(),
rootName.getPort(),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
UserAuthenticatorUtils.toChar(rootName.getUserName())),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
UserAuthenticatorUtils.toChar(rootName.getPassword())),
rootName.getPath(),
getFileSystemOptions());
}
finally
{
UserAuthenticatorUtils.cleanup(authData);
}
}
private FTPClient getFtpClient() throws FileSystemException
{
if (ftpClient == null)
{
ftpClient = createClient();
}
return ftpClient;
}
public boolean isConnected() throws FileSystemException
{
return ftpClient != null && ftpClient.isConnected();
}
public void disconnect() throws IOException
{
try
{
getFtpClient().disconnect();
}
finally
{
ftpClient = null;
}
}
public FTPFile[] listFiles(String relPath) throws IOException
{
try
{
// VFS-210: return getFtpClient().listFiles(relPath);
FTPFile[] files = listFilesInDirectory(relPath);
return files;
}
catch (IOException e)
{
disconnect();
FTPFile[] files = listFilesInDirectory(relPath);
return files;
}
}
private FTPFile[] listFilesInDirectory(String relPath) throws IOException
{
FTPFile[] files;
// VFS-307: no check if we can simply list the files, this might fail if there are spaces in the path
files = getFtpClient().listFiles(relPath);
if (FTPReply.isPositiveCompletion(getFtpClient().getReplyCode()))
{
return files;
}
// VFS-307: now try the hard way by cd'ing into the directory, list and cd back
// if VFS is required to fallback here the user might experience a real bad FTP performance
// as then every list requires 4 ftp commands.
String workingDirectory = null;
if (relPath != null)
{
workingDirectory = getFtpClient().printWorkingDirectory();
if (!getFtpClient().changeWorkingDirectory(relPath))
{
return null;
}
}
files = getFtpClient().listFiles();
if (relPath != null && !getFtpClient().changeWorkingDirectory(workingDirectory))
{
throw new FileSystemException("vfs.provider.ftp.wrapper/change-work-directory-back.error",
workingDirectory);
}
return files;
}
public boolean removeDirectory(String relPath) throws IOException
{
try
{
return getFtpClient().removeDirectory(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpClient().removeDirectory(relPath);
}
}
public boolean deleteFile(String relPath) throws IOException
{
try
{
return getFtpClient().deleteFile(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpClient().deleteFile(relPath);
}
}
public boolean rename(String oldName, String newName) throws IOException
{
try
{
return getFtpClient().rename(oldName, newName);
}
catch (IOException e)
{
disconnect();
return getFtpClient().rename(oldName, newName);
}
}
public boolean makeDirectory(String relPath) throws IOException
{
try
{
return getFtpClient().makeDirectory(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpClient().makeDirectory(relPath);
}
}
public boolean completePendingCommand() throws IOException
{
if (ftpClient != null)
{
return getFtpClient().completePendingCommand();
}
return true;
}
public InputStream retrieveFileStream(String relPath) throws IOException
{
try
{
return getFtpClient().retrieveFileStream(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpClient().retrieveFileStream(relPath);
}
}
public InputStream retrieveFileStream(String relPath, long restartOffset) throws IOException
{
try
{
FTPClient client = getFtpClient();
client.setRestartOffset(restartOffset);
return client.retrieveFileStream(relPath);
}
catch (IOException e)
{
disconnect();
FTPClient client = getFtpClient();
client.setRestartOffset(restartOffset);
return client.retrieveFileStream(relPath);
}
}
public OutputStream appendFileStream(String relPath) throws IOException
{
try
{
return getFtpClient().appendFileStream(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpClient().appendFileStream(relPath);
}
}
public OutputStream storeFileStream(String relPath) throws IOException
{
try
{
return getFtpClient().storeFileStream(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpClient().storeFileStream(relPath);
}
}
public boolean abort() throws IOException
{
try
{
// imario@apache.org: 2005-02-14
// it should be better to really "abort" the transfer, but
// currently I didnt manage to make it work - so lets "abort" the hard way.
// return getFtpClient().abort();
disconnect();
return true;
}
catch (IOException e)
{
disconnect();
}
return true;
}
public String getReplyString() throws IOException
{
return getFtpClient().getReplyString();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileNameParser.java 100644 765 24 2644 11623215064 32061 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.HostFileNameParser;
/**
* Implementation for ftp. set default port to 21
* @author Commons VFS team
*/
public class FtpFileNameParser extends HostFileNameParser
{
private static final FtpFileNameParser INSTANCE = new FtpFileNameParser();
private static final int PORT = 21;
public FtpFileNameParser()
{
super(PORT);
}
public static FileNameParser getInstance()
{
return INSTANCE;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileObject.java 100644 765 24 51667 11623215064 31263 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Calendar;
import java.util.Collections;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileNotFolderException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.util.FileObjectUtils;
import org.apache.commons.vfs2.util.Messages;
import org.apache.commons.vfs2.util.MonitorInputStream;
import org.apache.commons.vfs2.util.MonitorOutputStream;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* An FTP file.
*
* @author Commons VFS team
*/
public class FtpFileObject extends AbstractFileObject
{
private static final Map EMPTY_FTP_FILE_MAP =
Collections.unmodifiableMap(new TreeMap());
private static final FTPFile UNKNOWN = new FTPFile();
private final Log log = LogFactory.getLog(FtpFileObject.class);
private final FtpFileSystem ftpFs;
private final String relPath;
// Cached info
private FTPFile fileInfo;
private Map children;
private FileObject linkDestination;
private boolean inRefresh;
protected FtpFileObject(final AbstractFileName name,
final FtpFileSystem fileSystem,
final FileName rootName)
throws FileSystemException
{
super(name, fileSystem);
ftpFs = fileSystem;
String relPath = UriParser.decode(rootName.getRelativeName(name));
if (".".equals(relPath))
{
// do not use the "." as path against the ftp-server
// e.g. the uu.net ftp-server do a recursive listing then
// this.relPath = UriParser.decode(rootName.getPath());
// this.relPath = ".";
this.relPath = null;
}
else
{
this.relPath = relPath;
}
}
/**
* Called by child file objects, to locate their ftp file info.
*
* @param name the filename in its native form ie. without uri stuff (%nn)
* @param flush recreate children cache
*/
private FTPFile getChildFile(final String name, final boolean flush) throws IOException
{
/* If we should flush cached children, clear our children map unless
* we're in the middle of a refresh in which case we've just recently
* refreshed our children. No need to do it again when our children are
* refresh()ed, calling getChildFile() for themselves from within
* getInfo(). See getChildren(). */
if (flush && !inRefresh)
{
children = null;
}
// List the children of this file
doGetChildren();
// VFS-210
if (children == null)
{
return null;
}
// Look for the requested child
FTPFile ftpFile = children.get(name);
return ftpFile;
}
/**
* Fetches the children of this file, if not already cached.
*/
private void doGetChildren() throws IOException
{
if (children != null)
{
return;
}
final FtpClient client = ftpFs.getClient();
try
{
final String path = fileInfo != null && fileInfo.isSymbolicLink()
? getFileSystem().getFileSystemManager().
resolveName(getParent().getName(), fileInfo.getLink()).getPath()
: relPath;
final FTPFile[] tmpChildren = client.listFiles(path);
if (tmpChildren == null || tmpChildren.length == 0)
{
children = EMPTY_FTP_FILE_MAP;
}
else
{
children = new TreeMap();
// Remove '.' and '..' elements
for (int i = 0; i < tmpChildren.length; i++)
{
final FTPFile child = tmpChildren[i];
if (child == null)
{
if (log.isDebugEnabled())
{
log.debug(Messages.getString("vfs.provider.ftp/invalid-directory-entry.debug",
new Object[]
{
new Integer(i), relPath
}));
}
continue;
}
if (!".".equals(child.getName())
&& !"..".equals(child.getName()))
{
children.put(child.getName(), child);
}
}
}
}
finally
{
ftpFs.putClient(client);
}
}
/**
* Attaches this file object to its file resource.
*/
@Override
protected void doAttach()
throws IOException
{
// Get the parent folder to find the info for this file
// VFS-210 getInfo(false);
}
/**
* Fetches the info for this file.
*/
private void getInfo(boolean flush) throws IOException
{
final FtpFileObject parent = (FtpFileObject) FileObjectUtils.getAbstractFileObject(getParent());
FTPFile newFileInfo;
if (parent != null)
{
newFileInfo = parent.getChildFile(UriParser.decode(getName().getBaseName()), flush);
}
else
{
// Assume the root is a directory and exists
newFileInfo = new FTPFile();
newFileInfo.setType(FTPFile.DIRECTORY_TYPE);
}
if (newFileInfo == null)
{
this.fileInfo = UNKNOWN;
}
else
{
this.fileInfo = newFileInfo;
}
}
/**
* @throws FileSystemException if an error occurs.
*/
@Override
public void refresh() throws FileSystemException
{
if (!inRefresh)
{
try
{
inRefresh = true;
super.refresh();
synchronized (getFileSystem())
{
this.fileInfo = null;
}
/* VFS-210
try
{
// this will tell the parent to recreate its children collection
getInfo(true);
}
catch (IOException e)
{
throw new FileSystemException(e);
}
*/
}
finally
{
inRefresh = false;
}
}
}
/**
* Detaches this file object from its file resource.
*/
@Override
protected void doDetach()
{
synchronized (getFileSystem())
{
this.fileInfo = null;
children = null;
}
}
/**
* Called when the children of this file change.
*/
@Override
protected void onChildrenChanged(FileName child, FileType newType)
{
if (children != null && newType.equals(FileType.IMAGINARY))
{
try
{
children.remove(UriParser.decode(child.getBaseName()));
}
catch (FileSystemException e)
{
throw new RuntimeException(e.getMessage());
}
}
else
{
// if child was added we have to rescan the children
// TODO - get rid of this
children = null;
}
}
/**
* Called when the type or content of this file changes.
*/
@Override
protected void onChange() throws IOException
{
children = null;
if (getType().equals(FileType.IMAGINARY))
{
// file is deleted, avoid server lookup
synchronized (getFileSystem())
{
this.fileInfo = UNKNOWN;
}
return;
}
getInfo(true);
}
/**
* Determines the type of the file, returns null if the file does not
* exist.
*/
@Override
protected FileType doGetType()
throws Exception
{
// VFS-210
synchronized (getFileSystem())
{
if (this.fileInfo == null)
{
getInfo(false);
}
if (this.fileInfo == UNKNOWN)
{
return FileType.IMAGINARY;
}
else if (this.fileInfo.isDirectory())
{
return FileType.FOLDER;
}
else if (this.fileInfo.isFile())
{
return FileType.FILE;
}
else if (this.fileInfo.isSymbolicLink())
{
return getLinkDestination().getType();
}
}
throw new FileSystemException("vfs.provider.ftp/get-type.error", getName());
}
private FileObject getLinkDestination() throws FileSystemException
{
if (linkDestination == null)
{
final String path;
synchronized (getFileSystem())
{
path = this.fileInfo.getLink();
}
FileName relativeTo = getName().getParent();
if (relativeTo == null)
{
relativeTo = getName();
}
FileName linkDestinationName = getFileSystem().getFileSystemManager().resolveName(relativeTo, path);
linkDestination = getFileSystem().resolveFile(linkDestinationName);
}
return linkDestination;
}
@Override
protected FileObject[] doListChildrenResolved() throws Exception
{
synchronized (getFileSystem())
{
if (this.fileInfo != null && this.fileInfo.isSymbolicLink())
{
return getLinkDestination().getChildren();
}
}
return null;
}
/**
* Returns the file's list of children.
*
* @return The list of children
* @throws FileSystemException If there was a problem listing children
* @see AbstractFileObject#getChildren()
* @since 2.0
*/
@Override
public FileObject[] getChildren() throws FileSystemException
{
try
{
if (doGetType() != FileType.FOLDER)
{
throw new FileNotFolderException(getName());
}
}
catch (Exception ex)
{
throw new FileNotFolderException(getName(), ex);
}
try
{
/* Wrap our parent implementation, noting that we're refreshing so
* that we don't refresh() ourselves and each of our parents for
* each children. Note that refresh() will list children. Meaning,
* if if this file has C children, P parents, there will be (C * P)
* listings made with (C * (P + 1)) refreshes, when there should
* really only be 1 listing and C refreshes. */
this.inRefresh = true;
return super.getChildren();
}
finally
{
this.inRefresh = false;
}
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren()
throws Exception
{
// List the children of this file
doGetChildren();
// VFS-210
if (children == null)
{
return null;
}
// TODO - get rid of this children stuff
final String[] childNames = new String[children.size()];
int childNum = -1;
Iterator iterChildren = children.values().iterator();
while (iterChildren.hasNext())
{
childNum++;
final FTPFile child = iterChildren.next();
childNames[childNum] = child.getName();
}
return UriParser.encode(childNames);
}
/**
* Deletes the file.
*/
@Override
protected void doDelete() throws Exception
{
synchronized (getFileSystem())
{
final boolean ok;
final FtpClient ftpClient = ftpFs.getClient();
try
{
if (this.fileInfo.isDirectory())
{
ok = ftpClient.removeDirectory(relPath);
}
else
{
ok = ftpClient.deleteFile(relPath);
}
}
finally
{
ftpFs.putClient(ftpClient);
}
if (!ok)
{
throw new FileSystemException("vfs.provider.ftp/delete-file.error", getName());
}
this.fileInfo = null;
children = EMPTY_FTP_FILE_MAP;
}
}
/**
* Renames the file
*/
@Override
protected void doRename(FileObject newfile) throws Exception
{
synchronized (getFileSystem())
{
final boolean ok;
final FtpClient ftpClient = ftpFs.getClient();
try
{
String oldName = getName().getPath();
String newName = newfile.getName().getPath();
ok = ftpClient.rename(oldName, newName);
}
finally
{
ftpFs.putClient(ftpClient);
}
if (!ok)
{
throw new FileSystemException("vfs.provider.ftp/rename-file.error",
new Object[]{getName().toString(), newfile});
}
this.fileInfo = null;
children = EMPTY_FTP_FILE_MAP;
}
}
/**
* Creates this file as a folder.
*/
@Override
protected void doCreateFolder()
throws Exception
{
final boolean ok;
final FtpClient client = ftpFs.getClient();
try
{
ok = client.makeDirectory(relPath);
}
finally
{
ftpFs.putClient(client);
}
if (!ok)
{
throw new FileSystemException("vfs.provider.ftp/create-folder.error", getName());
}
}
/**
* Returns the size of the file content (in bytes).
*/
@Override
protected long doGetContentSize() throws Exception
{
synchronized (getFileSystem())
{
if (this.fileInfo.isSymbolicLink())
{
return getLinkDestination().getContent().getSize();
}
else
{
return this.fileInfo.getSize();
}
}
}
/**
* get the last modified time on an ftp file
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetLastModifiedTime()
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
synchronized (getFileSystem())
{
if (this.fileInfo.isSymbolicLink())
{
return getLinkDestination().getContent().getLastModifiedTime();
}
else
{
Calendar timestamp = this.fileInfo.getTimestamp();
if (timestamp == null)
{
return 0L;
}
else
{
return (timestamp.getTime().getTime());
}
}
}
}
/**
* Creates an input stream to read the file content from.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
final FtpClient client = ftpFs.getClient();
try
{
final InputStream instr = client.retrieveFileStream(relPath);
// VFS-210
if (instr == null)
{
throw new FileNotFoundException(getName().toString());
}
return new FtpInputStream(client, instr);
}
catch (Exception e)
{
ftpFs.putClient(client);
throw e;
}
}
@Override
protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
{
return new FtpRandomAccessContent(this, mode);
}
/**
* Creates an output stream to write the file content to.
*/
@Override
protected OutputStream doGetOutputStream(boolean bAppend)
throws Exception
{
final FtpClient client = ftpFs.getClient();
try
{
OutputStream out = null;
if (bAppend)
{
out = client.appendFileStream(relPath);
}
else
{
out = client.storeFileStream(relPath);
}
if (out == null)
{
throw new FileSystemException("vfs.provider.ftp/output-error.debug", new Object[]
{
this.getName(),
client.getReplyString()
});
}
return new FtpOutputStream(client, out);
}
catch (Exception e)
{
ftpFs.putClient(client);
throw e;
}
}
String getRelPath()
{
return relPath;
}
FtpInputStream getInputStream(long filePointer) throws IOException
{
final FtpClient client = ftpFs.getClient();
try
{
final InputStream instr = client.retrieveFileStream(relPath, filePointer);
if (instr == null)
{
throw new FileSystemException("vfs.provider.ftp/input-error.debug", new Object[]
{
this.getName(),
client.getReplyString()
});
}
return new FtpInputStream(client, instr);
}
catch (IOException e)
{
ftpFs.putClient(client);
throw e;
}
}
/**
* An InputStream that monitors for end-of-file.
*/
class FtpInputStream
extends MonitorInputStream
{
private final FtpClient client;
public FtpInputStream(final FtpClient client, final InputStream in)
{
super(in);
this.client = client;
}
void abort() throws IOException
{
client.abort();
close();
}
/**
* Called after the stream has been closed.
*/
@Override
protected void onClose() throws IOException
{
final boolean ok;
try
{
ok = client.completePendingCommand();
}
finally
{
ftpFs.putClient(client);
}
if (!ok)
{
throw new FileSystemException("vfs.provider.ftp/finish-get.error", getName());
}
}
}
/**
* An OutputStream that monitors for end-of-file.
*/
private class FtpOutputStream
extends MonitorOutputStream
{
private final FtpClient client;
public FtpOutputStream(final FtpClient client, final OutputStream outstr)
{
super(outstr);
this.client = client;
}
/**
* Called after this stream is closed.
*/
@Override
protected void onClose() throws IOException
{
final boolean ok;
try
{
ok = client.completePendingCommand();
}
finally
{
ftpFs.putClient(client);
}
if (!ok)
{
throw new FileSystemException("vfs.provider.ftp/finish-put.error", getName());
}
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileProvider.java 100644 765 24 6760 11623215064 31621 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.GenericFileName;
/**
* A provider for FTP file systems.
*
* @author Commons VFS team
*/
public class FtpFileProvider
extends AbstractOriginatingFileProvider
{
/**
* File Entry Parser.
*/
public static final String ATTR_FILE_ENTRY_PARSER = "FEP";
/**
* Authenticator types.
*/
public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD
};
static final Collection capabilities = Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.CREATE,
Capability.DELETE,
Capability.RENAME,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.GET_LAST_MODIFIED,
Capability.URI,
Capability.WRITE_CONTENT,
Capability.APPEND_CONTENT,
Capability.RANDOM_ACCESS_READ,
}));
public FtpFileProvider()
{
super();
setFileNameParser(FtpFileNameParser.getInstance());
}
/**
* Creates the filesystem.
*/
@Override
protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Create the file system
final GenericFileName rootName = (GenericFileName) name;
FTPClientWrapper ftpClient = new FTPClientWrapper(rootName, fileSystemOptions);
/*
FTPClient ftpClient = FtpClientFactory.createConnection(rootName.getHostName(),
rootName.getPort(),
rootName.getUserName(),
rootName.getPassword(),
rootName.getPath(),
fileSystemOptions);
*/
return new FtpFileSystem(rootName, ftpClient, fileSystemOptions);
}
@Override
public FileSystemConfigBuilder getConfigBuilder()
{
return FtpFileSystemConfigBuilder.getInstance();
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystem.java 100644 765 24 10761 11623215064 31327 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.io.IOException;
import java.util.Collection;
import java.util.concurrent.atomic.AtomicReference;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.VfsLog;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
import org.apache.commons.vfs2.provider.GenericFileName;
/**
* An FTP file system.
*
* @author Commons VFS team
*/
public class FtpFileSystem extends AbstractFileSystem
{
private static final Log LOG = LogFactory.getLog(FtpFileSystem.class);
// private final String hostname;
// private final int port;
// private final String username;
// private final String password;
// An idle client
private final AtomicReference idleClient = new AtomicReference();
/**
* @param rootName The root of the file system.
* @param ftpClient The FtpClient.
* @param fileSystemOptions The FileSystemOptions.
* @since 2.0 (was protected)
* */
public FtpFileSystem(final GenericFileName rootName, final FtpClient ftpClient,
final FileSystemOptions fileSystemOptions)
{
super(rootName, null, fileSystemOptions);
// hostname = rootName.getHostName();
// port = rootName.getPort();
idleClient.set(ftpClient);
}
@Override
protected void doCloseCommunicationLink()
{
FtpClient idle = idleClient.getAndSet(null);
// Clean up the connection
if (idle != null)
{
closeConnection(idle);
}
}
/**
* Adds the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(FtpFileProvider.capabilities);
}
/**
* Cleans up the connection to the server.
* @param client The FtpClient.
*/
private void closeConnection(final FtpClient client)
{
try
{
// Clean up
if (client.isConnected())
{
client.disconnect();
}
}
catch (final IOException e)
{
// getLogger().warn("vfs.provider.ftp/close-connection.error", e);
VfsLog.warn(getLogger(), LOG, "vfs.provider.ftp/close-connection.error", e);
}
}
/**
* Creates an FTP client to use.
* @return An FTPCleint.
* @throws FileSystemException if an error occurs.
*/
public FtpClient getClient() throws FileSystemException
{
FtpClient client = idleClient.getAndSet(null);
if (client == null || !client.isConnected())
{
client = new FTPClientWrapper((GenericFileName) getRoot().getName(), getFileSystemOptions());
}
return client;
}
/**
* Returns an FTP client after use.
* @param client The FTPClient.
*/
public void putClient(final FtpClient client)
{
// Save client for reuse if none is idle.
if (!idleClient.compareAndSet(null, client))
{
// An idle client is already present so close the connection.
closeConnection(client);
}
}
/**
* Creates a file object.
*/
@Override
protected FileObject createFile(final AbstractFileName name)
throws FileSystemException
{
return new FtpFileObject(name, this, getRootName());
}
}
././@LongLink 100644 0 0 150 11623215455 10253 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpFileSystemConfigBuilder.j100644 765 24 26421 11623215064 33274 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* The config BUILDER for various ftp configuration options.
*
* @author Commons VFS team
*/
public final class FtpFileSystemConfigBuilder extends FileSystemConfigBuilder
{
private static final FtpFileSystemConfigBuilder BUILDER = new FtpFileSystemConfigBuilder();
private static final String FACTORY_KEY = FTPFileEntryParserFactory.class.getName() + ".KEY";
private static final String PASSIVE_MODE = FtpFileSystemConfigBuilder.class.getName() + ".PASSIVE";
private static final String USER_DIR_IS_ROOT = FtpFileSystemConfigBuilder.class.getName() + ".USER_DIR_IS_ROOT";
private static final String DATA_TIMEOUT = FtpFileSystemConfigBuilder.class.getName() + ".DATA_TIMEOUT";
private static final String SO_TIMEOUT = FtpFileSystemConfigBuilder.class.getName() + ".SO_TIMEOUT";
private static final String SERVER_LANGUAGE_CODE =
FtpFileSystemConfigBuilder.class.getName() + ".SERVER_LANGUAGE_CODE";
private static final String DEFAULT_DATE_FORMAT =
FtpFileSystemConfigBuilder.class.getName() + ".DEFAULT_DATE_FORMAT";
private static final String RECENT_DATE_FORMAT =
FtpFileSystemConfigBuilder.class.getName() + ".RECENT_DATE_FORMAT";
private static final String SERVER_TIME_ZONE_ID =
FtpFileSystemConfigBuilder.class.getName() + ".SERVER_TIME_ZONE_ID";
private static final String SHORT_MONTH_NAMES =
FtpFileSystemConfigBuilder.class.getName() + ".SHORT_MONTH_NAMES";
private static final String ENCODING =
FtpFileSystemConfigBuilder.class.getName() + ".ENCODING";
private FtpFileSystemConfigBuilder()
{
super("ftp.");
}
public static FtpFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
/**
* FTPFileEntryParserFactory which will be used for ftp-entry parsing.
*
* @param opts The FileSystemOptions.
* @param factory instance of your factory
*/
public void setEntryParserFactory(FileSystemOptions opts, FTPFileEntryParserFactory factory)
{
setParam(opts, FTPFileEntryParserFactory.class.getName(), factory);
}
/**
* @param opts The FlleSystemOptions.
* @see #setEntryParserFactory
* @return An FTPFileEntryParserFactory.
*/
public FTPFileEntryParserFactory getEntryParserFactory(FileSystemOptions opts)
{
return (FTPFileEntryParserFactory) getParam(opts, FTPFileEntryParserFactory.class.getName());
}
/**
* set the FQCN of your FileEntryParser used to parse the directory listing from your server.
*
* If you do not use the default commons-net FTPFileEntryParserFactory e.g. by using
* {@link #setEntryParserFactory}
* this is the "key" parameter passed as argument into your custom factory
*
* @param opts The FileSystemOptions.
* @param key The key.
*/
public void setEntryParser(FileSystemOptions opts, String key)
{
setParam(opts, FACTORY_KEY, key);
}
/**
* @param opts The FileSystemOptions.
* @see #setEntryParser
* @return the key to the EntryParser.
*/
public String getEntryParser(FileSystemOptions opts)
{
return getString(opts, FACTORY_KEY);
}
@Override
protected Class extends FileSystem> getConfigClass()
{
return FtpFileSystem.class;
}
/**
* enter into passive mode.
*
* @param opts The FileSystemOptions.
* @param passiveMode true if passive mode should be used.
*/
public void setPassiveMode(FileSystemOptions opts, boolean passiveMode)
{
setParam(opts, PASSIVE_MODE, passiveMode ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @param opts The FileSystemOptions.
* @return true if passive mode is set.
* @see #setPassiveMode
*/
public Boolean getPassiveMode(FileSystemOptions opts)
{
return getBoolean(opts, PASSIVE_MODE);
}
/**
* use user directory as root (do not change to fs root).
*
* @param opts The FileSystemOptions.
* @param userDirIsRoot true if the user directory should be treated as the root.
*/
public void setUserDirIsRoot(FileSystemOptions opts, boolean userDirIsRoot)
{
setParam(opts, USER_DIR_IS_ROOT, userDirIsRoot ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @param opts The FileSystemOptions.
* @return true if the user directory is treated as the root.
* @see #setUserDirIsRoot
*/
public Boolean getUserDirIsRoot(FileSystemOptions opts)
{
return getBoolean(opts, USER_DIR_IS_ROOT);
}
/**
* @param opts The FileSystemOptions.
* @return The timeout as an Integer.
* @see #setDataTimeout
*/
public Integer getDataTimeout(FileSystemOptions opts)
{
return getInteger(opts, DATA_TIMEOUT);
}
/**
* set the data timeout for the ftp client.
* If you set the dataTimeout to null
no dataTimeout will be set on the
* ftp client.
*
* @param opts The FileSystemOptions.
* @param dataTimeout The timeout value.
*/
public void setDataTimeout(FileSystemOptions opts, Integer dataTimeout)
{
setParam(opts, DATA_TIMEOUT, dataTimeout);
}
/**
* @param opts The FileSystem options.
* @return The timeout value.
* @see #getDataTimeout
* @since 2.0
*/
public Integer getSoTimeout(FileSystemOptions opts)
{
return (Integer) getParam(opts, SO_TIMEOUT);
}
/**
* set the socket timeout for the ftp client.
* If you set the socketTimeout to null
no socketTimeout will be set on the
* ftp client.
*
* @param opts The FileSystem options.
* @param soTimeout The timeout value.
* @since 2.0
*/
public void setSoTimeout(FileSystemOptions opts, Integer soTimeout)
{
setParam(opts, SO_TIMEOUT, soTimeout);
}
/**
* get the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FilesystemOptions.
* @return The language code of the server.
*/
public String getServerLanguageCode(FileSystemOptions opts)
{
return getString(opts, SERVER_LANGUAGE_CODE);
}
/**
* set the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FileSystemOptions.
* @param serverLanguageCode The servers language code.
*/
public void setServerLanguageCode(FileSystemOptions opts, String serverLanguageCode)
{
setParam(opts, SERVER_LANGUAGE_CODE, serverLanguageCode);
}
/**
* get the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FileSystemOptions
* @return The default date format.
*/
public String getDefaultDateFormat(FileSystemOptions opts)
{
return getString(opts, DEFAULT_DATE_FORMAT);
}
/**
* set the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FileSystemOptions.
* @param defaultDateFormat The default date format.
*/
public void setDefaultDateFormat(FileSystemOptions opts, String defaultDateFormat)
{
setParam(opts, DEFAULT_DATE_FORMAT, defaultDateFormat);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @return The recent date format.
*/
public String getRecentDateFormat(FileSystemOptions opts)
{
return getString(opts, RECENT_DATE_FORMAT);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @param recentDateFormat The recent date format.
*/
public void setRecentDateFormat(FileSystemOptions opts, String recentDateFormat)
{
setParam(opts, RECENT_DATE_FORMAT, recentDateFormat);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @return The server timezone id.
*/
public String getServerTimeZoneId(FileSystemOptions opts)
{
return getString(opts, SERVER_TIME_ZONE_ID);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @param serverTimeZoneId The server timezone id.
*/
public void setServerTimeZoneId(FileSystemOptions opts, String serverTimeZoneId)
{
setParam(opts, SERVER_TIME_ZONE_ID, serverTimeZoneId);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @return An array of short month names.
*/
public String[] getShortMonthNames(FileSystemOptions opts)
{
return (String[]) getParam(opts, SHORT_MONTH_NAMES);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @param shortMonthNames an array of short month name Strings.
*/
public void setShortMonthNames(FileSystemOptions opts, String[] shortMonthNames)
{
String[] clone = null;
if (shortMonthNames != null)
{
clone = new String[shortMonthNames.length];
System.arraycopy(shortMonthNames, 0, clone, 0, shortMonthNames.length);
}
setParam(opts, SHORT_MONTH_NAMES, clone);
}
/**
* see {@link org.apache.commons.net.ftp.FTP#setControlEncoding} for details and examples.
* @param opts The FileSystemOptions.
* @param encoding the encoding to use
* @since 2.0
*/
public void setControlEncoding(FileSystemOptions opts, String encoding)
{
setParam(opts, ENCODING, encoding);
}
/**
* @param opts The FileSystemOptions.
* @return The encoding.
* @since 2.0
* */
public String getControlEncoding(FileSystemOptions opts)
{
return (String) getParam(opts, ENCODING);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/FtpRandomAccessContent.java 100644 765 24 7737 11623215064 33131 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftp;
import java.io.DataInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractRandomAccessStreamContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* @author Commons VFS team
*/
class FtpRandomAccessContent extends AbstractRandomAccessStreamContent
{
protected long filePointer;
private final FtpFileObject fileObject;
private DataInputStream dis;
private FtpFileObject.FtpInputStream mis;
FtpRandomAccessContent(final FtpFileObject fileObject, RandomAccessMode mode)
{
super(mode);
this.fileObject = fileObject;
// fileSystem = (FtpFileSystem) this.fileObject.getFileSystem();
}
public long getFilePointer() throws IOException
{
return filePointer;
}
public void seek(long pos) throws IOException
{
if (pos == filePointer)
{
// no change
return;
}
if (pos < 0)
{
throw new FileSystemException("vfs.provider/random-access-invalid-position.error",
new Object[]
{
new Long(pos)
});
}
if (dis != null)
{
close();
}
filePointer = pos;
}
@Override
protected DataInputStream getDataInputStream() throws IOException
{
if (dis != null)
{
return dis;
}
// FtpClient client = fileSystem.getClient();
mis = fileObject.getInputStream(filePointer);
dis = new DataInputStream(new FilterInputStream(mis)
{
@Override
public int read() throws IOException
{
int ret = super.read();
if (ret > -1)
{
filePointer++;
}
return ret;
}
@Override
public int read(byte[] b) throws IOException
{
int ret = super.read(b);
if (ret > -1)
{
filePointer += ret;
}
return ret;
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
int ret = super.read(b, off, len);
if (ret > -1)
{
filePointer += ret;
}
return ret;
}
@Override
public void close() throws IOException
{
FtpRandomAccessContent.this.close();
}
});
return dis;
}
public void close() throws IOException
{
if (dis != null)
{
mis.abort();
// this is to avoid recursive close
DataInputStream oldDis = dis;
dis = null;
oldDis.close();
mis = null;
}
}
public long length() throws IOException
{
return fileObject.getContent().getSize();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftp/package.html 100644 765 24 1540 11623215064 30162 0 ustar rgoers staff 0 0
The FTP File Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientFactory.java 100644 765 24 21145 11623215065 32356 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftps;
import java.io.IOException;
import org.apache.commons.net.ftp.FTP;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* Create a FtpClient instance.
*
* @author Commons VFS team
* @since 2.0
*/
public final class FtpsClientFactory
{
private FtpsClientFactory()
{
}
/**
* Creates a new connection to the server.
* @param hostname The host name.
* @param port The port.
* @param username The user name for authentication.
* @param password The user's password.
* @param workingDirectory The directory to use.
* @param fileSystemOptions The FileSystemOptions.
* @return The FTPSClient.
* @throws FileSystemException if an error occurs.
*/
public static FTPSClient createConnection(String hostname, int port, char[] username, char[] password,
String workingDirectory, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Determine the username and password to use
if (username == null)
{
username = "anonymous".toCharArray();
}
if (password == null)
{
password = "anonymous".toCharArray();
}
try
{
final FTPSClient client;
if (FtpsFileSystemConfigBuilder.getInstance().getFtpsType(fileSystemOptions).equals("explicit"))
{
client = new FTPSClient();
}
else if (FtpsFileSystemConfigBuilder.getInstance().getFtpsType(fileSystemOptions).equals("implicit"))
{
client = new FTPSClient(true);
}
else
{
throw new FileSystemException(
"Invalid FTPS type of " + FtpsFileSystemConfigBuilder.getInstance().getFtpsType(
fileSystemOptions) + " specified. Must be 'implicit' or 'explicit'");
}
String key = FtpsFileSystemConfigBuilder.getInstance().getEntryParser(fileSystemOptions);
if (key != null)
{
FTPClientConfig config = new FTPClientConfig(key);
String serverLanguageCode = FtpsFileSystemConfigBuilder.getInstance().getServerLanguageCode(
fileSystemOptions);
if (serverLanguageCode != null)
{
config.setServerLanguageCode(serverLanguageCode);
}
String defaultDateFormat = FtpsFileSystemConfigBuilder.getInstance().getDefaultDateFormat(
fileSystemOptions);
if (defaultDateFormat != null)
{
config.setDefaultDateFormatStr(defaultDateFormat);
}
String recentDateFormat = FtpsFileSystemConfigBuilder.getInstance().getRecentDateFormat(
fileSystemOptions);
if (recentDateFormat != null)
{
config.setRecentDateFormatStr(recentDateFormat);
}
String serverTimeZoneId = FtpsFileSystemConfigBuilder.getInstance().getServerTimeZoneId(
fileSystemOptions);
if (serverTimeZoneId != null)
{
config.setServerTimeZoneId(serverTimeZoneId);
}
String[] shortMonthNames = FtpsFileSystemConfigBuilder.getInstance().getShortMonthNames(
fileSystemOptions);
if (shortMonthNames != null)
{
StringBuilder shortMonthNamesStr = new StringBuilder(40);
for (int i = 0; i < shortMonthNames.length; i++)
{
if (shortMonthNamesStr.length() > 0)
{
shortMonthNamesStr.append("|");
}
shortMonthNamesStr.append(shortMonthNames[i]);
}
config.setShortMonthNames(shortMonthNamesStr.toString());
}
client.configure(config);
}
FTPFileEntryParserFactory myFactory = FtpsFileSystemConfigBuilder.getInstance().getEntryParserFactory(
fileSystemOptions);
if (myFactory != null)
{
client.setParserFactory(myFactory);
}
try
{
client.connect(hostname, port);
int reply = client.getReplyCode();
if (!FTPReply.isPositiveCompletion(reply))
{
throw new FileSystemException("vfs.provider.ftp/connect-rejected.error", hostname);
}
// Login
if (!client.login(
UserAuthenticatorUtils.toString(username),
UserAuthenticatorUtils.toString(password)))
{
throw new FileSystemException("vfs.provider.ftp/login.error",
new Object[]{hostname, UserAuthenticatorUtils.toString(username)}, null);
}
// Set binary mode
if (!client.setFileType(FTP.BINARY_FILE_TYPE))
{
throw new FileSystemException("vfs.provider.ftp/set-binary.error", hostname);
}
// Set dataTimeout value
Integer dataTimeout = FtpsFileSystemConfigBuilder.getInstance().getDataTimeout(fileSystemOptions);
if (dataTimeout != null)
{
client.setDataTimeout(dataTimeout.intValue());
}
// Change to root by default
// All file operations a relative to the filesystem-root
// String root = getRoot().getName().getPath();
Boolean userDirIsRoot = FtpsFileSystemConfigBuilder.getInstance().getUserDirIsRoot(
fileSystemOptions);
if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
{
if (!client.changeWorkingDirectory(workingDirectory))
{
throw new FileSystemException("vfs.provider.ftp/change-work-directory.error",
workingDirectory);
}
}
Boolean passiveMode = FtpsFileSystemConfigBuilder.getInstance().getPassiveMode(fileSystemOptions);
if (passiveMode != null && passiveMode.booleanValue())
{
client.enterLocalPassiveMode();
}
}
catch (final IOException e)
{
if (client.isConnected())
{
client.disconnect();
}
throw e;
}
return client;
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider.ftp/connect.error", new Object[]{hostname}, exc);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsClientWrapper.java 100644 765 24 16725 11623215065 32377 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftps;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.net.ftp.FTPFile;
import org.apache.commons.net.ftp.FTPSClient;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.provider.ftp.FtpClient;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* A wrapper to the FTPClient to allow automatic reconnect on connection loss.
* I decided to not to use eg. noop() to determine the state of the connection to avoid unnecesary server round-trips.
* @author Commons VFS team
* @since 2.0
*/
class FtpsClientWrapper implements FtpClient
{
private final GenericFileName root;
private final FileSystemOptions fileSystemOptions;
private FTPSClient ftpClient = null;
FtpsClientWrapper(final GenericFileName root, final FileSystemOptions fileSystemOptions) throws FileSystemException
{
this.root = root;
this.fileSystemOptions = fileSystemOptions;
getFtpsClient(); // fail-fast
}
public GenericFileName getRoot()
{
return root;
}
public FileSystemOptions getFileSystemOptions()
{
return fileSystemOptions;
}
private FTPSClient createClient() throws FileSystemException
{
final GenericFileName rootName = getRoot();
UserAuthenticationData authData = null;
try
{
authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, FtpsFileProvider.AUTHENTICATOR_TYPES);
return FtpsClientFactory.createConnection(rootName.getHostName(),
rootName.getPort(),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
UserAuthenticatorUtils.toChar(rootName.getUserName())),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
UserAuthenticatorUtils.toChar(rootName.getPassword())),
rootName.getPath(),
getFileSystemOptions());
}
finally
{
UserAuthenticatorUtils.cleanup(authData);
}
}
private FTPSClient getFtpsClient() throws FileSystemException
{
if (ftpClient == null)
{
ftpClient = createClient();
}
return ftpClient;
}
public boolean isConnected() throws FileSystemException
{
return getFtpsClient().isConnected();
}
public void disconnect() throws IOException
{
try
{
getFtpsClient().disconnect();
}
finally
{
ftpClient = null;
}
}
public FTPFile[] listFiles(String relPath) throws IOException
{
try
{
return getFtpsClient().listFiles(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().listFiles(relPath);
}
}
public boolean removeDirectory(String relPath) throws IOException
{
try
{
return getFtpsClient().removeDirectory(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().removeDirectory(relPath);
}
}
public boolean deleteFile(String relPath) throws IOException
{
try
{
return getFtpsClient().deleteFile(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().deleteFile(relPath);
}
}
public boolean rename(String oldName, String newName) throws IOException
{
try
{
return getFtpsClient().rename(oldName, newName);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().rename(oldName, newName);
}
}
public boolean makeDirectory(String relPath) throws IOException
{
try
{
return getFtpsClient().makeDirectory(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().makeDirectory(relPath);
}
}
public boolean completePendingCommand() throws IOException
{
if (ftpClient != null)
{
return getFtpsClient().completePendingCommand();
}
return true;
}
public InputStream retrieveFileStream(String relPath) throws IOException
{
try
{
return getFtpsClient().retrieveFileStream(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().retrieveFileStream(relPath);
}
}
public InputStream retrieveFileStream(String relPath, long restartOffset) throws IOException
{
try
{
FTPSClient client = getFtpsClient();
client.setRestartOffset(restartOffset);
return client.retrieveFileStream(relPath);
}
catch (IOException e)
{
disconnect();
FTPSClient client = getFtpsClient();
client.setRestartOffset(restartOffset);
return client.retrieveFileStream(relPath);
}
}
public OutputStream appendFileStream(String relPath) throws IOException
{
try
{
return getFtpsClient().appendFileStream(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().appendFileStream(relPath);
}
}
public OutputStream storeFileStream(String relPath) throws IOException
{
try
{
return getFtpsClient().storeFileStream(relPath);
}
catch (IOException e)
{
disconnect();
return getFtpsClient().storeFileStream(relPath);
}
}
public boolean abort() throws IOException
{
try
{
// imario@apache.org: 2005-02-14
// it should be better to really "abort" the transfer, but
// currently I didnt manage to make it work - so lets "abort" the hard way.
// return getFtpsClient().abort();
disconnect();
return true;
}
catch (IOException e)
{
disconnect();
}
return true;
}
public String getReplyString() throws IOException
{
return getFtpsClient().getReplyString();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileProvider.java 100644 765 24 4403 11623215065 32160 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftps;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.provider.ftp.FtpFileProvider;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystem;
/**
* A provider for FTP file systems.
*
* NOTE: Most of the heavy lifting for FTPS is done by the org.apache.commons.vfs2.provider.ftp package since
* they both use commons-net package
*
* @author Commons VFS team
* @since 2.0
*/
public class FtpsFileProvider extends FtpFileProvider
{
public FtpsFileProvider()
{
super();
}
/**
* Creates the filesystem.
*/
@Override
protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Create the file system
final GenericFileName rootName = (GenericFileName) name;
FtpsClientWrapper ftpClient = new FtpsClientWrapper(rootName, fileSystemOptions);
return new FtpFileSystem(rootName, ftpClient, fileSystemOptions);
}
@Override
public FileSystemConfigBuilder getConfigBuilder()
{
return FtpsFileSystemConfigBuilder.getInstance();
}
}
././@LongLink 100644 0 0 152 11623215455 10255 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystemConfigBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftps/FtpsFileSystemConfigBuilder100644 765 24 25502 11623215065 33412 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ftps;
import org.apache.commons.net.ftp.parser.FTPFileEntryParserFactory;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.ftp.FtpFileSystem;
/**
* The config BUILDER for various ftp configuration options.
*
* @author Commons VFS team
* @since 2.0
*/
public final class FtpsFileSystemConfigBuilder extends FileSystemConfigBuilder
{
private static final FtpsFileSystemConfigBuilder BUILDER =
new FtpsFileSystemConfigBuilder();
private static final String FACTORY_KEY =
FTPFileEntryParserFactory.class.getName() + ".KEY";
private static final String PASSIVE_MODE =
FtpsFileSystemConfigBuilder.class.getName() + ".PASSIVE";
private static final String USER_DIR_IS_ROOT =
FtpsFileSystemConfigBuilder.class.getName() + ".USER_DIR_IS_ROOT";
private static final String DATA_TIMEOUT =
FtpsFileSystemConfigBuilder.class.getName() + ".DATA_TIMEOUT";
private static final String FTPS_TYPE =
FtpsFileSystemConfigBuilder.class.getName() + ".FTPS_TYPE";
private static final String SERVER_LANGUAGE_CODE =
FtpsFileSystemConfigBuilder.class.getName() + ".SERVER_LANGUAGE_CODE";
private static final String DEFAULT_DATE_FORMAT =
FtpsFileSystemConfigBuilder.class.getName() + ".DEFAULT_DATE_FORMAT";
private static final String RECENT_DATE_FORMAT =
FtpsFileSystemConfigBuilder.class.getName() + ".RECENT_DATE_FORMAT";
private static final String SERVER_TIME_ZONE_ID =
FtpsFileSystemConfigBuilder.class.getName() + ".SERVER_TIME_ZONE_ID";
private static final String SHORT_MONTH_NAMES =
FtpsFileSystemConfigBuilder.class.getName() + ".SHORT_MONTH_NAMES";
private FtpsFileSystemConfigBuilder()
{
}
public static FtpsFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
/**
* FTPFileEntryParserFactory which will be used for ftp-entry parsing.
*
* @param opts The FileSystemOptions.
* @param factory instance of your factory
*/
public void setEntryParserFactory(FileSystemOptions opts, FTPFileEntryParserFactory factory)
{
setParam(opts, FTPFileEntryParserFactory.class.getName(), factory);
}
/**
* @param opts The FileSystemOptions
* @return The FTPFileEntryParserFactory.
* @see #setEntryParserFactory
*/
public FTPFileEntryParserFactory getEntryParserFactory(FileSystemOptions opts)
{
return (FTPFileEntryParserFactory) getParam(opts, FTPFileEntryParserFactory.class.getName());
}
/**
* set the FQCN of your FileEntryParser used to parse the directory listing from your server.
*
* If you do not use the default commons-net FTPFileEntryParserFactory e.g. by using
* {@link #setEntryParserFactory}
* this is the "key" parameter passed as argument into your custom factory
*
* @param opts The FileSystemOptions.
* @param key The key.
*/
public void setEntryParser(FileSystemOptions opts, String key)
{
setParam(opts, FACTORY_KEY, key);
}
/**
* @param opts The FileSystemOptions.
* @return The key.
* @see #setEntryParser
*/
public String getEntryParser(FileSystemOptions opts)
{
return (String) getParam(opts, FACTORY_KEY);
}
@Override
protected Class extends FileSystem> getConfigClass()
{
return FtpFileSystem.class;
}
/**
* Enter into passive mode.
*
* @param opts The FileSystemOptions.
* @param passiveMode true if passive mode should be used, false otherwise.
*/
public void setPassiveMode(FileSystemOptions opts, boolean passiveMode)
{
setParam(opts, PASSIVE_MODE, passiveMode ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @param opts The FileSystemOptions.
* @return true if passive mode is being used.
* @see #setPassiveMode
*/
public Boolean getPassiveMode(FileSystemOptions opts)
{
return (Boolean) getParam(opts, PASSIVE_MODE);
}
/**
* use user directory as root (do not change to fs root).
*
* @param opts The FileSystemOptions.
* @param userDirIsRoot true if the user directory should be the root.
*/
public void setUserDirIsRoot(FileSystemOptions opts, boolean userDirIsRoot)
{
setParam(opts, USER_DIR_IS_ROOT,
userDirIsRoot ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @param opts The FileSystemOptions.
* @return true if the user directory is the root.
* @see #setUserDirIsRoot
*/
public Boolean getUserDirIsRoot(FileSystemOptions opts)
{
return getBoolean(opts, USER_DIR_IS_ROOT, Boolean.TRUE);
}
/**
* Set FTPS security mode, either "implicit" or "explicit".
*
* @param opts The FileSystemOptions.
* @param ftpsType The file type.
*/
public void setFtpsType(FileSystemOptions opts, String ftpsType)
{
setParam(opts, FTPS_TYPE, ftpsType);
}
/**
* Return the FTPS security mode. Defaults to "explicit" if not defined.
*
* @param opts The FileSystemOptions.
* @return The file type.
* @see #setFtpsType
*/
public String getFtpsType(FileSystemOptions opts)
{
return getString(opts, FTPS_TYPE, "explicit");
}
/**
* @param opts The FileSystemOptions.
* @return The timeout value.
* @see #setDataTimeout
*/
public Integer getDataTimeout(FileSystemOptions opts)
{
return (Integer) getParam(opts, DATA_TIMEOUT);
}
/**
* set the data timeout for the ftp client.
* If you set the dataTimeout to null
no dataTimeout will be set on the
* ftp client.
*
* @param opts The FileSystemOptions.
* @param dataTimeout The timeout value.
*/
public void setDataTimeout(FileSystemOptions opts, Integer dataTimeout)
{
setParam(opts, DATA_TIMEOUT, dataTimeout);
}
/**
* get the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FileSystemOptions.
* @return The language code.
*/
public String getServerLanguageCode(FileSystemOptions opts)
{
return (String) getParam(opts, SERVER_LANGUAGE_CODE);
}
/**
* set the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FileSystemOptions.
* @param serverLanguageCode the language code.
*/
public void setServerLanguageCode(FileSystemOptions opts,
String serverLanguageCode)
{
setParam(opts, SERVER_LANGUAGE_CODE, serverLanguageCode);
}
/**
* get the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FileSystemOptions.
* @return The default date format.
*/
public String getDefaultDateFormat(FileSystemOptions opts)
{
return (String) getParam(opts, DEFAULT_DATE_FORMAT);
}
/**
* set the language code used by the server. see {@link org.apache.commons.net.ftp.FTPClientConfig}
* for details and examples.
* @param opts The FileSystemOptions.
* @param defaultDateFormat The default date format.
*/
public void setDefaultDateFormat(FileSystemOptions opts,
String defaultDateFormat)
{
setParam(opts, DEFAULT_DATE_FORMAT, defaultDateFormat);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @return The recent date format.
*/
public String getRecentDateFormat(FileSystemOptions opts)
{
return (String) getParam(opts, RECENT_DATE_FORMAT);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions
* @param recentDateFormat The recent date format.
*/
public void setRecentDateFormat(FileSystemOptions opts,
String recentDateFormat)
{
setParam(opts, RECENT_DATE_FORMAT, recentDateFormat);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @return The server timezone id.
*/
public String getServerTimeZoneId(FileSystemOptions opts)
{
return (String) getParam(opts, SERVER_TIME_ZONE_ID);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @param serverTimeZoneId The server's timezone id.
*/
public void setServerTimeZoneId(FileSystemOptions opts,
String serverTimeZoneId)
{
setParam(opts, SERVER_TIME_ZONE_ID, serverTimeZoneId);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @return An array of short month names.
*/
public String[] getShortMonthNames(FileSystemOptions opts)
{
return (String[]) getParam(opts, SHORT_MONTH_NAMES);
}
/**
* see {@link org.apache.commons.net.ftp.FTPClientConfig} for details and examples.
* @param opts The FileSystemOptions.
* @param shortMonthNames An array of short month names.
*/
public void setShortMonthNames(FileSystemOptions opts,
String[] shortMonthNames)
{
String[] clone = null;
if (shortMonthNames != null)
{
clone = new String[shortMonthNames.length];
System.arraycopy(shortMonthNames, 0, clone, 0, shortMonthNames.length);
}
setParam(opts, SHORT_MONTH_NAMES, clone);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ftps/package.html 100644 765 24 1541 11623215065 30347 0 ustar rgoers staff 0 0
The FTPS File Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/GenericFileName.java 100644 765 24 11161 11623215065 30751 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileType;
/**
* A file name that represents a 'generic' URI, as per RFC 2396. Consists of
* a scheme, userinfo (typically username and password), hostname, port, and
* path.
*
* @author Commons VFS team
*/
public class GenericFileName extends AbstractFileName
{
private static final char[] USERNAME_RESERVED = {':', '@', '/'};
private static final char[] PASSWORD_RESERVED = {'@', '/', '?'};
private final String userName;
private final String hostName;
private final int defaultPort;
private final String password;
private final int port;
protected GenericFileName(final String scheme,
final String hostName,
final int port,
final int defaultPort,
final String userName,
final String password,
final String path,
final FileType type
)
{
super(scheme, path, type);
this.hostName = hostName;
this.defaultPort = defaultPort;
this.password = password;
this.userName = userName;
if (port > 0)
{
this.port = port;
}
else
{
this.port = getDefaultPort();
}
}
/**
* Returns the user name part of this name.
* @return The user name.
*/
public String getUserName()
{
return userName;
}
/**
* Returns the password part of this name.
* @return The password.
*/
public String getPassword()
{
return password;
}
/**
* Returns the host name part of this name.
* @return The host name.
*/
public String getHostName()
{
return hostName;
}
/**
* Returns the port part of this name.
* @return The port number.
*/
public int getPort()
{
return port;
}
/**
* Returns the default port for this file name.
* @return The default port number.
*/
public int getDefaultPort()
{
return defaultPort;
}
/**
* Create a FileName.
* @param absPath The absolute path.
* @param type The FileType.
* @return The created FileName.
*/
@Override
public FileName createName(String absPath, FileType type)
{
return new GenericFileName(
getScheme(),
hostName,
port,
defaultPort,
userName,
password,
absPath,
type);
}
/**
* Builds the root URI for this file name.
*/
@Override
protected void appendRootUri(final StringBuilder buffer, boolean addPassword)
{
buffer.append(getScheme());
buffer.append("://");
appendCredentials(buffer, addPassword);
buffer.append(hostName);
if (port != getDefaultPort())
{
buffer.append(':');
buffer.append(port);
}
}
/**
* append the user credentials
*/
protected void appendCredentials(StringBuilder buffer, boolean addPassword)
{
if (userName != null && userName.length() != 0)
{
UriParser.appendEncoded(buffer, userName, USERNAME_RESERVED);
if (password != null && password.length() != 0)
{
buffer.append(':');
if (addPassword)
{
UriParser.appendEncoded(buffer, password, PASSWORD_RESERVED);
}
else
{
buffer.append("***");
}
}
buffer.append('@');
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileObject.java 100644 765 24 3717 11623215065 31575 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.gzip;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileObject;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
/**
* the gzip file.
*
* @author Commons VFS team
*/
public class GzipFileObject extends CompressedFileFileObject
{
protected GzipFileObject(AbstractFileName name, FileObject container, CompressedFileFileSystem fs)
{
super(name, container, fs);
}
@Override
protected InputStream doGetInputStream() throws Exception
{
InputStream is = getContainer().getContent().getInputStream();
return new GZIPInputStream(is);
}
@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
OutputStream os = getContainer().getContent().getOutputStream(false);
return new GZIPOutputStream(os);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileProvider.java 100644 765 24 4441 11623215065 32154 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.gzip;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileProvider;
/**
* Provides access to the content of gzip compressed files.
*
* @author Commons VFS team
*/
public class GzipFileProvider extends CompressedFileFileProvider
{
/**
* Capabilities.
*/
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.GET_LAST_MODIFIED,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.WRITE_CONTENT,
Capability.READ_CONTENT,
Capability.URI,
Capability.COMPRESS
}));
public GzipFileProvider()
{
super();
}
@Override
protected FileSystem createFileSystem(FileName name, FileObject file, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
return new GzipFileSystem(name, file, fileSystemOptions);
}
@Override
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/gzip/GzipFileSystem.java 100644 765 24 3671 11623215065 31652 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.gzip;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.compressed.CompressedFileFileSystem;
/**
* Filesytem to handle compressed files using the gzip method.
*
* @author Commons VFS team
*/
public class GzipFileSystem extends CompressedFileFileSystem
{
protected GzipFileSystem(FileName rootName, FileObject parentLayer, FileSystemOptions fileSystemOptions)
{
super(rootName, parentLayer, fileSystemOptions);
}
@Override
protected FileObject createFile(AbstractFileName name) throws FileSystemException
{
return new GzipFileObject(name, getParentLayer(), this);
}
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(GzipFileProvider.capabilities);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/gzip/package.html 100644 765 24 1532 11623215065 30344 0 ustar rgoers staff 0 0
The GZIP File Provider
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/HostFileNameParser.java 100644 765 24 21761 11623215065 31476 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.util.Cryptor;
import org.apache.commons.vfs2.util.CryptorFactory;
/**
* Implementation for any url based filesystem.
* Parses the url into user/password/host/port/path
* Does not handle a query string (after ?)
*
* @author Commons VFS team
* @see URLFileNameParser URLFileNameParser for the implementation which also handles the query string too
*/
public class HostFileNameParser extends AbstractFileNameParser
{
private final int defaultPort;
public HostFileNameParser(final int defaultPort)
{
this.defaultPort = defaultPort;
}
public int getDefaultPort()
{
return defaultPort;
}
@Override
public boolean encodeCharacter(char ch)
{
return super.encodeCharacter(ch);
}
public FileName parseUri(final VfsComponentContext context, FileName base, final String filename)
throws FileSystemException
{
// FTP URI are generic URI (as per RFC 2396)
final StringBuilder name = new StringBuilder();
// Extract the scheme and authority parts
final Authority auth = extractToPath(filename, name);
// Decode and normalise the file name
UriParser.canonicalizePath(name, 0, name.length(), this);
UriParser.fixSeparators(name);
FileType fileType = UriParser.normalisePath(name);
final String path = name.toString();
return new GenericFileName(
auth.scheme,
auth.hostName,
auth.port,
defaultPort,
auth.userName,
auth.password,
path,
fileType);
}
/**
* Extracts the scheme, userinfo, hostname and port components of a
* generic URI.
*
* @param uri The absolute URI to parse.
* @param name Used to return the remainder of the URI.
*/
protected Authority extractToPath(final String uri,
final StringBuilder name)
throws FileSystemException
{
final Authority auth = new Authority();
// Extract the scheme
auth.scheme = UriParser.extractScheme(uri, name);
// Expecting "//"
if (name.length() < 2 || name.charAt(0) != '/' || name.charAt(1) != '/')
{
throw new FileSystemException("vfs.provider/missing-double-slashes.error", uri);
}
name.delete(0, 2);
// Extract userinfo, and split into username and password
final String userInfo = extractUserInfo(name);
final String userName;
final String password;
if (userInfo != null)
{
int idx = userInfo.indexOf(':');
if (idx == -1)
{
userName = userInfo;
password = null;
}
else
{
userName = userInfo.substring(0, idx);
password = userInfo.substring(idx + 1);
}
}
else
{
userName = null;
password = null;
}
auth.userName = UriParser.decode(userName);
auth.password = UriParser.decode(password);
if (auth.password != null && auth.password.startsWith("{") && auth.password.endsWith("}"))
{
try
{
Cryptor cryptor = CryptorFactory.getCryptor();
auth.password = cryptor.decrypt(auth.password.substring(1, auth.password.length() - 1));
}
catch (Exception ex)
{
throw new FileSystemException("Unable to decrypt password", ex);
}
}
// Extract hostname, and normalise (lowercase)
final String hostName = extractHostName(name);
if (hostName == null)
{
throw new FileSystemException("vfs.provider/missing-hostname.error", uri);
}
auth.hostName = hostName.toLowerCase();
// Extract port
auth.port = extractPort(name, uri);
// Expecting '/' or empty name
if (name.length() > 0 && name.charAt(0) != '/')
{
throw new FileSystemException("vfs.provider/missing-hostname-path-sep.error", uri);
}
return auth;
}
/**
* Extracts the user info from a URI. The scheme:// part has been removed
* already.
*/
protected String extractUserInfo(final StringBuilder name)
{
final int maxlen = name.length();
for (int pos = 0; pos < maxlen; pos++)
{
final char ch = name.charAt(pos);
if (ch == '@')
{
// Found the end of the user info
String userInfo = name.substring(0, pos);
name.delete(0, pos + 1);
return userInfo;
}
if (ch == '/' || ch == '?')
{
// Not allowed in user info
break;
}
}
// Not found
return null;
}
/**
* Extracts the hostname from a URI. The scheme://userinfo@ part has
* been removed.
*/
protected String extractHostName(final StringBuilder name)
{
final int maxlen = name.length();
int pos = 0;
for (; pos < maxlen; pos++)
{
final char ch = name.charAt(pos);
if (ch == '/' || ch == ';' || ch == '?' || ch == ':'
|| ch == '@' || ch == '&' || ch == '=' || ch == '+'
|| ch == '$' || ch == ',')
{
break;
}
}
if (pos == 0)
{
return null;
}
final String hostname = name.substring(0, pos);
name.delete(0, pos);
return hostname;
}
/**
* Extracts the port from a URI. The scheme://userinfo@hostname
* part has been removed.
*
* @return The port, or -1 if the URI does not contain a port.
*/
protected int extractPort(final StringBuilder name, final String uri) throws FileSystemException
{
if (name.length() < 1 || name.charAt(0) != ':')
{
return -1;
}
final int maxlen = name.length();
int pos = 1;
for (; pos < maxlen; pos++)
{
final char ch = name.charAt(pos);
if (ch < '0' || ch > '9')
{
break;
}
}
final String port = name.substring(1, pos);
name.delete(0, pos);
if (port.length() == 0)
{
throw new FileSystemException("vfs.provider/missing-port.error", uri);
}
return Integer.parseInt(port);
}
/**
* Parsed authority info (scheme, hostname, userinfo, port)
*/
protected static class Authority
{
private String scheme;
private String hostName;
private String userName;
private String password;
private int port;
/** @since 2.0 */
public String getScheme()
{
return scheme;
}
/** @since 2.0 */
public void setScheme(String scheme)
{
this.scheme = scheme;
}
/** @since 2.0 */
public String getHostName()
{
return hostName;
}
/** @since 2.0 */
public void setHostName(String hostName)
{
this.hostName = hostName;
}
/** @since 2.0 */
public String getUserName()
{
return userName;
}
/** @since 2.0 */
public void setUserName(String userName)
{
this.userName = userName;
}
/** @since 2.0 */
public String getPassword()
{
return password;
}
/** @since 2.0 */
public void setPassword(String password)
{
this.password = password;
}
/** @since 2.0 */
public int getPort()
{
return port;
}
/** @since 2.0 */
public void setPort(int port)
{
this.port = port;
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpClientFactory.java 100644 765 24 15363 11623215064 32370 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.HostConfiguration;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.httpclient.UsernamePasswordCredentials;
import org.apache.commons.httpclient.auth.AuthScope;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.params.HttpClientParams;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.UserAuthenticator;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* Create a HttpClient instance.
*
* @author Commons VFS team
*/
public final class HttpClientFactory
{
private HttpClientFactory()
{
}
public static HttpClient createConnection(String scheme, String hostname, int port, String username,
String password, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
return createConnection(HttpFileSystemConfigBuilder.getInstance(), scheme, hostname, port,
username, password, fileSystemOptions);
}
/**
* Creates a new connection to the server.
* @param builder The HttpFileSystemConfigBuilder.
* @param scheme The protocol.
* @param hostname The hostname.
* @param port The port number.
* @param username The username.
* @param password The password
* @param fileSystemOptions The file system options.
* @return a new HttpClient connection.
* @throws FileSystemException if an error occurs.
* @since 2.0
*/
public static HttpClient createConnection(HttpFileSystemConfigBuilder builder, String scheme,
String hostname, int port, String username,
String password, FileSystemOptions fileSystemOptions)
throws FileSystemException
{
HttpClient client;
try
{
HttpConnectionManager mgr = new MultiThreadedHttpConnectionManager();
HttpConnectionManagerParams connectionMgrParams = mgr.getParams();
client = new HttpClient(mgr);
final HostConfiguration config = new HostConfiguration();
config.setHost(hostname, port, scheme);
if (fileSystemOptions != null)
{
String proxyHost = builder.getProxyHost(fileSystemOptions);
int proxyPort = builder.getProxyPort(fileSystemOptions);
if (proxyHost != null && proxyHost.length() > 0 && proxyPort > 0)
{
config.setProxy(proxyHost, proxyPort);
}
UserAuthenticator proxyAuth = builder.getProxyAuthenticator(fileSystemOptions);
if (proxyAuth != null)
{
UserAuthenticationData authData = UserAuthenticatorUtils.authenticate(proxyAuth,
new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME,
UserAuthenticationData.PASSWORD
});
if (authData != null)
{
final UsernamePasswordCredentials proxyCreds =
new UsernamePasswordCredentials(
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.USERNAME, null)),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.PASSWORD, null)));
AuthScope scope = new AuthScope(proxyHost, AuthScope.ANY_PORT);
client.getState().setProxyCredentials(scope, proxyCreds);
}
if (builder.isPreemptiveAuth(fileSystemOptions))
{
HttpClientParams httpClientParams = new HttpClientParams();
httpClientParams.setAuthenticationPreemptive(true);
client.setParams(httpClientParams);
}
}
Cookie[] cookies = builder.getCookies(fileSystemOptions);
if (cookies != null)
{
client.getState().addCookies(cookies);
}
}
/**
* ConnectionManager set methodsmust be called after the host & port and proxy host & port
* are set in the HostConfiguration. They are all used as part of the key when HttpConnectionManagerParams
* tries to locate the host configuration.
*/
connectionMgrParams.setMaxConnectionsPerHost(config, builder.getMaxConnectionsPerHost(fileSystemOptions));
connectionMgrParams.setMaxTotalConnections(builder.getMaxTotalConnections(fileSystemOptions));
client.setHostConfiguration(config);
if (username != null)
{
final UsernamePasswordCredentials creds =
new UsernamePasswordCredentials(username, password);
AuthScope scope = new AuthScope(hostname, AuthScope.ANY_PORT);
client.getState().setCredentials(scope, creds);
}
client.executeMethod(new HeadMethod());
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider.http/connect.error", new Object[]{hostname}, exc);
}
return client;
}
}
././@LongLink 100644 0 0 151 11623215455 10254 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileContentInfoFactory.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileContentInfoFactory.100644 765 24 4306 11623215064 33311 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HeaderElement;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileContentInfo;
import org.apache.commons.vfs2.FileContentInfoFactory;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.impl.DefaultFileContentInfo;
import org.apache.commons.vfs2.util.FileObjectUtils;
/**
* Creates the FileContentInfo.
*
* @author Commons VFS team
*/
public class HttpFileContentInfoFactory implements FileContentInfoFactory
{
public FileContentInfo create(FileContent fileContent) throws FileSystemException
{
HttpFileObject httpFile = (HttpFileObject) (FileObjectUtils
.getAbstractFileObject(fileContent.getFile()));
String contentType = null;
String contentEncoding = null;
Header header = httpFile.getHeadMethod().getResponseHeader("content-type");
if (header != null)
{
HeaderElement[] element = header.getElements();
if (element != null && element.length > 0)
{
contentType = element[0].getName();
}
}
contentEncoding = httpFile.getHeadMethod().getResponseCharSet();
return new DefaultFileContentInfo(contentType, contentEncoding);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileNameParser.java 100644 765 24 2575 11623215064 32440 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.URLFileNameParser;
/**
* Implementation for http. set default port to 80
* @author Commons VFS team
*/
public class HttpFileNameParser extends URLFileNameParser
{
private static final HttpFileNameParser INSTANCE = new HttpFileNameParser();
public HttpFileNameParser()
{
super(80);
}
public static FileNameParser getInstance()
{
return INSTANCE;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileObject.java 100644 765 24 17104 11623215064 31623 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import org.apache.commons.httpclient.Header;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.httpclient.methods.HeadMethod;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.vfs2.FileContentInfoFactory;
import org.apache.commons.vfs2.FileNotFoundException;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
import org.apache.commons.vfs2.provider.URLFileName;
import org.apache.commons.vfs2.util.MonitorInputStream;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* A file object backed by commons httpclient.
*
* @author Commons VFS team
* @todo status codes
*/
public class HttpFileObject extends AbstractFileObject
{
private final HttpFileSystem fileSystem;
private final String urlCharset;
private HeadMethod method;
protected HttpFileObject(final AbstractFileName name, final HttpFileSystem fileSystem)
{
super(name, fileSystem);
this.fileSystem = fileSystem;
urlCharset = HttpFileSystemConfigBuilder.getInstance().getUrlCharset(getFileSystem().getFileSystemOptions());
}
/**
* Detaches this file object from its file resource.
*/
@Override
protected void doDetach() throws Exception
{
method = null;
}
/**
* Determines the type of this file. Must not return null. The return
* value of this method is cached, so the implementation can be expensive.
*/
@Override
protected FileType doGetType() throws Exception
{
// Use the HEAD method to probe the file.
method = new HeadMethod();
setupMethod(method);
final HttpClient client = fileSystem.getClient();
final int status = client.executeMethod(method);
method.releaseConnection();
if (status == HttpURLConnection.HTTP_OK)
{
return FileType.FILE;
}
else if (status == HttpURLConnection.HTTP_NOT_FOUND
|| status == HttpURLConnection.HTTP_GONE)
{
return FileType.IMAGINARY;
}
else
{
throw new FileSystemException("vfs.provider.http/head.error", getName());
}
}
/**
* Lists the children of this file.
*/
@Override
protected String[] doListChildren() throws Exception
{
throw new Exception("Not implemented.");
}
/**
* Returns the size of the file content (in bytes).
*/
@Override
protected long doGetContentSize() throws Exception
{
final Header header = method.getResponseHeader("content-length");
if (header == null)
{
// Assume 0 content-length
return 0;
}
return Long.parseLong(header.getValue());
}
/**
* Returns the last modified time of this file.
*
* This implementation throws an exception.
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
final Header header = method.getResponseHeader("last-modified");
if (header == null)
{
throw new FileSystemException("vfs.provider.http/last-modified.error", getName());
}
return DateUtil.parseDate(header.getValue()).getTime();
}
/**
* Creates an input stream to read the file content from. Is only called
* if {@link #doGetType} returns {@link FileType#FILE}.
*
* It is guaranteed that there are no open output streams for this file
* when this method is called.
*
* The returned stream does not have to be buffered.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
final GetMethod getMethod = new GetMethod();
setupMethod(getMethod);
final int status = fileSystem.getClient().executeMethod(getMethod);
if (status == HttpURLConnection.HTTP_NOT_FOUND)
{
throw new FileNotFoundException(getName());
}
if (status != HttpURLConnection.HTTP_OK)
{
throw new FileSystemException("vfs.provider.http/get.error", getName());
}
return new HttpInputStream(getMethod);
}
@Override
protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
{
return new HttpRandomAccessContent(this, mode);
}
/**
* Prepares a Method object.
* @since 2.0 (was package)
*/
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException
{
String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(urlCharset);
method.setPath(pathEncoded);
method.setFollowRedirects(true);
method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS");
}
protected String encodePath(final String decodedPath) throws URIException
{
String pathEncoded = URIUtil.encodePath(decodedPath);
return pathEncoded;
}
/**
* An InputStream that cleans up the HTTP connection on close.
*/
static class HttpInputStream extends MonitorInputStream
{
private final GetMethod method;
public HttpInputStream(final GetMethod method)
throws IOException
{
super(method.getResponseBodyAsStream());
this.method = method;
}
/**
* Called after the stream has been closed.
*/
@Override
protected void onClose() throws IOException
{
method.releaseConnection();
}
}
@Override
protected FileContentInfoFactory getFileContentInfoFactory()
{
return new HttpFileContentInfoFactory();
}
HeadMethod getHeadMethod()
{
return method;
}
/*
protected Map doGetAttributes() throws Exception
{
TreeMap map = new TreeMap();
Header contentType = method.getResponseHeader("content-type");
if (contentType != null)
{
HeaderElement[] element = contentType.getValues();
if (element != null && element.length > 0)
{
map.put("content-type", element[0].getName());
}
}
map.put("content-encoding", method.getResponseCharSet());
return map;
}
*/
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileProvider.java 100644 765 24 7674 11623215064 32202 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* An HTTP provider that uses commons-httpclient.
*
* @author Commons VFS team
*/
public class HttpFileProvider
extends AbstractOriginatingFileProvider
{
/** Authenticator information. */
public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD
};
static final Collection capabilities = Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.GET_TYPE,
Capability.READ_CONTENT,
Capability.URI,
Capability.GET_LAST_MODIFIED,
Capability.ATTRIBUTES,
Capability.RANDOM_ACCESS_READ,
Capability.DIRECTORY_READ_CONTENT,
}));
public HttpFileProvider()
{
super();
setFileNameParser(HttpFileNameParser.getInstance());
}
/**
* Creates a {@link FileSystem}.
*/
@Override
protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Create the file system
final GenericFileName rootName = (GenericFileName) name;
UserAuthenticationData authData = null;
HttpClient httpClient;
try
{
authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, AUTHENTICATOR_TYPES);
httpClient = HttpClientFactory.createConnection(
rootName.getScheme(),
rootName.getHostName(),
rootName.getPort(),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName()))),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()))),
fileSystemOptions);
}
finally
{
UserAuthenticatorUtils.cleanup(authData);
}
return new HttpFileSystem(rootName, httpClient, fileSystemOptions);
}
@Override
public FileSystemConfigBuilder getConfigBuilder()
{
return HttpFileSystemConfigBuilder.getInstance();
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystem.java 100644 765 24 5474 11623215064 31670 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import java.util.Collection;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.httpclient.HttpConnectionManager;
import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
import org.apache.commons.vfs2.provider.GenericFileName;
/**
* An HTTP file system.
*
* @author Commons VFS team
*/
public class HttpFileSystem
extends AbstractFileSystem
implements FileSystem
{
private final HttpClient client;
protected HttpFileSystem(final GenericFileName rootName, final HttpClient client,
final FileSystemOptions fileSystemOptions)
{
super(rootName, null, fileSystemOptions);
this.client = client;
}
/**
* Adds the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(HttpFileProvider.capabilities);
}
protected HttpClient getClient()
{
return client;
}
/** @since 2.0 */
@Override
public void closeCommunicationLink()
{
if (getClient() != null)
{
HttpConnectionManager mgr = getClient().getHttpConnectionManager();
if (mgr instanceof MultiThreadedHttpConnectionManager)
{
((MultiThreadedHttpConnectionManager) mgr).shutdown();
}
}
}
/**
* Creates a file object. This method is called only if the requested
* file is not cached.
*/
@Override
protected FileObject createFile(final AbstractFileName name)
throws Exception
{
return new HttpFileObject(name, this);
}
}
././@LongLink 100644 0 0 152 11623215455 10255 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystemConfigBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpFileSystemConfigBuilder100644 765 24 17774 11623215064 33433 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import org.apache.commons.httpclient.Cookie;
import org.apache.commons.httpclient.params.HttpConnectionManagerParams;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticator;
/**
* Configuration options for HTTP.
*
* @author Commons VFS team
*/
public class HttpFileSystemConfigBuilder extends FileSystemConfigBuilder
{
private static final HttpFileSystemConfigBuilder BUILDER = new HttpFileSystemConfigBuilder();
private static final int DEFAULT_MAX_HOST_CONNECTIONS = 5;
private static final int DEFAULT_MAX_CONNECTIONS = 50;
private static final String OPTION_NAME_PREEMPTIVE_AUTHENTICATION = "preemptiveAuth";
/** @since 2.0 */
protected HttpFileSystemConfigBuilder(String prefix)
{
super(prefix);
}
private HttpFileSystemConfigBuilder()
{
super("http.");
}
public static HttpFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
/**
* Set the charset used for url encoding.
*
* @param opts The FileSystem options.
* @param chaset the chaset
*/
public void setUrlCharset(FileSystemOptions opts, String chaset)
{
setParam(opts, "urlCharset", chaset);
}
/**
* Set the charset used for url encoding.
*
* @param opts The FileSystem options.
* @return the chaset
*/
public String getUrlCharset(FileSystemOptions opts)
{
return getString(opts, "urlCharset");
}
/**
* Set the proxy to use for http connection.
* You have to set the ProxyPort too if you would like to have the proxy really used.
*
* @param opts The FileSystem options.
* @param proxyHost the host
* @see #setProxyPort
*/
public void setProxyHost(FileSystemOptions opts, String proxyHost)
{
setParam(opts, "proxyHost", proxyHost);
}
/**
* Set the proxy-port to use for http connection.
* You have to set the ProxyHost too if you would like to have the proxy really used.
*
* @param opts The FileSystem options.
* @param proxyPort the port
* @see #setProxyHost
*/
public void setProxyPort(FileSystemOptions opts, int proxyPort)
{
setParam(opts, "proxyPort", new Integer(proxyPort));
}
/**
* Get the proxy to use for http connection.
* You have to set the ProxyPort too if you would like to have the proxy really used.
*
* @param opts The FileSystem options.
* @return proxyHost
* @see #setProxyPort
*/
public String getProxyHost(FileSystemOptions opts)
{
return getString(opts, "proxyHost");
}
/**
* Get the proxy-port to use for http the connection.
* You have to set the ProxyHost too if you would like to have the proxy really used.
*
* @param opts The FileSystem options.
* @return proxyPort: the port number or 0 if it is not set
* @see #setProxyHost
*/
public int getProxyPort(FileSystemOptions opts)
{
return getInteger(opts, "proxyPort", 0);
}
/**
* Set the proxy authenticator where the system should get the credentials from.
* @param opts The FileSystem options.
* @param authenticator The UserAuthenticator.
*/
public void setProxyAuthenticator(FileSystemOptions opts, UserAuthenticator authenticator)
{
setParam(opts, "proxyAuthenticator", authenticator);
}
/**
* Get the proxy authenticator where the system should get the credentials from.
* @param opts The FileSystem options.
* @return The UserAuthenticator.
*/
public UserAuthenticator getProxyAuthenticator(FileSystemOptions opts)
{
return (UserAuthenticator) getParam(opts, "proxyAuthenticator");
}
/**
* The cookies to add to the request.
* @param opts The FileSystem options.
* @param cookies An array of Cookies.
*/
public void setCookies(FileSystemOptions opts, Cookie[] cookies)
{
setParam(opts, "cookies", cookies);
}
/**
* The cookies to add to the request.
* @param opts The FileSystem options.
* @return the Cookie array.
*/
public Cookie[] getCookies(FileSystemOptions opts)
{
return (Cookie[]) getParam(opts, "cookies");
}
/**
* The maximum number of connections allowed.
* @param opts The FileSystem options.
* @param maxTotalConnections The maximum number of connections.
* @since 2.0
*/
public void setMaxTotalConnections(FileSystemOptions opts, int maxTotalConnections)
{
setParam(opts, HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, new Integer(maxTotalConnections));
}
/**
* Retrieve the maximum number of connections allowed.
* @param opts The FileSystemOptions.
* @return The maximum number of connections allowed.
* @since 2.0
*/
public int getMaxTotalConnections(FileSystemOptions opts)
{
return getInteger(opts, HttpConnectionManagerParams.MAX_TOTAL_CONNECTIONS, DEFAULT_MAX_CONNECTIONS);
}
/**
* The maximum number of connections allowed to any host.
* @param opts The FileSystem options.
* @param maxHostConnections The maximum number of connections to a host.
* @since 2.0
*/
public void setMaxConnectionsPerHost(FileSystemOptions opts, int maxHostConnections)
{
setParam(opts, HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, new Integer(maxHostConnections));
}
/**
* Retrieve the maximum number of connections allowed per host.
* @param opts The FileSystemOptions.
* @return The maximum number of connections allowed per host.
* @since 2.0
*/
public int getMaxConnectionsPerHost(FileSystemOptions opts)
{
return getInteger(opts, HttpConnectionManagerParams.MAX_HOST_CONNECTIONS, DEFAULT_MAX_HOST_CONNECTIONS);
}
/**
* Determines if the FileSystemOptions indicate that preemptive
* authentication is requested.
* @param opts The FileSystemOptions.
* @return true if preemptiveAuth is requested.
* @since 2.0
*/
public boolean isPreemptiveAuth(FileSystemOptions opts)
{
return getBoolean(opts, OPTION_NAME_PREEMPTIVE_AUTHENTICATION, Boolean.FALSE).booleanValue();
}
/**
* Sets the given value for preemptive HTTP authentication (using BASIC) on the
* given FileSystemOptions object. Defaults to false if not set. It may be
* appropriate to set to true in cases when the resulting chattiness of the
* conversation outweighs any architectural desire to use a stronger authentication
* scheme than basic/preemptive.
* @param opts The FileSystemOptions.
* @param preemptiveAuth the desired setting; true=enabled and false=disabled.
*/
public void setPreemptiveAuth(FileSystemOptions opts, boolean preemptiveAuth)
{
setParam(opts, OPTION_NAME_PREEMPTIVE_AUTHENTICATION, Boolean.valueOf(preemptiveAuth));
}
@Override
protected Class extends FileSystem> getConfigClass()
{
return HttpFileSystem.class;
}
}
././@LongLink 100644 0 0 146 11623215455 10260 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpRandomAccessContent.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/HttpRandomAccessContent.jav100644 765 24 11576 11623215064 33360 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.http;
import java.io.DataInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.net.HttpURLConnection;
import org.apache.commons.httpclient.methods.GetMethod;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractRandomAccessStreamContent;
import org.apache.commons.vfs2.util.MonitorInputStream;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* RandomAccess content using Http.
* @author Commons VFS team
*/
class HttpRandomAccessContent extends AbstractRandomAccessStreamContent
{
protected long filePointer = 0;
private final HttpFileObject fileObject;
private final HttpFileSystem fileSystem;
private DataInputStream dis = null;
private MonitorInputStream mis = null;
HttpRandomAccessContent(final HttpFileObject fileObject, RandomAccessMode mode)
{
super(mode);
this.fileObject = fileObject;
fileSystem = (HttpFileSystem) this.fileObject.getFileSystem();
}
public long getFilePointer() throws IOException
{
return filePointer;
}
public void seek(long pos) throws IOException
{
if (pos == filePointer)
{
// no change
return;
}
if (pos < 0)
{
throw new FileSystemException("vfs.provider/random-access-invalid-position.error",
new Object[]
{
new Long(pos)
});
}
if (dis != null)
{
close();
}
filePointer = pos;
}
@Override
protected DataInputStream getDataInputStream() throws IOException
{
if (dis != null)
{
return dis;
}
final GetMethod getMethod = new GetMethod();
fileObject.setupMethod(getMethod);
getMethod.setRequestHeader("Range", "bytes=" + filePointer + "-");
final int status = fileSystem.getClient().executeMethod(getMethod);
if (status != HttpURLConnection.HTTP_PARTIAL && status != HttpURLConnection.HTTP_OK)
{
throw new FileSystemException("vfs.provider.http/get-range.error", new Object[]
{
fileObject.getName(),
new Long(filePointer)
});
}
mis = new HttpFileObject.HttpInputStream(getMethod);
// If the range request was ignored
if (status == HttpURLConnection.HTTP_OK)
{
long skipped = mis.skip(filePointer);
if (skipped != filePointer)
{
throw new FileSystemException("vfs.provider.http/get-range.error", new Object[]
{
fileObject.getName(),
new Long(filePointer)
});
}
}
dis = new DataInputStream(new FilterInputStream(mis)
{
@Override
public int read() throws IOException
{
int ret = super.read();
if (ret > -1)
{
filePointer++;
}
return ret;
}
@Override
public int read(byte[] b) throws IOException
{
int ret = super.read(b);
if (ret > -1)
{
filePointer += ret;
}
return ret;
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
int ret = super.read(b, off, len);
if (ret > -1)
{
filePointer += ret;
}
return ret;
}
});
return dis;
}
public void close() throws IOException
{
if (dis != null)
{
dis.close();
dis = null;
mis = null;
}
}
public long length() throws IOException
{
return fileObject.getContent().getSize();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/http/package.html 100644 765 24 1532 11623215064 30351 0 ustar rgoers staff 0 0
The HTTP File Provider
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileNameParser.java 100644 765 24 2606 11623215065 33002 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.https;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.URLFileNameParser;
/**
* Implementation for https. set default port to 443.
* @author Commons VFS team
*/
public class HttpsFileNameParser extends URLFileNameParser
{
private static final HttpsFileNameParser INSTANCE = new HttpsFileNameParser();
public HttpsFileNameParser()
{
super(443);
}
public static FileNameParser getInstance()
{
return INSTANCE;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/https/HttpsFileProvider.java 100644 765 24 2343 11623215065 32535 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.https;
import org.apache.commons.vfs2.provider.http.HttpFileProvider;
/**
* An HTTPS provider that uses commons-httpclient.
*
* @author Commons VFS team
*/
public class HttpsFileProvider
extends HttpFileProvider
{
public HttpsFileProvider()
{
super();
setFileNameParser(HttpsFileNameParser.getInstance());
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/https/package.html 100644 765 24 1533 11623215065 30536 0 ustar rgoers staff 0 0
The HTTPS File Provider
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileObject.java 100644 765 24 10214 11623215064 31210 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.jar;
import java.io.IOException;
import java.security.cert.Certificate;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.zip.ZipFileObject;
/**
* A file in a Jar file system.
*
* @author Commons VFS team
*/
public class JarFileObject extends ZipFileObject
{
private final JarFileSystem fs;
private Attributes attributes;
protected JarFileObject(final AbstractFileName name,
final ZipEntry entry,
final JarFileSystem fs,
final boolean zipExists) throws FileSystemException
{
super(name, entry, fs, zipExists);
this.fs = fs;
try
{
getAttributes(); // early get the attributes as the zip file might be closed
}
catch (IOException e)
{
throw new FileSystemException(e);
}
}
/**
* Returns the Jar manifest.
*/
Manifest getManifest() throws IOException
{
if (fs.getZipFile() == null)
{
return null;
}
return ((JarFile) fs.getZipFile()).getManifest();
}
/**
* Returns the attributes of this file.
*/
Attributes getAttributes() throws IOException
{
if (attributes == null)
{
if (entry == null)
{
attributes = new Attributes(1);
}
else
{
attributes = ((JarEntry) entry).getAttributes();
if (attributes == null)
{
attributes = new Attributes(1);
}
}
}
return attributes;
}
/**
* Returns the value of an attribute.
*/
@Override
protected Map doGetAttributes()
throws Exception
{
final Map attrs = new HashMap();
// Add the file system's attributes first
final JarFileSystem fs = (JarFileSystem) getFileSystem();
addAll(fs.getAttributes(), attrs);
// Add this file's attributes
addAll(getAttributes(), attrs);
return attrs;
}
/**
* Adds the source attributes to the destination map.
*/
private void addAll(final Attributes src, final Map dest)
{
for (Iterator> iterator = src.entrySet().iterator(); iterator.hasNext();)
{
final Map.Entry entry = iterator.next();
// final String name = entry.getKey().toString().toLowerCase();
final String name = entry.getKey().toString();
dest.put(name, entry.getValue());
}
}
/**
* Return the certificates of this JarEntry.
*/
@Override
protected Certificate[] doGetCertificates()
{
if (entry == null)
{
return null;
}
return ((JarEntry) entry).getCertificates();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileProvider.java 100644 765 24 6247 11623215064 31567 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.jar;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.LayeredFileName;
import org.apache.commons.vfs2.provider.zip.ZipFileProvider;
/**
* A file system provider for Jar files. Provides read-only file
* systems. This provides access to Jar specific features like Signing and
* Manifest Attributes.
*
* @author Commons VFS team
*/
public class JarFileProvider extends ZipFileProvider
{
static final Collection capabilities;
static
{
Collection combined = new ArrayList();
combined.addAll(ZipFileProvider.capabilities);
combined.addAll(Arrays.asList(new Capability[]
{
Capability.ATTRIBUTES,
Capability.FS_ATTRIBUTES,
Capability.SIGNING,
Capability.MANIFEST_ATTRIBUTES,
Capability.VIRTUAL
}));
capabilities = Collections.unmodifiableCollection(combined);
}
public JarFileProvider()
{
super();
}
/**
* Creates a layered file system. This method is called if the file system
* is not cached.
*
* @param scheme The URI scheme.
* @param file The file to create the file system on top of.
* @return The file system.
*/
@Override
protected FileSystem doCreateFileSystem(final String scheme,
final FileObject file,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
final AbstractFileName name =
new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
return new JarFileSystem(name, file, fileSystemOptions);
}
@Override
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarFileSystem.java 100644 765 24 15024 11623215064 31272 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.jar;
import java.io.File;
import java.io.IOException;
import java.util.Collection;
import java.util.jar.Attributes;
import java.util.jar.Attributes.Name;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.zip.ZipFileObject;
import org.apache.commons.vfs2.provider.zip.ZipFileSystem;
/**
* A read-only file system for Jar files.
*
* @author Commons VFS team
*/
public class JarFileSystem extends ZipFileSystem
{
private Attributes attributes;
protected JarFileSystem(final AbstractFileName rootName,
final FileObject file,
final FileSystemOptions fileSystemOptions) throws FileSystemException
{
super(rootName, file, fileSystemOptions);
}
@Override
protected ZipFile createZipFile(File file) throws FileSystemException
{
try
{
return new JarFile(file);
}
catch (IOException ioe)
{
throw new FileSystemException("vfs.provider.jar/open-jar-file.error", file, ioe);
}
}
@Override
protected ZipFileObject createZipFileObject(AbstractFileName name,
ZipEntry entry) throws FileSystemException
{
return new JarFileObject(name, entry, this, true);
}
/**
* Returns the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
// super.addCapabilities(caps);
caps.addAll(JarFileProvider.capabilities);
}
Attributes getAttributes() throws IOException
{
if (attributes == null)
{
final Manifest man = ((JarFile) getZipFile()).getManifest();
if (man == null)
{
attributes = new Attributes(1);
}
else
{
attributes = man.getMainAttributes();
if (attributes == null)
{
attributes = new Attributes(1);
}
}
}
return attributes;
}
Object getAttribute(Name attrName)
throws FileSystemException
{
try
{
final Attributes attr = getAttributes();
final String value = attr.getValue(attrName);
return value;
}
catch (IOException ioe)
{
throw new FileSystemException(attrName.toString(), ioe);
}
}
Name lookupName(String attrName)
{
if (Name.CLASS_PATH.toString().equals(attrName))
{
return Name.CLASS_PATH;
}
else if (Name.CONTENT_TYPE.toString().equals(attrName))
{
return Name.CONTENT_TYPE;
}
else if (Name.EXTENSION_INSTALLATION.toString().equals(attrName))
{
return Name.EXTENSION_INSTALLATION;
}
else if (Name.EXTENSION_LIST.toString().equals(attrName))
{
return Name.EXTENSION_LIST;
}
else if (Name.EXTENSION_NAME.toString().equals(attrName))
{
return Name.EXTENSION_NAME;
}
else if (Name.IMPLEMENTATION_TITLE.toString().equals(attrName))
{
return Name.IMPLEMENTATION_TITLE;
}
else if (Name.IMPLEMENTATION_URL.toString().equals(attrName))
{
return Name.IMPLEMENTATION_URL;
}
else if (Name.IMPLEMENTATION_VENDOR.toString().equals(attrName))
{
return Name.IMPLEMENTATION_VENDOR;
}
else if (Name.IMPLEMENTATION_VENDOR_ID.toString().equals(attrName))
{
return Name.IMPLEMENTATION_VENDOR_ID;
}
else if (Name.IMPLEMENTATION_VERSION.toString().equals(attrName))
{
return Name.IMPLEMENTATION_VENDOR;
}
else if (Name.MAIN_CLASS.toString().equals(attrName))
{
return Name.MAIN_CLASS;
}
else if (Name.MANIFEST_VERSION.toString().equals(attrName))
{
return Name.MANIFEST_VERSION;
}
else if (Name.SEALED.toString().equals(attrName))
{
return Name.SEALED;
}
else if (Name.SIGNATURE_VERSION.toString().equals(attrName))
{
return Name.SIGNATURE_VERSION;
}
else if (Name.SPECIFICATION_TITLE.toString().equals(attrName))
{
return Name.SPECIFICATION_TITLE;
}
else if (Name.SPECIFICATION_VENDOR.toString().equals(attrName))
{
return Name.SPECIFICATION_VENDOR;
}
else if (Name.SPECIFICATION_VERSION.toString().equals(attrName))
{
return Name.SPECIFICATION_VERSION;
}
else
{
return new Name(attrName);
}
}
/**
* Retrives the attribute with the specified name. The default
* implementation simply throws an exception.
* @param attrName The attiribute's name.
* @return The value of the attribute.
* @throws FileSystemException if an error occurs.
*/
@Override
public Object getAttribute(String attrName) throws FileSystemException
{
final Name name = lookupName(attrName);
return getAttribute(name);
}
@Override
protected ZipFile getZipFile() throws FileSystemException
{
return super.getZipFile();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/jar/JarURLConnectionImpl.java 100644 765 24 7117 11623215064 32476 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.jar;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.JarURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.cert.Certificate;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileSystemException;
/**
* A default URL connection that will work for most file systems.
*
* @author Commons VFS team
*/
public class JarURLConnectionImpl
extends JarURLConnection
{
// This is because JarURLConnection SUCKS
private static final String HACK_URL = "jar:http://somehost/somejar.jar!/";
private final FileContent content;
private final URL parentURL;
private final JarFileObject file;
private final String entryName;
public JarURLConnectionImpl(JarFileObject file, FileContent content)
throws MalformedURLException, FileSystemException
{
//This is because JarURLConnection SUCKS!!
super(new URL(HACK_URL));
this.url = file.getURL();
this.content = content;
this.parentURL = file.getURL();
this.entryName = file.getName().getPath();
this.file = file;
}
@Override
public URL getJarFileURL()
{
return parentURL;
}
@Override
public String getEntryName()
{
return entryName;
}
@Override
public JarFile getJarFile() throws IOException
{
throw new FileSystemException("vfs.provider.jar/jar-file-no-access.error");
}
@Override
public Manifest getManifest() throws IOException
{
return file.getManifest();
}
@Override
public JarEntry getJarEntry() throws IOException
{
throw new FileSystemException("vfs.provider.jar/jar-entry-no-access.error");
}
@Override
public Attributes getAttributes() throws IOException
{
return file.getAttributes();
}
@Override
public Certificate[] getCertificates()
{
return file.doGetCertificates();
}
@Override
public void connect()
{
connected = true;
}
@Override
public InputStream getInputStream()
throws IOException
{
return content.getInputStream();
}
@Override
public OutputStream getOutputStream()
throws IOException
{
return content.getOutputStream();
}
@Override
public int getContentLength()
{
try
{
return (int) content.getSize();
}
catch (FileSystemException fse)
{
// Ignore the error.
}
return -1;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/jar/package.html 100644 765 24 1540 11623215064 30145 0 ustar rgoers staff 0 0
The Jar File Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileName.java 100644 765 24 4127 11623215065 30746 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileType;
/**
* A file name for layered files.
*
* @author Commons VFS team
*/
public class LayeredFileName extends AbstractFileName
{
private final FileName outerUri;
public LayeredFileName(final String scheme,
final FileName outerUri,
final String path,
final FileType type)
{
super(scheme, path, type);
this.outerUri = outerUri;
}
/**
* Returns the URI of the outer file.
* @return The FileName.
*/
public FileName getOuterName()
{
return outerUri;
}
/**
* Create a FileName.
* @param path The file URI.
* @param type The FileType.
* @return The FileName.
*/
@Override
public FileName createName(String path, FileType type)
{
return new LayeredFileName(getScheme(), getOuterName(), path, type);
}
@Override
protected void appendRootUri(StringBuilder buffer, boolean addPassword)
{
buffer.append(getScheme());
buffer.append(":");
buffer.append(getOuterName().getURI());
buffer.append("!");
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/LayeredFileNameParser.java 100644 765 24 7304 11623215065 32123 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
/**
* Implementation for layered filesystems.
*
* Additionally encodes the '!' character.
* @author Commons VFS team
*/
public class LayeredFileNameParser extends AbstractFileNameParser
{
private static final LayeredFileNameParser INSTANCE = new LayeredFileNameParser();
/**
* Return the Parser.
* @return The Parser.
*/
public static LayeredFileNameParser getInstance()
{
return INSTANCE;
}
/**
* Determines if a character should be encoded.
* @param ch The character to check.
* @return true if the character should be encoded.
*/
@Override
public boolean encodeCharacter(char ch)
{
return super.encodeCharacter(ch) || ch == '!';
}
/**
* Parse the base and name into a FileName.
* @param context The component context.
* @param base The base FileName.
* @param filename The target file name.
* @return The constructed FileName.
* @throws FileSystemException if an error occurs.
*/
public FileName parseUri(final VfsComponentContext context, FileName base, final String filename)
throws FileSystemException
{
final StringBuilder name = new StringBuilder();
// Extract the scheme
final String scheme = UriParser.extractScheme(filename, name);
// Extract the Layered file URI
final String rootUriName = extractRootName(name);
FileName rootUri = null;
if (rootUriName != null)
{
rootUri = context.parseURI(rootUriName);
}
// Decode and normalise the path
UriParser.canonicalizePath(name, 0, name.length(), this);
UriParser.fixSeparators(name);
FileType fileType = UriParser.normalisePath(name);
final String path = name.toString();
return new LayeredFileName(scheme, rootUri, path, fileType);
}
/**
* Pops the root prefix off a URI, which has had the scheme removed.
*/
protected String extractRootName(final StringBuilder uri)
throws FileSystemException
{
// Looking for ! (staring at the end)
int maxlen = uri.length();
int pos = maxlen - 1;
for (; pos > 0 && uri.charAt(pos) != '!'; pos--)
{
}
if (pos == 0 && uri.charAt(pos) != '!')
{
// not ! found, so take the whole path a root
// e.g. zip:/my/zip/file.zip
pos = maxlen;
}
// Extract the name
String prefix = uri.substring(0, pos);
if (pos < maxlen)
{
uri.delete(0, pos + 1);
}
else
{
uri.setLength(0);
}
return prefix;
}
}
././@LongLink 100644 0 0 150 11623215455 10253 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/DefaultLocalFileProvider.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/DefaultLocalFileProvider.j100644 765 24 10524 11623215064 33251 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import java.io.File;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.LocalFileProvider;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.util.Os;
/**
* A file system provider, which uses direct file access.
*
* @author Commons VFS team
*/
public class DefaultLocalFileProvider
extends AbstractOriginatingFileProvider
implements LocalFileProvider
{
/** The provider's capabilities. */
public static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.CREATE,
Capability.DELETE,
Capability.RENAME,
Capability.GET_TYPE,
Capability.GET_LAST_MODIFIED,
Capability.SET_LAST_MODIFIED_FILE,
Capability.SET_LAST_MODIFIED_FOLDER,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.URI,
Capability.WRITE_CONTENT,
Capability.APPEND_CONTENT,
Capability.RANDOM_ACCESS_READ,
Capability.RANDOM_ACCESS_WRITE
}));
public DefaultLocalFileProvider()
{
super();
if (Os.isFamily(Os.OS_FAMILY_WINDOWS))
{
setFileNameParser(new WindowsFileNameParser());
}
else
{
setFileNameParser(new GenericFileNameParser());
}
}
/**
* Determines if a name is an absolute file name.
* @param name The file name.
* @return true if the name is absolute, false otherwise.
*/
public boolean isAbsoluteLocalName(final String name)
{
return ((LocalFileNameParser) getFileNameParser()).isAbsoluteName(name);
}
/**
* Finds a local file, from its local name.
* @param name The name of the file to locate.
* @return the located FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileObject findLocalFile(final String name)
throws FileSystemException
{
StringBuilder uri = new StringBuilder(name.length() + 5);
uri.append("file:");
uri.append(name);
FileName filename = parseUri(null, uri.toString());
return findFile(filename, null);
}
/**
* Finds a local file.
* @param file The File to locate.
* @return the located FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileObject findLocalFile(final File file)
throws FileSystemException
{
return findLocalFile(UriParser.encode(file.getAbsolutePath()));
// return findLocalFile(file.getAbsolutePath());
}
/**
* Creates the filesystem.
*/
@Override
protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Create the file system
final LocalFileName rootName = (LocalFileName) name;
return new LocalFileSystem(rootName, rootName.getRootFile(), fileSystemOptions);
}
public Collection getCapabilities()
{
return capabilities;
}
}
././@LongLink 100644 0 0 145 11623215455 10257 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/GenericFileNameParser.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/GenericFileNameParser.java100644 765 24 4706 11623215064 33206 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
/**
* A general-purpose file name parser.
*
* @author Commons VFS team
*/
public class GenericFileNameParser
extends LocalFileNameParser
{
private static final GenericFileNameParser INSTANCE = new GenericFileNameParser();
/**
* retrieve a instance to this parser.
*
* @return the parser
*/
public static GenericFileNameParser getInstance()
{
return INSTANCE;
}
/**
* Pops the root prefix off a URI, which has had the scheme removed.
*/
@Override
protected String extractRootPrefix(final String uri,
final StringBuilder name)
throws FileSystemException
{
// TODO - this class isn't generic at all. Need to fix this
// Looking for
if (name.length() == 0 || name.charAt(0) != '/')
{
throw new FileSystemException("vfs.provider.local/not-absolute-file-name.error", uri);
}
// do not strip the separator, BUT also return it ...
return "/";
}
/*
* ... this is why whe need this:
* here the rootFilename can only be "/" (see above) put this "/" is also in the pathname
* so its of no value for the LocalFileName instance
*/
@Override
protected FileName createFileName(String scheme, final String rootFile, final String path, final FileType type)
{
return new LocalFileName(scheme, "", path, type);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFile.java 100644 765 24 15436 11623215064 30730 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.util.FileObjectUtils;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* A file object implementation which uses direct file access.
*
* @author Commons VFS team
*/
public class LocalFile extends AbstractFileObject implements FileObject
{
private final String rootFile;
private File file;
/**
* Creates a non-root file.
*/
protected LocalFile(final LocalFileSystem fileSystem,
final String rootFile,
final AbstractFileName name) throws FileSystemException
{
super(name, fileSystem);
this.rootFile = rootFile;
}
/**
* Returns the local file that this file object represents.
*/
protected File getLocalFile()
{
return file;
}
/**
* Attaches this file object to its file resource.
*/
@Override
protected void doAttach() throws Exception
{
if (file == null)
{
// Remove the "file:///"
// LocalFileName localFileName = (LocalFileName) getName();
String fileName = rootFile + getName().getPathDecoded();
// fileName = UriParser.decode(fileName);
file = new File(fileName);
}
}
/**
* Returns the file's type.
*/
@Override
protected FileType doGetType() throws Exception
{
// JDK BUG: 6192331
// if (!file.exists())
if (!file.exists() && file.length() < 1)
{
return FileType.IMAGINARY;
}
if (file.isDirectory())
{
return FileType.FOLDER;
}
// In doubt, treat an existing file as file
// if (file.isFile())
// {
return FileType.FILE;
// }
// throw new FileSystemException("vfs.provider.local/get-type.error", file);
}
/**
* Returns the children of the file.
*/
@Override
protected String[] doListChildren() throws Exception
{
return UriParser.encode(file.list());
}
/**
* Deletes this file, and all children.
*/
@Override
protected void doDelete() throws Exception
{
if (!file.delete())
{
throw new FileSystemException("vfs.provider.local/delete-file.error", file);
}
}
/**
* rename this file
*/
@Override
protected void doRename(final FileObject newfile) throws Exception
{
LocalFile newLocalFile = (LocalFile) FileObjectUtils.getAbstractFileObject(newfile);
if (!file.renameTo(newLocalFile.getLocalFile()))
{
throw new FileSystemException("vfs.provider.local/rename-file.error",
new String[]{file.toString(), newfile.toString()});
}
}
/**
* Creates this folder.
*/
@Override
protected void doCreateFolder() throws Exception
{
if (!file.mkdirs())
{
throw new FileSystemException("vfs.provider.local/create-folder.error", file);
}
}
/**
* Determines if this file can be written to.
*/
@Override
protected boolean doIsWriteable() throws FileSystemException
{
return file.canWrite();
}
/**
* Determines if this file is hidden.
*/
@Override
protected boolean doIsHidden()
{
return file.isHidden();
}
/**
* Determines if this file can be read.
*/
@Override
protected boolean doIsReadable() throws FileSystemException
{
return file.canRead();
}
/**
* Gets the last modified time of this file.
*/
@Override
protected long doGetLastModifiedTime() throws FileSystemException
{
return file.lastModified();
}
/**
* Sets the last modified time of this file.
* @since 2.0
*/
@Override
protected boolean doSetLastModifiedTime(final long modtime) throws FileSystemException
{
return file.setLastModified(modtime);
}
/**
* Creates an input stream to read the content from.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
return new FileInputStream(file);
}
/**
* Creates an output stream to write the file content to.
*/
@Override
protected OutputStream doGetOutputStream(boolean bAppend)
throws Exception
{
return new FileOutputStream(file.getPath(), bAppend);
}
/**
* Returns the size of the file content (in bytes).
*/
@Override
protected long doGetContentSize() throws Exception
{
return file.length();
}
@Override
protected RandomAccessContent doGetRandomAccessContent(final RandomAccessMode mode) throws Exception
{
return new LocalFileRandomAccessContent(file, mode);
}
@Override
protected boolean doIsSameFile(FileObject destFile) throws FileSystemException
{
if (!FileObjectUtils.isInstanceOf(destFile, LocalFile.class))
{
return false;
}
LocalFile destLocalFile = (LocalFile) FileObjectUtils.getAbstractFileObject(destFile);
if (!exists() || !destLocalFile.exists())
{
return false;
}
try
{
return file.getCanonicalPath().equals(destLocalFile.file.getCanonicalPath());
}
catch (IOException e)
{
throw new FileSystemException(e);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileName.java 100644 765 24 4302 11623215064 31477 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
/**
* A local file URI.
*
* @author Commons VFS team
*/
public class LocalFileName extends AbstractFileName
{
private final String rootFile;
protected LocalFileName(final String scheme,
final String rootFile,
final String path,
final FileType type)
{
super(scheme, path, type);
this.rootFile = rootFile;
}
/**
* Returns the root file for this file.
* @return The root file name.
*/
public String getRootFile()
{
return rootFile;
}
/**
* Factory method for creating name instances.
* @param path The file path.
* @param type The file type.
* @return The FileName.
*/
@Override
public FileName createName(final String path, FileType type)
{
return new LocalFileName(getScheme(), rootFile, path, type);
}
/**
* Builds the root URI for this file name.
*/
@Override
protected void appendRootUri(final StringBuilder buffer, boolean addPassword)
{
buffer.append(getScheme());
buffer.append("://");
buffer.append(rootFile);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileNameParser.java 100644 765 24 6232 11623215064 32660 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileNameParser;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.provider.VfsComponentContext;
/**
* A name parser.
*
* @author Commons VFS team
*/
public abstract class LocalFileNameParser extends AbstractFileNameParser
{
/**
* Determines if a name is an absolute file name.
* @param name The file name.
* @return true if the name is absolute, false otherwise.
*/
public boolean isAbsoluteName(final String name)
{
// TODO - this is yucky
StringBuilder b = new StringBuilder(name);
try
{
UriParser.fixSeparators(b);
extractRootPrefix(name, b);
return true;
}
catch (FileSystemException e)
{
return false;
}
}
/**
* Pops the root prefix off a URI, which has had the scheme removed.
*/
protected abstract String extractRootPrefix(final String uri,
final StringBuilder name)
throws FileSystemException;
public FileName parseUri(final VfsComponentContext context, FileName base, final String filename)
throws FileSystemException
{
final StringBuilder name = new StringBuilder();
// Extract the scheme
String scheme = UriParser.extractScheme(filename, name);
if (scheme == null)
{
scheme = "file";
}
// Remove encoding, and adjust the separators
UriParser.canonicalizePath(name, 0, name.length(), this);
UriParser.fixSeparators(name);
// Extract the root prefix
final String rootFile = extractRootPrefix(filename, name);
// Normalise the path
FileType fileType = UriParser.normalisePath(name);
final String path = name.toString();
return createFileName(
scheme,
rootFile,
path,
fileType);
}
protected abstract FileName createFileName(String scheme, final String rootFile, final String path,
final FileType type);
}
././@LongLink 100644 0 0 154 11623215455 10257 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileRandomAccessContent.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileRandomAccessConte100644 765 24 15176 11623215064 33265 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import java.io.EOFException;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractRandomAccessContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* RandomAccess for local files
*
* @author Commons VFS team
*/
class LocalFileRandomAccessContent extends AbstractRandomAccessContent
{
// private final LocalFile localFile;
private final RandomAccessFile raf;
private final InputStream rafis;
LocalFileRandomAccessContent(final File localFile, final RandomAccessMode mode) throws FileSystemException
{
super(mode);
try
{
raf = new RandomAccessFile(localFile, mode.getModeString());
rafis = new InputStream()
{
@Override
public int read() throws IOException
{
try
{
return raf.readByte();
}
catch (EOFException e)
{
return -1;
}
}
@Override
public long skip(long n) throws IOException
{
raf.seek(raf.getFilePointer() + n);
return n;
}
@Override
public void close() throws IOException
{
raf.close();
}
@Override
public int read(byte[] b) throws IOException
{
return raf.read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
return raf.read(b, off, len);
}
@Override
public int available() throws IOException
{
long available = raf.length() - raf.getFilePointer();
if (available > Integer.MAX_VALUE)
{
return Integer.MAX_VALUE;
}
return (int) available;
}
};
}
catch (FileNotFoundException e)
{
throw new FileSystemException("vfs.provider/random-access-open-failed.error", localFile);
}
}
public long getFilePointer() throws IOException
{
return raf.getFilePointer();
}
public void seek(long pos) throws IOException
{
raf.seek(pos);
}
public long length() throws IOException
{
return raf.length();
}
public void close() throws IOException
{
raf.close();
}
public byte readByte() throws IOException
{
return raf.readByte();
}
public char readChar() throws IOException
{
return raf.readChar();
}
public double readDouble() throws IOException
{
return raf.readDouble();
}
public float readFloat() throws IOException
{
return raf.readFloat();
}
public int readInt() throws IOException
{
return raf.readInt();
}
public int readUnsignedByte() throws IOException
{
return raf.readUnsignedByte();
}
public int readUnsignedShort() throws IOException
{
return raf.readUnsignedShort();
}
public long readLong() throws IOException
{
return raf.readLong();
}
public short readShort() throws IOException
{
return raf.readShort();
}
public boolean readBoolean() throws IOException
{
return raf.readBoolean();
}
public int skipBytes(int n) throws IOException
{
return raf.skipBytes(n);
}
public void readFully(byte[] b) throws IOException
{
raf.readFully(b);
}
public void readFully(byte[] b, int off, int len) throws IOException
{
raf.readFully(b, off, len);
}
public String readUTF() throws IOException
{
return raf.readUTF();
}
@Override
public void writeDouble(double v) throws IOException
{
raf.writeDouble(v);
}
@Override
public void writeFloat(float v) throws IOException
{
raf.writeFloat(v);
}
@Override
public void write(int b) throws IOException
{
raf.write(b);
}
@Override
public void writeByte(int v) throws IOException
{
raf.writeByte(v);
}
@Override
public void writeChar(int v) throws IOException
{
raf.writeChar(v);
}
@Override
public void writeInt(int v) throws IOException
{
raf.writeInt(v);
}
@Override
public void writeShort(int v) throws IOException
{
raf.writeShort(v);
}
@Override
public void writeLong(long v) throws IOException
{
raf.writeLong(v);
}
@Override
public void writeBoolean(boolean v) throws IOException
{
raf.writeBoolean(v);
}
@Override
public void write(byte[] b) throws IOException
{
raf.write(b);
}
@Override
public void write(byte[] b, int off, int len) throws IOException
{
raf.write(b, off, len);
}
@Override
public void writeBytes(String s) throws IOException
{
raf.writeBytes(s);
}
@Override
public void writeChars(String s) throws IOException
{
raf.writeChars(s);
}
@Override
public void writeUTF(String str) throws IOException
{
raf.writeUTF(str);
}
public InputStream getInputStream() throws IOException
{
return rafis;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/LocalFileSystem.java 100644 765 24 5647 11623215064 32120 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import java.io.File;
import java.io.FilePermission;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSelector;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
/**
* A local file system.
*
* @author Commons VFS team
*/
public class LocalFileSystem
extends AbstractFileSystem
implements FileSystem
{
private final String rootFile;
public LocalFileSystem(final FileName rootName,
final String rootFile,
final FileSystemOptions opts)
{
super(rootName, null, opts);
this.rootFile = rootFile;
}
/**
* Creates a file object.
*/
@Override
protected FileObject createFile(final AbstractFileName name) throws FileSystemException
{
// Create the file
return new LocalFile(this, rootFile, name);
}
/**
* Returns the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(DefaultLocalFileProvider.capabilities);
}
/**
* Creates a temporary local copy of a file and its descendents.
*/
@Override
protected File doReplicateFile(final FileObject fileObject,
final FileSelector selector)
throws Exception
{
final LocalFile localFile = (LocalFile) fileObject;
final File file = localFile.getLocalFile();
final SecurityManager sm = System.getSecurityManager();
if (sm != null)
{
final FilePermission requiredPerm = new FilePermission(file.getAbsolutePath(), "read");
sm.checkPermission(requiredPerm);
}
return file;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/package.html 100644 765 24 1542 11623215064 30465 0 ustar rgoers staff 0 0
The Local File Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileName.java 100644 765 24 4147 11623215064 32106 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileType;
/**
* A local file URI.
*
* @author Commons VFS team
*/
public class WindowsFileName extends LocalFileName
{
protected WindowsFileName(final String scheme,
final String rootFile,
final String path,
final FileType type)
{
super(scheme, rootFile, path, type);
}
/**
* Factory method for creating name instances.
* @param path The file path.
* @param type The file type.
* @return The FileName.
*/
@Override
public FileName createName(final String path, FileType type)
{
return new WindowsFileName(getScheme(), getRootFile(), path, type);
}
/**
* Builds the root URI for this file name.
*/
@Override
protected void appendRootUri(final StringBuilder buffer, boolean addPassword)
{
buffer.append(getScheme());
buffer.append("://");
if (getRootFile() != null && !getRootFile().startsWith("/"))
{
// next is drive-letter (else unc name)
buffer.append("/");
}
buffer.append(getRootFile());
}
}
././@LongLink 100644 0 0 145 11623215455 10257 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileNameParser.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/local/WindowsFileNameParser.java100644 765 24 11422 11623215064 33275 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.local;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
/**
* A parser for Windows file names.
*
* @author Commons VFS team
*/
public class WindowsFileNameParser extends LocalFileNameParser
{
/**
* Pops the root prefix off a URI, which has had the scheme removed.
*/
@Override
protected String extractRootPrefix(final String uri,
final StringBuilder name)
throws FileSystemException
{
return extractWindowsRootPrefix(uri, name);
}
@Override
protected FileName createFileName(String scheme, final String rootFile, final String path, final FileType type)
{
return new WindowsFileName(scheme, rootFile, path, type);
}
/**
* Extracts a Windows root prefix from a name.
*/
private String extractWindowsRootPrefix(final String uri,
final StringBuilder name)
throws FileSystemException
{
// Looking for:
// ('/'){0, 3} ':' '/'
// ['/'] '//' '/' ( '/' | )
// Skip over first 4 (unc) leading '/' chars
int startPos = 0;
int maxlen = Math.min(4, name.length());
for (; startPos < maxlen && name.charAt(startPos) == '/'; startPos++)
{
}
if (startPos == maxlen && name.length() > startPos && name.charAt(startPos + 1) == '/')
{
// Too many '/'
throw new FileSystemException("vfs.provider.local/not-absolute-file-name.error", uri);
}
name.delete(0, startPos);
// Look for drive name
String driveName = extractDrivePrefix(name);
if (driveName != null)
{
return driveName;
}
// Look for UNC name
if (startPos < 2)
{
throw new FileSystemException("vfs.provider.local/not-absolute-file-name.error", uri);
}
return "//" + extractUNCPrefix(uri, name);
}
/**
* Extracts a drive prefix from a path. Leading '/' chars have been removed.
*/
private String extractDrivePrefix(final StringBuilder name)
{
// Looking for ':' '/'
if (name.length() < 3)
{
// Too short
return null;
}
char ch = name.charAt(0);
if (ch == '/' || ch == ':')
{
// Missing drive letter
return null;
}
if (name.charAt(1) != ':')
{
// Missing ':'
return null;
}
if (name.charAt(2) != '/')
{
// Missing separator
return null;
}
String prefix = name.substring(0, 2);
name.delete(0, 2);
return prefix.intern();
}
/**
* Extracts a UNC name from a path. Leading '/' chars have been removed.
*/
private String extractUNCPrefix(final String uri,
final StringBuilder name)
throws FileSystemException
{
// Looking for '/' ( '/' | )
// Look for first separator
int maxpos = name.length();
int pos = 0;
for (; pos < maxpos && name.charAt(pos) != '/'; pos++)
{
}
pos++;
if (pos >= maxpos)
{
throw new FileSystemException("vfs.provider.local/missing-share-name.error", uri);
}
// Now have '/'
int startShareName = pos;
for (; pos < maxpos && name.charAt(pos) != '/'; pos++)
{
}
if (pos == startShareName)
{
throw new FileSystemException("vfs.provider.local/missing-share-name.error", uri);
}
// Now have '/' ( '/' | )
String prefix = name.substring(0, pos);
name.delete(0, pos);
return prefix;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/LocalFileProvider.java 100644 765 24 3772 11623215065 31332 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.File;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
/**
* A file provider which handles local files.
*
* @author Commons VFS team
*/
public interface LocalFileProvider
extends FileProvider
{
/**
* Determines if a name is an absolute file name.
*
* @param name The name to test.
* @todo Move this to a general file name parser interface.
* @return true if the name is absolute.
*/
boolean isAbsoluteLocalName(final String name);
/**
* Finds a local file, from its local name.
* @param name The name of the file to locate.
* @return The FileObject for the file.
* @throws FileSystemException if an error occurs.
*
*/
FileObject findLocalFile(final String name)
throws FileSystemException;
/**
* Converts from java.io.File to FileObject.
* @param file The File for the file.
* @return The FileObject for the file.
* @throws FileSystemException if an error occurs.
*/
FileObject findLocalFile(final File file)
throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/package.html 100644 765 24 1565 11623215065 27401 0 ustar rgoers staff 0 0
The File Provider API, and utility classes.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/package.html 100644 765 24 1540 11623215064 30150 0 ustar rgoers staff 0 0
The RAM File Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileData.java 100644 765 24 14141 11623215064 30664 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
/**
* RAM File Object Data.
* @author Commons VFS team
*/
class RamFileData implements Serializable
{
/**
* serialVersionUID format is YYYYMMDD for the date of the last binary change.
*/
private static final long serialVersionUID = 20101208L;
/**
* File Name.
*/
private FileName name;
/**
* File Type.
*/
private FileType type;
/**
* Bytes.
*/
private byte[] buffer;
/**
* Last modified time
*/
private long lastModified;
/**
* Children
*/
private final Collection children;
/**
* Constructor.
* @param name The file name.
*/
public RamFileData(FileName name)
{
super();
this.children = Collections.synchronizedCollection(new ArrayList());
this.clear();
if (name == null)
{
throw new IllegalArgumentException("name can not be null");
}
this.name = name;
}
/**
* @return Returns the buffer.
*/
byte[] getBuffer()
{
return buffer;
}
/**
* @param buffer The buffer.
*/
void setBuffer(byte[] buffer)
{
updateLastModified();
this.buffer = buffer;
}
/**
* @return Returns the lastModified.
*/
long getLastModified()
{
return lastModified;
}
/**
* @param lastModified
* The lastModified to set.
*/
void setLastModified(long lastModified)
{
this.lastModified = lastModified;
}
/**
* @return Returns the type.
*/
FileType getType()
{
return type;
}
/**
* @param type
* The type to set.
*/
void setType(FileType type)
{
this.type = type;
}
/**
*
*/
void clear()
{
this.buffer = new byte[0];
updateLastModified();
this.type = FileType.IMAGINARY;
this.children.clear();
this.name = null;
}
void updateLastModified()
{
this.lastModified = System.currentTimeMillis();
}
/**
* @return Returns the name.
*/
FileName getName()
{
return name;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return this.name.toString();
}
/**
* Add a child.
*
* @param data The file data.
* @throws FileSystemException if an error occurs.
*/
void addChild(RamFileData data) throws FileSystemException
{
if (!this.getType().hasChildren())
{
throw new FileSystemException(
"A child can only be added in a folder");
}
if (data == null)
{
throw new FileSystemException("No child can be null");
}
if (this.children.contains(data))
{
throw new FileSystemException("Child already exists. " + data);
}
this.children.add(data);
updateLastModified();
}
/**
* Remove a child.
*
* @param data The file data.
* @throws FileSystemException if an error occurs.
*/
void removeChild(RamFileData data) throws FileSystemException
{
if (!this.getType().hasChildren())
{
throw new FileSystemException(
"A child can only be removed from a folder");
}
if (!this.children.contains(data))
{
throw new FileSystemException("Child not found. " + data);
}
this.children.remove(data);
updateLastModified();
}
/**
* @return Returns the children.
*/
Collection getChildren()
{
if (name == null)
{
throw new IllegalStateException("Data is clear");
}
return children;
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (!(o instanceof RamFileData))
{
return false;
}
RamFileData data = (RamFileData) o;
return this.getName().equals(data.getName());
}
/*
* (non-Javadoc)
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
return this.getName().hashCode();
}
boolean hasChildren(RamFileData data)
{
return this.children.contains(data);
}
/**
* @return Returns the size of the buffer
*/
int size()
{
return buffer.length;
}
/**
* Resize the buffer
*
* @param newSize The new buffer size.
*/
void resize(int newSize)
{
int size = this.size();
byte[] newBuf = new byte[newSize];
System.arraycopy(this.buffer, 0, newBuf, 0, size);
this.buffer = newBuf;
updateLastModified();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileObject.java 100644 765 24 16313 11623215064 31224 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* A RAM File contains a single RAM FileData instance, it provides methods to
* access the data by implementing FileObject interface.
* @author Commons VFS team
*/
public class RamFileObject extends AbstractFileObject implements FileObject
{
/**
* File System.
*/
private final RamFileSystem fs;
/**
* RAM File Object Data.
*/
private RamFileData data;
/**
* @param name The name of the file.
* @param fs The FileSystem.
*/
protected RamFileObject(AbstractFileName name, RamFileSystem fs)
{
super(name, fs);
this.fs = fs;
this.fs.attach(this);
}
private void save() throws FileSystemException
{
this.fs.save(this);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetType()
*/
@Override
protected FileType doGetType() throws Exception
{
return data.getType();
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doListChildren()
*/
@Override
protected String[] doListChildren() throws Exception
{
return this.fs.listChildren(this.getName());
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetContentSize()
*/
@Override
protected long doGetContentSize() throws Exception
{
return this.data.getBuffer().length;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetInputStream()
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
// VFS-210: ram allows to gather an input stream even from a directory. So we need to check the type anyway.
if (!getType().hasContent())
{
throw new FileSystemException("vfs.provider/read-not-file.error", getName());
}
return new ByteArrayInputStream(this.data.getBuffer());
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetOutputStream(boolean)
*/
@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
if (!bAppend)
{
this.data.setBuffer(new byte[0]);
}
return new RamFileOutputStream(this);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doDelete()
*/
@Override
protected void doDelete() throws Exception
{
fs.delete(this);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetLastModifiedTime()
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
return data.getLastModified();
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doSetLastModifiedTime(long)
*/
/** @since 2.0 */
@Override
protected boolean doSetLastModifiedTime(long modtime) throws Exception
{
data.setLastModified(modtime);
return true;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doCreateFolder()
*/
@Override
protected void doCreateFolder() throws Exception
{
this.injectType(FileType.FOLDER);
this.save();
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doRename(org.apache.commons.vfs2.FileObject)
*/
@Override
protected void doRename(FileObject newfile) throws Exception
{
fs.rename(this, (RamFileObject) newfile);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doGetRandomAccessContent(
* org.apache.commons.vfs2.util.RandomAccessMode)
*/
@Override
protected RandomAccessContent doGetRandomAccessContent(RandomAccessMode mode)
throws Exception
{
return new RamFileRandomAccessContent(this, mode);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#doAttach()
*/
@Override
protected void doAttach() throws Exception
{
this.fs.attach(this);
}
/**
* @return Returns the data.
*/
RamFileData getData()
{
return data;
}
/**
* @param data
* The data to set.
*/
void setData(RamFileData data)
{
this.data = data;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#injectType(org.apache.commons.vfs2.FileType)
*/
@Override
protected void injectType(FileType fileType)
{
this.data.setType(fileType);
super.injectType(fileType);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileObject#endOutput()
*/
@Override
protected void endOutput() throws Exception
{
super.endOutput();
this.save();
}
/**
* @return Returns the size of the RAMFileData
*/
int size()
{
if (data == null)
{
return 0;
}
return data.size();
}
/**
* @param newSize
* @throws IOException
* if the new size exceeds the limit
*/
synchronized void resize(int newSize) throws IOException
{
if (fs.getFileSystemOptions() != null)
{
int maxSize = RamFileSystemConfigBuilder.getInstance().getMaxSize(
fs.getFileSystemOptions());
if (fs.size() + newSize - this.size() > maxSize)
{
throw new IOException("FileSystem capacity (" + maxSize
+ ") exceeded.");
}
}
this.data.resize(newSize);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileOutputStream.java 100644 765 24 5577 11623215064 32464 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.commons.vfs2.FileSystemException;
/**
* OutputStream to a RamFile.
* @author Commons VFS team
*/
public class RamFileOutputStream extends OutputStream
{
/**
* File.
*/
protected RamFileObject file;
/**
* buffer.
*/
protected byte[] buffer1 = new byte[1];
/** File is open or closed */
protected boolean closed = false;
private IOException exc;
/**
* @param file The base file.
*/
public RamFileOutputStream(RamFileObject file)
{
super();
this.file = file;
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(byte[], int, int)
*/
@Override
public void write(byte[] b, int off, int len) throws IOException
{
int size = this.file.getData().size();
int newSize = this.file.getData().size() + len;
// Store the Exception in order to notify the client again on close()
try
{
this.file.resize(newSize);
}
catch (IOException e)
{
this.exc = e;
throw e;
}
System.arraycopy(b, off, this.file.getData().getBuffer(), size, len);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(int)
*/
@Override
public void write(int b) throws IOException
{
buffer1[0] = (byte) b;
this.write(buffer1);
}
@Override
public void flush() throws IOException
{
}
@Override
public void close() throws IOException
{
if (closed)
{
return;
}
// Notify on close that there was an IOException while writing
if (exc != null)
{
throw exc;
}
try
{
this.closed = true;
// Close the
this.file.endOutput();
}
catch (Exception e)
{
throw new FileSystemException(e);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileProvider.java 100644 765 24 5654 11623215064 31576 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.FileProvider;
/**
* RAM File Provider.
* @author Commons VFS team
*
*/
public class RamFileProvider extends AbstractOriginatingFileProvider implements
FileProvider
{
/** The provider's capabilities. */
public static final Collection capabilities = Collections
.unmodifiableCollection(Arrays.asList(new Capability[]
{Capability.CREATE, Capability.DELETE, Capability.RENAME,
Capability.GET_TYPE, Capability.GET_LAST_MODIFIED,
Capability.SET_LAST_MODIFIED_FILE,
Capability.SET_LAST_MODIFIED_FOLDER,
Capability.LIST_CHILDREN, Capability.READ_CONTENT,
Capability.URI, Capability.WRITE_CONTENT,
Capability.APPEND_CONTENT, Capability.RANDOM_ACCESS_READ,
Capability.RANDOM_ACCESS_WRITE
}));
/**
* Constructor.
*/
public RamFileProvider()
{
super();
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider#doCreateFileSystem(
* org.apache.commons.vfs2.FileName, org.apache.commons.vfs2.FileSystemOptions)
*/
@Override
protected FileSystem doCreateFileSystem(FileName name,
FileSystemOptions fileSystemOptions) throws FileSystemException
{
return new RamFileSystem(name, fileSystemOptions);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.FileProvider#getCapabilities()
*/
public Collection getCapabilities()
{
return capabilities;
}
}
././@LongLink 100644 0 0 150 11623215455 10253 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileRandomAccessContent.j100644 765 24 33142 11623215064 33222 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* RAM File Random Access Content.
* @author Commons VFS team
*/
public class RamFileRandomAccessContent implements RandomAccessContent
{
/**
* File Pointer
*/
protected int filePointer = 0;
/**
* Buffer
*/
private byte[] buf;
/**
* buffer
*/
private final byte[] buffer8 = new byte[8];
/**
* buffer
*/
private final byte[] buffer4 = new byte[4];
/**
* buffer
*/
private final byte[] buffer2 = new byte[2];
/**
* buffer
*/
private final byte[] buffer1 = new byte[1];
/**
* Mode
*/
private final RandomAccessMode mode;
/**
* File
*/
private final RamFileObject file;
private final InputStream rafis;
/**
* @param file The file to access.
* @param mode The access mode.
*/
public RamFileRandomAccessContent(RamFileObject file, RandomAccessMode mode)
{
super();
this.buf = file.getData().getBuffer();
this.file = file;
this.mode = mode;
rafis = new InputStream()
{
@Override
public int read() throws IOException
{
try
{
return readByte();
}
catch (EOFException e)
{
return -1;
}
}
@Override
public long skip(long n) throws IOException
{
seek(getFilePointer() + n);
return n;
}
@Override
public void close() throws IOException
{
}
@Override
public int read(byte[] b) throws IOException
{
return read(b, 0, b.length);
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
int retLen = Math.min(len, getLeftBytes());
RamFileRandomAccessContent.this.readFully(b, off, retLen);
return retLen;
}
@Override
public int available() throws IOException
{
return getLeftBytes();
}
};
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#getFilePointer()
*/
public long getFilePointer() throws IOException
{
return this.filePointer;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#seek(long)
*/
public void seek(long pos) throws IOException
{
this.filePointer = (int) pos;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#length()
*/
public long length() throws IOException
{
return buf.length;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.RandomAccessContent#close()
*/
public void close() throws IOException
{
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readByte()
*/
public byte readByte() throws IOException
{
return (byte) this.readUnsignedByte();
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readChar()
*/
public char readChar() throws IOException
{
int ch1 = this.readUnsignedByte();
int ch2 = this.readUnsignedByte();
return (char) ((ch1 << 8) + (ch2 << 0));
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readDouble()
*/
public double readDouble() throws IOException
{
return Double.longBitsToDouble(this.readLong());
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readFloat()
*/
public float readFloat() throws IOException
{
return Float.intBitsToFloat(this.readInt());
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readInt()
*/
public int readInt() throws IOException
{
return (readUnsignedByte() << 24) | (readUnsignedByte() << 16)
| (readUnsignedByte() << 8) | readUnsignedByte();
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readUnsignedByte()
*/
public int readUnsignedByte() throws IOException
{
if (filePointer < buf.length)
{
return buf[filePointer++] & 0xFF;
}
else
{
throw new EOFException();
}
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readUnsignedShort()
*/
public int readUnsignedShort() throws IOException
{
this.readFully(buffer2);
return toUnsignedShort(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readLong()
*/
public long readLong() throws IOException
{
this.readFully(buffer8);
return toLong(buffer8);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readShort()
*/
public short readShort() throws IOException
{
this.readFully(buffer2);
return toShort(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readBoolean()
*/
public boolean readBoolean() throws IOException
{
return (this.readUnsignedByte() != 0);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#skipBytes(int)
*/
public int skipBytes(int n) throws IOException
{
if (n < 0)
{
throw new IndexOutOfBoundsException(
"The skip number can't be negative");
}
long newPos = filePointer + n;
if (newPos > buf.length)
{
throw new IndexOutOfBoundsException("Tyring to skip too much bytes");
}
seek(newPos);
return n;
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readFully(byte[])
*/
public void readFully(byte[] b) throws IOException
{
this.readFully(b, 0, b.length);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readFully(byte[], int, int)
*/
public void readFully(byte[] b, int off, int len) throws IOException
{
if (len < 0)
{
throw new IndexOutOfBoundsException("Length is lower than 0");
}
if (len > this.getLeftBytes())
{
throw new IndexOutOfBoundsException("Read length (" + len
+ ") is higher than buffer left bytes ("
+ this.getLeftBytes() + ") ");
}
System.arraycopy(buf, filePointer, b, off, len);
filePointer += len;
}
private int getLeftBytes()
{
return buf.length - filePointer;
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readUTF()
*/
public String readUTF() throws IOException
{
return DataInputStream.readUTF(this);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(byte[], int, int)
*/
public void write(byte[] b, int off, int len) throws IOException
{
if (this.getLeftBytes() < len)
{
int newSize = this.buf.length + len - this.getLeftBytes();
this.file.resize(newSize);
this.buf = this.file.getData().getBuffer();
}
System.arraycopy(b, off, this.buf, filePointer, len);
this.filePointer += len;
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(byte[])
*/
public void write(byte[] b) throws IOException
{
this.write(b, 0, b.length);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeByte(int)
*/
public void writeByte(int i) throws IOException
{
this.write(i);
}
/**
* Build a long from first 8 bytes of the array.
*
* @param b The byte[] to convert.
* @return A long.
*/
public static long toLong(byte[] b)
{
return ((((long) b[7]) & 0xFF) + ((((long) b[6]) & 0xFF) << 8)
+ ((((long) b[5]) & 0xFF) << 16)
+ ((((long) b[4]) & 0xFF) << 24)
+ ((((long) b[3]) & 0xFF) << 32)
+ ((((long) b[2]) & 0xFF) << 40)
+ ((((long) b[1]) & 0xFF) << 48) + ((((long) b[0]) & 0xFF) << 56));
}
/**
* Build a 8-byte array from a long. No check is performed on the array
* length.
*
* @param n The number to convert.
* @param b The array to fill.
* @return A byte[].
*/
public static byte[] toBytes(long n, byte[] b)
{
b[7] = (byte) (n);
n >>>= 8;
b[6] = (byte) (n);
n >>>= 8;
b[5] = (byte) (n);
n >>>= 8;
b[4] = (byte) (n);
n >>>= 8;
b[3] = (byte) (n);
n >>>= 8;
b[2] = (byte) (n);
n >>>= 8;
b[1] = (byte) (n);
n >>>= 8;
b[0] = (byte) (n);
return b;
}
/**
* Build a short from first 2 bytes of the array.
* @param b The byte[] to convert.
* @return A short.
*/
public static short toShort(byte[] b)
{
return (short) toUnsignedShort(b);
}
/**
* Build a short from first 2 bytes of the array.
*
* @param b The byte[] to convert.
* @return A short.
*/
public static int toUnsignedShort(byte[] b)
{
return ((b[1] & 0xFF) + ((b[0] & 0xFF) << 8));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#write(int)
*/
public void write(int b) throws IOException
{
buffer1[0] = (byte) b;
this.write(buffer1);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeBoolean(boolean)
*/
public void writeBoolean(boolean v) throws IOException
{
this.write(v ? 1 : 0);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeBytes(java.lang.String)
*/
public void writeBytes(String s) throws IOException
{
write(s.getBytes());
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeChar(int)
*/
public void writeChar(int v) throws IOException
{
buffer2[0] = (byte) ((v >>> 8) & 0xFF);
buffer2[1] = (byte) ((v >>> 0) & 0xFF);
write(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeChars(java.lang.String)
*/
public void writeChars(String s) throws IOException
{
int len = s.length();
for (int i = 0; i < len; i++)
{
writeChar(s.charAt(i));
}
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeDouble(double)
*/
public void writeDouble(double v) throws IOException
{
writeLong(Double.doubleToLongBits(v));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeFloat(float)
*/
public void writeFloat(float v) throws IOException
{
writeInt(Float.floatToIntBits(v));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeInt(int)
*/
public void writeInt(int v) throws IOException
{
buffer4[0] = (byte) ((v >>> 24) & 0xFF);
buffer4[1] = (byte) ((v >>> 16) & 0xFF);
buffer4[2] = (byte) ((v >>> 8) & 0xFF);
buffer4[3] = (byte) (v & 0xFF);
write(buffer4);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeLong(long)
*/
public void writeLong(long v) throws IOException
{
write(toBytes(v, buffer8));
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeShort(int)
*/
public void writeShort(int v) throws IOException
{
buffer2[0] = (byte) ((v >>> 8) & 0xFF);
buffer2[1] = (byte) (v & 0xFF);
write(buffer2);
}
/*
* (non-Javadoc)
*
* @see java.io.DataOutput#writeUTF(java.lang.String)
*/
public void writeUTF(String str) throws IOException
{
ByteArrayOutputStream out = new ByteArrayOutputStream(str.length());
DataOutputStream dataOut = new DataOutputStream(out);
dataOut.writeUTF(str);
dataOut.flush();
dataOut.close();
byte[] b = out.toByteArray();
write(b);
}
/*
* (non-Javadoc)
*
* @see java.io.DataInput#readLine()
*/
public String readLine() throws IOException
{
throw new UnsupportedOperationException("deprecated");
}
public InputStream getInputStream() throws IOException
{
return rafis;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystem.java 100644 765 24 22726 11623215064 31307 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.Serializable;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
/**
* A RAM File System.
* @author Commons VFS team
*/
public class RamFileSystem extends AbstractFileSystem implements Serializable
{
/**
* serialVersionUID format is YYYYMMDD for the date of the last binary change.
*/
private static final long serialVersionUID = 20101208L;
/**
* Cache of RAM File Data
*/
private final Map cache;
/**
* @param rootName The root file name.
* @param fileSystemOptions The FileSystem options.
*/
protected RamFileSystem(FileName rootName, FileSystemOptions fileSystemOptions)
{
super(rootName, null, fileSystemOptions);
this.cache = Collections.synchronizedMap(new HashMap());
// create root
RamFileData rootData = new RamFileData(rootName);
rootData.setType(FileType.FOLDER);
rootData.setLastModified(System.currentTimeMillis());
this.cache.put(rootName, rootData);
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileSystem#createFile(org.apache.commons.vfs2.FileName)
*/
@Override
protected FileObject createFile(AbstractFileName name) throws Exception
{
RamFileObject file = new RamFileObject(name, this);
return file;
}
/*
* (non-Javadoc)
*
* @see org.apache.commons.vfs2.provider.AbstractFileSystem#addCapabilities(java.util.Collection)
*/
@Override
protected void addCapabilities(Collection caps)
{
caps.addAll(RamFileProvider.capabilities);
}
/**
* @param name The name of the file.
* @return children The names of the children.
*/
String[] listChildren(FileName name)
{
RamFileData data = this.cache.get(name);
if (data == null || !data.getType().hasChildren())
{
return null;
}
Collection children = data.getChildren();
String[] names;
synchronized (children)
{
names = new String[children.size()];
int pos = 0;
Iterator iter = children.iterator();
while (iter.hasNext())
{
RamFileData childData = iter.next();
names[pos] = childData.getName().getBaseName();
pos++;
}
}
return names;
}
/**
* Delete a file
*
* @param file
* @throws FileSystemException
*/
void delete(RamFileObject file) throws FileSystemException
{
// root is read only check
if (file.getParent() == null)
{
throw new FileSystemException("unable to delete root");
}
// Remove reference from cache
this.cache.remove(file.getName());
// Notify the parent
RamFileObject parent = (RamFileObject) this.resolveFile(file
.getParent().getName());
parent.getData().removeChild(file.getData());
parent.close();
// Close the file
file.getData().clear();
file.close();
}
/**
* Saves a file
*
* @param file
* @throws FileSystemException
*/
void save(final RamFileObject file) throws FileSystemException
{
// Validate name
if (file.getData().getName() == null)
{
throw new FileSystemException(new IllegalStateException(
"The data has no name. " + file));
}
// Add to the parent
if (file.getName().getDepth() > 0)
{
RamFileData parentData = this.cache.get(file.getParent().getName());
// Only if not already added
if (!parentData.hasChildren(file.getData()))
{
RamFileObject parent = (RamFileObject) file.getParent();
parent.getData().addChild(file.getData());
parent.close();
}
}
// Store in cache
cache.put(file.getName(), file.getData());
file.getData().updateLastModified();
file.close();
}
/**
* @param from The original file.
* @param to The new file.
* @throws FileSystemException if an error occurs.
*/
void rename(RamFileObject from, RamFileObject to)
throws FileSystemException
{
if (!this.cache.containsKey(from.getName()))
{
throw new FileSystemException("File does not exist: "
+ from.getName());
}
// Copy data
to.getData().setBuffer(from.getData().getBuffer());
to.getData().setLastModified(from.getData().getLastModified());
to.getData().setType(from.getData().getType());
this.save(to);
this.delete(from);
}
public void attach(RamFileObject fo)
{
if (fo.getName() == null)
{
throw new IllegalArgumentException("Null argument");
}
RamFileData data = this.cache.get(fo.getName());
if (data == null)
{
data = new RamFileData(fo.getName());
}
fo.setData(data);
}
/**
* Import a Tree.
*
* @param file The File
* @throws FileSystemException if an error occurs.
*/
public void importTree(File file) throws FileSystemException
{
FileObject fileFo = getFileSystemManager().toFileObject(file);
this.toRamFileObject(fileFo, fileFo);
}
/**
* Import the given file with the name relative to the given root
*
* @param fo
* @param root
* @throws FileSystemException
*/
void toRamFileObject(FileObject fo, FileObject root)
throws FileSystemException
{
RamFileObject memFo = (RamFileObject) this.resolveFile(fo.getName()
.getPath().substring(root.getName().getPath().length()));
if (fo.getType().hasChildren())
{
// Create Folder
memFo.createFolder();
// Import recursively
FileObject[] fos = fo.getChildren();
for (int i = 0; i < fos.length; i++)
{
FileObject child = fos[i];
this.toRamFileObject(child, root);
}
}
else if (fo.getType().equals(FileType.FILE))
{
// Read bytes
try
{
InputStream is = fo.getContent().getInputStream();
try
{
OutputStream os = new BufferedOutputStream(memFo
.getOutputStream(), 512);
int i;
while ((i = is.read()) != -1)
{
os.write(i);
}
os.flush();
os.close();
}
finally
{
try
{
is.close();
}
catch (IOException e)
{
// ignore on close exception
}
}
}
catch (IOException e)
{
throw new FileSystemException(e.getClass().getName() + " "
+ e.getMessage());
}
}
else
{
throw new FileSystemException("File is not a folder nor a file "
+ memFo);
}
}
/**
* @return Returns the size of the FileSystem
*/
int size()
{
int size = 0;
synchronized (cache)
{
Iterator iter = cache.values().iterator();
while (iter.hasNext())
{
RamFileData data = iter.next();
size += data.size();
}
}
return size;
}
/**
* Close the RAMFileSystem.
*/
@Override
public void close()
{
this.cache.clear();
super.close();
}
}
././@LongLink 100644 0 0 150 11623215455 10253 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystemConfigBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/ram/RamFileSystemConfigBuilder.j100644 765 24 4603 11623215064 33226 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.ram;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* Config Builder for the RAM filesystem.
* @author Commons VFS team
*/
public final class RamFileSystemConfigBuilder extends FileSystemConfigBuilder
{
/** max size key. */
private static final String MAX_SIZE_KEY = "maxsize";
/** config builder SINGLETON. */
private static final RamFileSystemConfigBuilder SINGLETON = new RamFileSystemConfigBuilder();
/**
* Constructor
*/
private RamFileSystemConfigBuilder()
{
super("ram.");
}
/**
* @return the config builder SINGLETON
*/
public static RamFileSystemConfigBuilder getInstance()
{
return SINGLETON;
}
/**
* {@inheritDoc}
*/
@Override
protected Class extends FileSystem> getConfigClass()
{
return RamFileSystem.class;
}
/**
* @param opts The FileSystem options.
* @return The maximum size of the file.
* @see #setMaxSize
*/
public int getMaxSize(FileSystemOptions opts)
{
return getInteger(opts, MAX_SIZE_KEY, Integer.MAX_VALUE);
}
/**
* Sets the maximum size of the file system.
*
* @param opts The FileSystem options.
* @param sizeInBytes The maximum file size.
*/
public void setMaxSize(FileSystemOptions opts, int sizeInBytes)
{
setParam(opts, MAX_SIZE_KEY, new Integer(sizeInBytes));
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/res/package.html 100644 765 24 1536 11623215065 30170 0 ustar rgoers staff 0 0
The Resource File Provider
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileProvider.java 100644 765 24 6524 11623215065 32656 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.res;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileProvider;
import org.apache.commons.vfs2.provider.UriParser;
/**
* The Resource provider.
*
* @author Commons VFS team
*/
public class ResourceFileProvider extends AbstractFileProvider
{
/** The provider's capabilities */
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.DISPATCHER
}));
public ResourceFileProvider()
{
super();
}
/**
* Locates a file object, by absolute URI.
* @param baseFile The base file.
* @param uri The URI of the file to locate.
* @param fileSystemOptions The FileSystem options.
* @return the FileObject.
* @throws FileSystemException if an error occurs.
*/
public FileObject findFile(final FileObject baseFile,
final String uri,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
StringBuilder buf = new StringBuilder(80);
UriParser.extractScheme(uri, buf);
String resourceName = buf.toString();
ClassLoader cl = ResourceFileSystemConfigBuilder.getInstance().getClassLoader(fileSystemOptions);
if (cl == null)
{
cl = getClass().getClassLoader();
}
final URL url = cl.getResource(resourceName);
if (url == null)
{
throw new FileSystemException("vfs.provider.url/badly-formed-uri.error", uri);
}
FileObject fo = getContext().getFileSystemManager().resolveFile(url.toExternalForm());
return fo;
}
@Override
public FileSystemConfigBuilder getConfigBuilder()
{
return org.apache.commons.vfs2.provider.res.ResourceFileSystemConfigBuilder.getInstance();
}
@Override
public void closeFileSystem(FileSystem filesystem)
{
// no filesystem created here - so nothing to do
}
public Collection getCapabilities()
{
return capabilities;
}
}
././@LongLink 100644 0 0 155 11623215455 10260 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileSystemConfigBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/res/ResourceFileSystemConfigBuil100644 765 24 3756 11623215065 33376 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.res;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.url.UrlFileSystem;
/**
* The config BUILDER for various ftp configuration options.
*
* @author Commons VFS team
*/
public final class ResourceFileSystemConfigBuilder extends FileSystemConfigBuilder
{
private static final ResourceFileSystemConfigBuilder BUILDER = new ResourceFileSystemConfigBuilder();
private ResourceFileSystemConfigBuilder()
{
super("resource.");
}
public static ResourceFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
public void setClassLoader(FileSystemOptions opts, ClassLoader classLoader)
{
setParam(opts, ClassLoader.class.getName(), classLoader);
}
public ClassLoader getClassLoader(FileSystemOptions opts)
{
return (ClassLoader) getParam(opts, ClassLoader.class.getName());
}
@Override
protected Class extends FileSystem> getConfigClass()
{
return UrlFileSystem.class;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/package.html 100644 765 24 1534 11623215064 30350 0 ustar rgoers staff 0 0
The SFTP Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpClientFactory.java 100644 765 24 23323 11623215064 32355 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import java.io.File;
import java.util.Properties;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.util.Os;
import com.jcraft.jsch.JSch;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Proxy;
import com.jcraft.jsch.ProxyHTTP;
import com.jcraft.jsch.ProxySOCKS5;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.UserInfo;
/**
* Create a JSch Session instance.
*
* @author Commons VFS team
*/
public final class SftpClientFactory
{
private static final String SSH_DIR_NAME = ".ssh";
private SftpClientFactory()
{
}
/**
* Creates a new connection to the server.
* @param hostname The name of the host to connect to.
* @param port The port to use.
* @param username The user's id.
* @param password The user's password.
* @param fileSystemOptions The FileSystem options.
* @return A Session.
* @throws FileSystemException if an error occurs.
*/
public static Session createConnection(String hostname, int port, char[] username, char[] password,
FileSystemOptions fileSystemOptions) throws FileSystemException
{
JSch jsch = new JSch();
File sshDir = null;
// new style - user passed
File knownHostsFile = SftpFileSystemConfigBuilder.getInstance().getKnownHosts(fileSystemOptions);
File[] identities = SftpFileSystemConfigBuilder.getInstance().getIdentities(fileSystemOptions);
if (knownHostsFile != null)
{
try
{
jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
}
catch (JSchException e)
{
throw new FileSystemException("vfs.provider.sftp/known-hosts.error",
knownHostsFile.getAbsolutePath(), e);
}
}
else
{
sshDir = findSshDir();
// Load the known hosts file
knownHostsFile = new File(sshDir, "known_hosts");
if (knownHostsFile.isFile() && knownHostsFile.canRead())
{
try
{
jsch.setKnownHosts(knownHostsFile.getAbsolutePath());
}
catch (JSchException e)
{
throw new FileSystemException("vfs.provider.sftp/known-hosts.error",
knownHostsFile.getAbsolutePath(), e);
}
}
}
if (identities != null)
{
for (int iterIdentities = 0; iterIdentities < identities.length; iterIdentities++)
{
final File privateKeyFile = identities[iterIdentities];
try
{
jsch.addIdentity(privateKeyFile.getAbsolutePath());
}
catch (final JSchException e)
{
throw new FileSystemException("vfs.provider.sftp/load-private-key.error", privateKeyFile, e);
}
}
}
else
{
if (sshDir == null)
{
sshDir = findSshDir();
}
// Load the private key (rsa-key only)
final File privateKeyFile = new File(sshDir, "id_rsa");
if (privateKeyFile.isFile() && privateKeyFile.canRead())
{
try
{
jsch.addIdentity(privateKeyFile.getAbsolutePath());
}
catch (final JSchException e)
{
throw new FileSystemException("vfs.provider.sftp/load-private-key.error", privateKeyFile, e);
}
}
}
Session session;
try
{
session = jsch.getSession(new String(username),
hostname,
port);
if (password != null)
{
session.setPassword(new String(password));
}
Integer timeout = SftpFileSystemConfigBuilder.getInstance().getTimeout(fileSystemOptions);
if (timeout != null)
{
session.setTimeout(timeout.intValue());
}
UserInfo userInfo = SftpFileSystemConfigBuilder.getInstance().getUserInfo(fileSystemOptions);
if (userInfo != null)
{
session.setUserInfo(userInfo);
}
Properties config = new Properties();
//set StrictHostKeyChecking property
String strictHostKeyChecking =
SftpFileSystemConfigBuilder.getInstance().getStrictHostKeyChecking(fileSystemOptions);
if (strictHostKeyChecking != null)
{
config.setProperty("StrictHostKeyChecking", strictHostKeyChecking);
}
//set PreferredAuthentications property
String preferredAuthentications = SftpFileSystemConfigBuilder.getInstance().
getPreferredAuthentications(fileSystemOptions);
if (preferredAuthentications != null)
{
config.setProperty("PreferredAuthentications", preferredAuthentications);
}
//set compression property
String compression = SftpFileSystemConfigBuilder.getInstance().getCompression(fileSystemOptions);
if (compression != null)
{
config.setProperty("compression.s2c", compression);
config.setProperty("compression.c2s", compression);
}
String proxyHost = SftpFileSystemConfigBuilder.getInstance().getProxyHost(fileSystemOptions);
if (proxyHost != null)
{
int proxyPort = SftpFileSystemConfigBuilder.getInstance().getProxyPort(fileSystemOptions);
SftpFileSystemConfigBuilder.ProxyType proxyType =
SftpFileSystemConfigBuilder.getInstance().getProxyType(fileSystemOptions);
Proxy proxy = null;
if (SftpFileSystemConfigBuilder.PROXY_HTTP.equals(proxyType))
{
if (proxyPort != 0)
{
proxy = new ProxyHTTP(proxyHost, proxyPort);
}
else
{
proxy = new ProxyHTTP(proxyHost);
}
}
else if (SftpFileSystemConfigBuilder.PROXY_SOCKS5.equals(proxyType))
{
if (proxyPort != 0)
{
proxy = new ProxySOCKS5(proxyHost, proxyPort);
}
else
{
proxy = new ProxySOCKS5(proxyHost);
}
}
if (proxy != null)
{
session.setProxy(proxy);
}
}
//set properties for the session
if (config.size() > 0)
{
session.setConfig(config);
}
session.setDaemonThread(true);
session.connect();
}
catch (final Exception exc)
{
throw new FileSystemException("vfs.provider.sftp/connect.error", new Object[]{hostname}, exc);
}
return session;
}
/**
* Finds the .ssh directory.
* The lookup order is:
*
* The system property vfs.sftp.sshdir
(the override
* mechanism)
* {user.home}/.ssh
* On Windows only: C:\cygwin\home\{user.name}\.ssh
* The current directory, as a last resort.
*
*
* Windows Notes:
* The default installation directory for Cygwin is C:\cygwin
.
* On my set up (Gary here), I have Cygwin in C:\bin\cygwin, not the default.
* Also, my .ssh directory was created in the {user.home} directory.
*
*
* @return The .ssh directory
*/
private static File findSshDir()
{
String sshDirPath;
sshDirPath = System.getProperty("vfs.sftp.sshdir");
if (sshDirPath != null)
{
File sshDir = new File(sshDirPath);
if (sshDir.exists())
{
return sshDir;
}
}
File sshDir = new File(System.getProperty("user.home"), SSH_DIR_NAME);
if (sshDir.exists())
{
return sshDir;
}
if (Os.isFamily(Os.OS_FAMILY_WINDOWS))
{
// TODO - this may not be true
final String userName = System.getProperty("user.name");
sshDir = new File("C:\\cygwin\\home\\" + userName + "\\" + SSH_DIR_NAME);
if (sshDir.exists())
{
return sshDir;
}
}
return new File("");
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileNameParser.java 100644 765 24 2577 11623215064 32434 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.URLFileNameParser;
/**
* Implementation for sftp. set default port to 22.
* @author Commons VFS team
*/
public class SftpFileNameParser extends URLFileNameParser
{
private static final SftpFileNameParser INSTANCE = new SftpFileNameParser();
public SftpFileNameParser()
{
super(22);
}
public static FileNameParser getInstance()
{
return INSTANCE;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileObject.java 100644 765 24 41216 11623215064 31616 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.Vector;
import org.apache.commons.vfs2.FileNotFoundException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.RandomAccessContent;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.util.FileObjectUtils;
import org.apache.commons.vfs2.util.MonitorInputStream;
import org.apache.commons.vfs2.util.MonitorOutputStream;
import org.apache.commons.vfs2.util.RandomAccessMode;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.ChannelSftp.LsEntry;
import com.jcraft.jsch.SftpATTRS;
import com.jcraft.jsch.SftpException;
/**
* An SFTP file.
*
* @author Commons VFS team
* 2005) $
*/
public class SftpFileObject extends AbstractFileObject implements FileObject
{
private final SftpFileSystem fileSystem;
private SftpATTRS attrs;
private final String relPath;
private boolean inRefresh;
protected SftpFileObject(final AbstractFileName name,
final SftpFileSystem fileSystem) throws FileSystemException
{
super(name, fileSystem);
this.fileSystem = fileSystem;
relPath = UriParser.decode(fileSystem.getRootName().getRelativeName(
name));
}
/** @since 2.0 */
@Override
protected void doDetach() throws Exception
{
attrs = null;
}
/** @since 2.0 */
@Override
public void refresh() throws FileSystemException
{
if (!inRefresh)
{
try
{
inRefresh = true;
super.refresh();
try
{
attrs = null;
getType();
}
catch (IOException e)
{
throw new FileSystemException(e);
}
}
finally
{
inRefresh = false;
}
}
}
/**
* Determines the type of this file, returns null if the file does not
* exist.
*/
@Override
protected FileType doGetType() throws Exception
{
if (attrs == null)
{
statSelf();
}
if (attrs == null)
{
return FileType.IMAGINARY;
}
if ((attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_PERMISSIONS) == 0)
{
throw new FileSystemException(
"vfs.provider.sftp/unknown-permissions.error");
}
if (attrs.isDir())
{
return FileType.FOLDER;
}
else
{
return FileType.FILE;
}
}
/**
* Called when the type or content of this file changes.
*/
@Override
protected void onChange() throws Exception
{
statSelf();
}
/**
* Fetches file attrs from server.
*/
private void statSelf() throws Exception
{
ChannelSftp channel = fileSystem.getChannel();
try
{
setStat(channel.stat(relPath));
}
catch (final SftpException e)
{
try
{
// maybe the channel has some problems, so recreate the channel and retry
if (e.id != ChannelSftp.SSH_FX_NO_SUCH_FILE)
{
channel.disconnect();
channel = fileSystem.getChannel();
setStat(channel.stat(relPath));
}
else
{
// Really does not exist
attrs = null;
}
}
catch (final SftpException e2)
{
// TODO - not strictly true, but jsch 0.1.2 does not give us
// enough info in the exception. Should be using:
// if ( e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE )
// However, sometimes the exception has the correct id, and
// sometimes
// it does not. Need to look into why.
// Does not exist
attrs = null;
}
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Set attrs from listChildrenResolved
*/
private void setStat(SftpATTRS attrs)
{
this.attrs = attrs;
}
/**
* Creates this file as a folder.
*/
@Override
protected void doCreateFolder() throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
channel.mkdir(relPath);
}
finally
{
fileSystem.putChannel(channel);
}
}
@Override
protected long doGetLastModifiedTime() throws Exception
{
if (attrs == null
|| (attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_ACMODTIME) == 0)
{
throw new FileSystemException(
"vfs.provider.sftp/unknown-modtime.error");
}
return attrs.getMTime() * 1000L;
}
/**
* Sets the last modified time of this file. Is only called if
* {@link #doGetType} does not return {@link FileType#IMAGINARY}.
*
* @param modtime
* is modification time in milliseconds. SFTP protocol can send
* times with nanosecond precision but at the moment jsch send
* them with second precision.
*/
@Override
protected boolean doSetLastModifiedTime(final long modtime) throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
int newMTime = (int) (modtime / 1000L);
attrs.setACMODTIME(attrs.getATime(), newMTime);
channel.setStat(relPath, attrs);
}
finally
{
fileSystem.putChannel(channel);
}
return true;
}
/**
* Deletes the file.
*/
@Override
protected void doDelete() throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
if (getType() == FileType.FILE)
{
channel.rm(relPath);
}
else
{
channel.rmdir(relPath);
}
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Rename the file.
*/
@Override
protected void doRename(FileObject newfile) throws Exception
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
channel.rename(relPath, ((SftpFileObject) newfile).relPath);
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Lists the children of this file.
*/
@Override
protected FileObject[] doListChildrenResolved() throws Exception
{
// List the contents of the folder
Vector> vector = null;
final ChannelSftp channel = fileSystem.getChannel();
try
{
// try the direct way to list the directory on the server to avoid too many roundtrips
vector = channel.ls(relPath);
}
catch (SftpException e)
{
String workingDirectory = null;
try
{
if (relPath != null)
{
workingDirectory = channel.pwd();
channel.cd(relPath);
}
}
catch (SftpException ex)
{
// VFS-210: seems not to be a directory
return null;
}
SftpException lsEx = null;
try
{
vector = channel.ls(".");
}
catch (SftpException ex)
{
lsEx = ex;
}
finally
{
try
{
if (relPath != null)
{
channel.cd(workingDirectory);
}
}
catch (SftpException xe)
{
throw new FileSystemException("vfs.provider.sftp/change-work-directory-back.error",
workingDirectory, lsEx);
}
}
if (lsEx != null)
{
throw lsEx;
}
}
finally
{
fileSystem.putChannel(channel);
}
if (vector == null)
{
throw new FileSystemException(
"vfs.provider.sftp/list-children.error");
}
// Extract the child names
final ArrayList children = new ArrayList();
for (@SuppressWarnings("unchecked") // OK because ChannelSftp.ls() is documented to return Vector
Iterator iterator = (Iterator) vector.iterator(); iterator.hasNext();)
{
final LsEntry stat = iterator.next();
String name = stat.getFilename();
if (VFS.isUriStyle())
{
if (stat.getAttrs().isDir()
&& name.charAt(name.length() - 1) != '/')
{
name = name + "/";
}
}
if (name.equals(".") || name.equals("..") || name.equals("./")
|| name.equals("../"))
{
continue;
}
FileObject fo =
getFileSystem()
.resolveFile(
getFileSystem().getFileSystemManager().resolveName(
getName(), UriParser.encode(name),
NameScope.CHILD));
((SftpFileObject) FileObjectUtils.getAbstractFileObject(fo)).setStat(stat.getAttrs());
children.add(fo);
}
return children.toArray(new FileObject[children.size()]);
}
/**
* Lists the children of this file.
*/
@Override
protected String[] doListChildren() throws Exception
{
// use doListChildrenResolved for performance
return null;
}
/**
* Returns the size of the file content (in bytes).
*/
@Override
protected long doGetContentSize() throws Exception
{
if (attrs == null
|| (attrs.getFlags() & SftpATTRS.SSH_FILEXFER_ATTR_SIZE) == 0)
{
throw new FileSystemException(
"vfs.provider.sftp/unknown-size.error");
}
return attrs.getSize();
}
@Override
protected RandomAccessContent doGetRandomAccessContent(
final RandomAccessMode mode) throws Exception
{
return new SftpRandomAccessContent(this, mode);
}
/**
* Creates an input stream to read the file content from.
*/
InputStream getInputStream(long filePointer) throws IOException
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
// hmmm - using the in memory method is soooo much faster ...
// TODO - Don't read the entire file into memory. Use the
// stream-based methods on ChannelSftp once they work properly final
// .... no stream based method with resume???
ByteArrayOutputStream outstr = new ByteArrayOutputStream();
try
{
channel.get(getName().getPathDecoded(), outstr, null,
ChannelSftp.RESUME, filePointer);
}
catch (SftpException e)
{
throw new FileSystemException(e);
}
outstr.close();
return new ByteArrayInputStream(outstr.toByteArray());
}
finally
{
fileSystem.putChannel(channel);
}
}
/**
* Creates an input stream to read the file content from.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
// VFS-113: avoid npe
synchronized (fileSystem)
{
final ChannelSftp channel = fileSystem.getChannel();
try
{
// return channel.get(getName().getPath());
// hmmm - using the in memory method is soooo much faster ...
// TODO - Don't read the entire file into memory. Use the
// stream-based methods on ChannelSftp once they work properly
/*
final ByteArrayOutputStream outstr = new ByteArrayOutputStream();
channel.get(relPath, outstr);
outstr.close();
return new ByteArrayInputStream(outstr.toByteArray());
*/
InputStream is;
try
{
// VFS-210: sftp allows to gather an input stream even from a directory and will
// fail on first read. So we need to check the type anyway
if (!getType().hasContent())
{
throw new FileSystemException("vfs.provider/read-not-file.error", getName());
}
is = channel.get(relPath);
}
catch (SftpException e)
{
if (e.id == ChannelSftp.SSH_FX_NO_SUCH_FILE)
{
throw new FileNotFoundException(getName());
}
throw new FileSystemException(e);
}
return new SftpInputStream(channel, is);
}
finally
{
// fileSystem.putChannel(channel);
}
}
}
/**
* Creates an output stream to write the file content to.
*/
@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
// TODO - Don't write the entire file into memory. Use the stream-based
// methods on ChannelSftp once the work properly
/*
final ChannelSftp channel = fileSystem.getChannel();
return new SftpOutputStream(channel);
*/
final ChannelSftp channel = fileSystem.getChannel();
return new SftpOutputStream(channel, channel.put(relPath));
}
/**
* An InputStream that monitors for end-of-file.
*/
private class SftpInputStream extends MonitorInputStream
{
private final ChannelSftp channel;
public SftpInputStream(final ChannelSftp channel, final InputStream in)
{
super(in);
this.channel = channel;
}
/**
* Called after the stream has been closed.
*/
@Override
protected void onClose() throws IOException
{
fileSystem.putChannel(channel);
}
}
/**
* An OutputStream that wraps an sftp OutputStream, and closes the channel
* when the stream is closed.
*/
private class SftpOutputStream extends MonitorOutputStream
{
private final ChannelSftp channel;
public SftpOutputStream(final ChannelSftp channel, OutputStream out)
{
super(out);
this.channel = channel;
}
/**
* Called after this stream is closed.
*/
@Override
protected void onClose() throws IOException
{
fileSystem.putChannel(channel);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileProvider.java 100644 765 24 11244 11623215064 32200 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.AbstractOriginatingFileProvider;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
import com.jcraft.jsch.Session;
/**
* A provider for accessing files over SFTP.
*
* @author Commons VFS team
*/
public class SftpFileProvider extends AbstractOriginatingFileProvider
{
/** User Information. */
public static final String ATTR_USER_INFO = "UI";
/** Authentication types. */
public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES =
new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD
};
/** The provider's capabilities. */
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.CREATE,
Capability.DELETE,
Capability.RENAME,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.URI,
Capability.WRITE_CONTENT,
Capability.GET_LAST_MODIFIED,
Capability.SET_LAST_MODIFIED_FILE,
Capability.RANDOM_ACCESS_READ
}));
// private JSch jSch = new JSch();
public SftpFileProvider()
{
super();
setFileNameParser(SftpFileNameParser.getInstance());
}
/**
* Creates a {@link FileSystem}.
*/
@Override
protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// JSch jsch = createJSch(fileSystemOptions);
// Create the file system
final GenericFileName rootName = (GenericFileName) name;
Session session;
UserAuthenticationData authData = null;
try
{
authData = UserAuthenticatorUtils.authenticate(fileSystemOptions, AUTHENTICATOR_TYPES);
session = SftpClientFactory.createConnection(
rootName.getHostName(),
rootName.getPort(),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
UserAuthenticatorUtils.toChar(rootName.getUserName())),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
UserAuthenticatorUtils.toChar(rootName.getPassword())),
fileSystemOptions);
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider.sftp/connect.error",
name,
e);
}
finally
{
UserAuthenticatorUtils.cleanup(authData);
}
return new SftpFileSystem(rootName, session, fileSystemOptions);
}
/**
* Returns the JSch.
*
* @return Returns the jSch.
*/
/*
private JSch getJSch()
{
return this.jSch;
}
*/
/**
* Initialises the component.
* @throws FileSystemException if an error occurs.
*/
@Override
public void init() throws FileSystemException
{
}
@Override
public FileSystemConfigBuilder getConfigBuilder()
{
return SftpFileSystemConfigBuilder.getInstance();
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystem.java 100644 765 24 14671 11623215064 31701 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import java.io.IOException;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
import com.jcraft.jsch.ChannelSftp;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.Session;
import com.jcraft.jsch.SftpException;
/**
* Represents the files on an SFTP server.
*
* @author Commons VFS team
*/
public class SftpFileSystem
extends AbstractFileSystem
implements FileSystem
{
private Session session;
// private final JSch jSch;
private ChannelSftp idleChannel;
protected SftpFileSystem(final GenericFileName rootName,
final Session session,
final FileSystemOptions fileSystemOptions)
{
super(rootName, null, fileSystemOptions);
this.session = session;
}
@Override
protected void doCloseCommunicationLink()
{
if (idleChannel != null)
{
idleChannel.disconnect();
idleChannel = null;
}
if (session != null)
{
session.disconnect();
session = null;
}
}
/**
* Returns an SFTP channel to the server.
*/
protected ChannelSftp getChannel() throws IOException
{
if (this.session == null || !this.session.isConnected())
{
doCloseCommunicationLink();
// channel closed. e.g. by freeUnusedResources, but now we need it again
Session session;
UserAuthenticationData authData = null;
try
{
final GenericFileName rootName = (GenericFileName) getRootName();
authData = UserAuthenticatorUtils.authenticate(getFileSystemOptions(),
SftpFileProvider.AUTHENTICATOR_TYPES);
session = SftpClientFactory.createConnection(
rootName.getHostName(),
rootName.getPort(),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.USERNAME,
UserAuthenticatorUtils.toChar(rootName.getUserName())),
UserAuthenticatorUtils.getData(authData, UserAuthenticationData.PASSWORD,
UserAuthenticatorUtils.toChar(rootName.getPassword())),
getFileSystemOptions());
}
catch (final Exception e)
{
throw new FileSystemException("vfs.provider.sftp/connect.error",
getRootName(),
e);
}
finally
{
UserAuthenticatorUtils.cleanup(authData);
}
this.session = session;
}
try
{
// Use the pooled channel, or create a new one
final ChannelSftp channel;
if (idleChannel != null)
{
channel = idleChannel;
idleChannel = null;
}
else
{
channel = (ChannelSftp) session.openChannel("sftp");
channel.connect();
Boolean userDirIsRoot =
SftpFileSystemConfigBuilder.getInstance().getUserDirIsRoot(getFileSystemOptions());
String workingDirectory = getRootName().getPath();
if (workingDirectory != null && (userDirIsRoot == null || !userDirIsRoot.booleanValue()))
{
try
{
channel.cd(workingDirectory);
}
catch (SftpException e)
{
throw new FileSystemException("vfs.provider.sftp/change-work-directory.error",
workingDirectory);
}
}
}
return channel;
}
catch (final JSchException e)
{
throw new FileSystemException("vfs.provider.sftp/connect.error",
getRootName(),
e);
}
}
/**
* Returns a channel to the pool.
*/
protected void putChannel(final ChannelSftp channel)
{
if (idleChannel == null)
{
// put back the channel only if it is still connected
if (channel.isConnected() && !channel.isClosed())
{
idleChannel = channel;
}
}
else
{
channel.disconnect();
}
}
/**
* Adds the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(SftpFileProvider.capabilities);
}
/**
* Creates a file object. This method is called only if the requested
* file is not cached.
*/
@Override
protected FileObject createFile(final AbstractFileName name)
throws FileSystemException
{
return new SftpFileObject(name, this);
}
/**
* last mod time is only a int and in seconds, thus can be off by 999.
*
* @return 1000
*/
@Override
public double getLastModTimeAccuracy()
{
return 1000L;
}
}
././@LongLink 100644 0 0 152 11623215455 10255 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystemConfigBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpFileSystemConfigBuilder100644 765 24 26116 11623215064 33413 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import java.io.File;
import java.io.Serializable;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import com.jcraft.jsch.UserInfo;
/**
* The config BUILDER for various sftp configuration options.
*
* @author Commons VFS team
*/
public final class SftpFileSystemConfigBuilder extends FileSystemConfigBuilder
{
/** HTTP Proxy. */
public static final ProxyType PROXY_HTTP = new ProxyType("http");
/** SOCKS Proxy. */
public static final ProxyType PROXY_SOCKS5 = new ProxyType("socks");
private static final SftpFileSystemConfigBuilder BUILDER = new SftpFileSystemConfigBuilder();
private static final String USER_DIR_IS_ROOT = SftpFileSystemConfigBuilder.class.getName() + ".USER_DIR_IS_ROOT";
private static final String TIMEOUT = SftpFileSystemConfigBuilder.class.getName() + ".TIMEOUT";
private SftpFileSystemConfigBuilder()
{
super("sftp.");
}
public static SftpFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
/**
* Proxy type.
*/
public static final class ProxyType implements Serializable, Comparable
{
/**
* serialVersionUID format is YYYYMMDD for the date of the last binary change.
*/
private static final long serialVersionUID = 20101208L;
private final String proxyType;
private ProxyType(final String proxyType)
{
this.proxyType = proxyType;
}
public int compareTo(ProxyType o)
{
return proxyType.compareTo(o.proxyType);
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
ProxyType proxyType1 = (ProxyType) o;
if (proxyType != null ? !proxyType.equals(proxyType1.proxyType) : proxyType1.proxyType != null)
{
return false;
}
return true;
}
/** @since 2.0 */
@Override
public int hashCode()
{
return proxyType.hashCode();
}
}
/**
* Set the userinfo class to use if e.g. a password or a not known host
* will be contacted.
*
* @param opts The FileSystem options.
* @param info User information.
*/
public void setUserInfo(FileSystemOptions opts, UserInfo info)
{
setParam(opts, UserInfo.class.getName(), info);
}
/**
* @param opts The FileSystem options.
* @return The UserInfo.
* @see #setUserInfo
*/
public UserInfo getUserInfo(FileSystemOptions opts)
{
return (UserInfo) getParam(opts, UserInfo.class.getName());
}
/**
* Set the known_hosts file. e.g. /home/user/.ssh/known_hosts2
* Need to use a java.io.File as JSch cant deal with vfs FileObjects ;-)
*
* @param opts The FileSystem options.
* @param sshdir The known hosts directory.
* @throws FileSystemException if an error occurs.
*/
public void setKnownHosts(FileSystemOptions opts, File sshdir) throws FileSystemException
{
setParam(opts, "knownHosts", sshdir);
}
/**
* @param opts The FileSystem options.
* @return the known hosts File.
* @see #setKnownHosts
*/
public File getKnownHosts(FileSystemOptions opts)
{
return (File) getParam(opts, "knownHosts");
}
/**
* Set the identity files (your private key files).
* Need to use a java.io.File as JSch cant deal with vfs FileObjects ;-)
*
* @param opts The FileSystem options.
* @param identities An array of identity Files.
* @throws FileSystemException if an error occurs.
*/
public void setIdentities(FileSystemOptions opts, File[] identities) throws FileSystemException
{
setParam(opts, "identities", identities);
}
/**
* configure the compression to use.
* e.g. pass "zlib,none" to enable the compression.
* See the jsch documentation for details.
*
* @param opts The FileSystem options.
* @param compression The compression algorithm name.
* @throws FileSystemException if an error occurs.
*/
public void setCompression(FileSystemOptions opts, String compression) throws FileSystemException
{
setParam(opts, "compression", compression);
}
/**
* @param opts The FileSystem options.
* @return The name of the compression algorithm.
* @see #setCompression
*/
public String getCompression(FileSystemOptions opts)
{
return getString(opts, "compression");
}
/**
* @param opts The FileSystem options.
* @return the array of identity Files.
* @see #setIdentities
*/
public File[] getIdentities(FileSystemOptions opts)
{
return (File[]) getParam(opts, "identities");
}
/**
* configure the host key checking to use.
* valid arguments are only yes, no and ask.
* See the jsch documentation for details.
*
* @param opts The FileSystem options.
* @param hostKeyChecking The host key checking to use.
* @throws FileSystemException if an error occurs.
*/
public void setStrictHostKeyChecking(FileSystemOptions opts, String hostKeyChecking) throws FileSystemException
{
if (hostKeyChecking == null || (!hostKeyChecking.equals("ask") && !hostKeyChecking.equals("no") &&
!hostKeyChecking.equals("yes")))
{
throw new FileSystemException("vfs.provider.sftp/StrictHostKeyChecking-arg.error", hostKeyChecking);
}
setParam(opts, "StrictHostKeyChecking", hostKeyChecking);
}
/**
* @param opts The FileSystem options.
* @return the option value The host key checking.
* @see #setStrictHostKeyChecking(FileSystemOptions, String)
*/
public String getStrictHostKeyChecking(FileSystemOptions opts)
{
return getString(opts, "StrictHostKeyChecking", "no");
}
/**
* use user directory as root (do not change to fs root).
*
* @param opts The FileSystem options.
* @param userDirIsRoot true if the user dir is the root directory.
*/
public void setUserDirIsRoot(FileSystemOptions opts, boolean userDirIsRoot)
{
setParam(opts, USER_DIR_IS_ROOT, userDirIsRoot ? Boolean.TRUE : Boolean.FALSE);
}
/**
* @param opts The FileSystemOptions.
* @return true if the user directory is the root.
* @see #setUserDirIsRoot
*/
public Boolean getUserDirIsRoot(FileSystemOptions opts)
{
return getBoolean(opts, USER_DIR_IS_ROOT, Boolean.TRUE);
}
/**
* set the timeout value on jsch session.
*
* @param opts The FileSystem options.
* @param timeout The timeout.
*/
public void setTimeout(FileSystemOptions opts, Integer timeout)
{
setParam(opts, TIMEOUT, timeout);
}
/**
* @param opts The FileSystem options.
* @return The timeout value.
* @see #setTimeout
*/
public Integer getTimeout(FileSystemOptions opts)
{
return getInteger(opts, TIMEOUT);
}
@Override
protected Class extends FileSystem> getConfigClass()
{
return SftpFileSystem.class;
}
/**
* Set the proxy to use for sftp connection.
* You have to set the ProxyPort too if you would like to have the proxy relly used.
*
* @param opts The FileSystem options.
* @param proxyHost the host
* @see #setProxyPort
*/
public void setProxyHost(FileSystemOptions opts, String proxyHost)
{
setParam(opts, "proxyHost", proxyHost);
}
/**
* Set the proxy-port to use for sftp connection.
* You have to set the ProxyHost too if you would like to have the proxy relly used.
*
* @param opts The FileSystem options.
* @param proxyPort the port
* @see #setProxyHost
*/
public void setProxyPort(FileSystemOptions opts, int proxyPort)
{
setParam(opts, "proxyPort", new Integer(proxyPort));
}
/**
* Get the proxy to use for sftp connection.
* You have to set the ProxyPort too if you would like to have the proxy relly used.
*
* @param opts The FileSystem options.
* @return proxyHost
* @see #setProxyPort
*/
public String getProxyHost(FileSystemOptions opts)
{
return getString(opts, "proxyHost");
}
/**
* Get the proxy-port to use for sftp the connection
* You have to set the ProxyHost too if you would like to have the proxy relly used.
*
* @param opts The FileSystem options.
* @return proxyPort: the port number or 0 if it is not set
* @see #setProxyHost
*/
public int getProxyPort(FileSystemOptions opts)
{
return getInteger(opts, "proxyPort", 0);
}
/**
* Set the proxy type to use for sftp connection.
* @param opts The FileSystem options.
* @param proxyType the type of the proxy to use.
*/
public void setProxyType(FileSystemOptions opts, ProxyType proxyType)
{
setParam(opts, "proxyType", proxyType);
}
/**
* Get the proxy type to use for sftp connection.
* @param opts The FileSystem options.
* @return The ProxyType.
*/
public ProxyType getProxyType(FileSystemOptions opts)
{
return (ProxyType) getParam(opts, "proxyType");
}
/**
* Configure authentication order.
* @param opts The FileSystem options.
* @param preferredAuthentications The authentication order.
* @since 2.0
*/
public void setPreferredAuthentications(FileSystemOptions opts, String preferredAuthentications)
{
setParam(opts, "PreferredAuthentications", preferredAuthentications);
}
/**
* Get authentication order.
* @param opts The FileSystem options.
* @return The authentication order.
* @since 2.0
*/
public String getPreferredAuthentications(FileSystemOptions opts)
{
return (String) getParam(opts, "PreferredAuthentications");
}
}
././@LongLink 100644 0 0 146 11623215455 10260 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpRandomAccessContent.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/SftpRandomAccessContent.jav100644 765 24 10120 11623215064 33332 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import java.io.DataInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractRandomAccessStreamContent;
import org.apache.commons.vfs2.util.RandomAccessMode;
/**
* Random access content.
* @author Commons VFS team
*/
class SftpRandomAccessContent extends AbstractRandomAccessStreamContent
{
/** file pointer */
protected long filePointer = 0;
private final SftpFileObject fileObject;
private DataInputStream dis = null;
private InputStream mis = null;
SftpRandomAccessContent(final SftpFileObject fileObject, RandomAccessMode mode)
{
super(mode);
this.fileObject = fileObject;
// fileSystem = (FtpFileSystem) this.fileObject.getFileSystem();
}
public long getFilePointer() throws IOException
{
return filePointer;
}
public void seek(long pos) throws IOException
{
if (pos == filePointer)
{
// no change
return;
}
if (pos < 0)
{
throw new FileSystemException("vfs.provider/random-access-invalid-position.error",
new Object[]
{
new Long(pos)
});
}
if (dis != null)
{
close();
}
filePointer = pos;
}
@Override
protected DataInputStream getDataInputStream() throws IOException
{
if (dis != null)
{
return dis;
}
// FtpClient client = fileSystem.getClient();
mis = fileObject.getInputStream(filePointer);
dis = new DataInputStream(new FilterInputStream(mis)
{
@Override
public int read() throws IOException
{
int ret = super.read();
if (ret > -1)
{
filePointer++;
}
return ret;
}
@Override
public int read(byte[] b) throws IOException
{
int ret = super.read(b);
if (ret > -1)
{
filePointer += ret;
}
return ret;
}
@Override
public int read(byte[] b, int off, int len) throws IOException
{
int ret = super.read(b, off, len);
if (ret > -1)
{
filePointer += ret;
}
return ret;
}
@Override
public void close() throws IOException
{
SftpRandomAccessContent.this.close();
}
});
return dis;
}
public void close() throws IOException
{
if (dis != null)
{
// mis.abort();
mis.close();
// this is to avoid recursive close
DataInputStream oldDis = dis;
dis = null;
oldDis.close();
mis = null;
}
}
public long length() throws IOException
{
return fileObject.getContent().getSize();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/sftp/TrustEveryoneUserInfo.java 100644 765 24 3437 11623215064 33247 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.sftp;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import com.jcraft.jsch.UserInfo;
/**
* Helper class to trust a new host.
* @author Commons VFS team
*/
public class TrustEveryoneUserInfo implements UserInfo
{
private final Log log = LogFactory.getLog(TrustEveryoneUserInfo.class);
public String getPassphrase()
{
return null;
}
public String getPassword()
{
return null;
}
public boolean promptPassword(String s)
{
log.info(s + " - Answer: False");
return false;
}
public boolean promptPassphrase(String s)
{
log.info(s + " - Answer: False");
return false;
}
public boolean promptYesNo(String s)
{
log.debug(s + " - Answer: Yes");
// trust
return true;
}
public void showMessage(String s)
{
log.debug(s);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/package.html 100644 765 24 1540 11623215064 30157 0 ustar rgoers staff 0 0
The Tar File Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarBuffer.java 100644 765 24 31770 11623215064 30451 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Arrays;
/**
* The TarBuffer class implements the tar archive concept of a buffered input
* stream. This concept goes back to the days of blocked tape drives and special
* io devices. In the Java universe, the only real function that this class
* performs is to ensure that files have the correct "block" size, or other tars
* will complain.
*
* You should never have a need to access this class directly. TarBuffers are
* created by Tar IO Streams.
*
* @author Commons VFS team
*/
class TarBuffer
{
public static final int DEFAULT_RECORDSIZE = (512);
public static final int DEFAULT_BLOCKSIZE = (DEFAULT_RECORDSIZE * 20);
private byte[] blockBuffer;
private int blockSize;
private int currBlkIdx;
private int currRecIdx;
private boolean debug;
private InputStream input;
private OutputStream output;
private int recordSize;
private int recsPerBlock;
TarBuffer(final InputStream input)
{
this(input, TarBuffer.DEFAULT_BLOCKSIZE);
}
TarBuffer(final InputStream input, final int blockSize)
{
this(input, blockSize, TarBuffer.DEFAULT_RECORDSIZE);
}
TarBuffer(final InputStream input,
final int blockSize,
final int recordSize)
{
this.input = input;
initialize(blockSize, recordSize);
}
TarBuffer(final OutputStream output)
{
this(output, TarBuffer.DEFAULT_BLOCKSIZE);
}
TarBuffer(final OutputStream output, final int blockSize)
{
this(output, blockSize, TarBuffer.DEFAULT_RECORDSIZE);
}
TarBuffer(final OutputStream output,
final int blockSize,
final int recordSize)
{
this.output = output;
initialize(blockSize, recordSize);
}
/**
* Set the debugging flag for the buffer.
*
* @param debug If true, print debugging output.
*/
public void setDebug(final boolean debug)
{
this.debug = debug;
}
/**
* Get the TAR Buffer's block size. Blocks consist of multiple records.
*
* @return The BlockSize value
*/
public int getBlockSize()
{
return blockSize;
}
/**
* Get the current block number, zero based.
*
* @return The current zero based block number.
*/
public int getCurrentBlockNum()
{
return currBlkIdx;
}
/**
* Get the current record number, within the current block, zero based.
* Thus, current offset = (currentBlockNum * recsPerBlk) + currentRecNum.
*
* @return The current zero based record number.
*/
public int getCurrentRecordNum()
{
return currRecIdx - 1;
}
/**
* Get the TAR Buffer's record size.
*
* @return The RecordSize value
*/
public int getRecordSize()
{
return recordSize;
}
/**
* Determine if an archive record indicate End of Archive. End of archive is
* indicated by a record that consists entirely of null bytes.
*
* @param record The record data to check.
* @return The EOFRecord value
*/
public boolean isEOFRecord(final byte[] record)
{
final int size = getRecordSize();
for (int i = 0; i < size; ++i)
{
if (record[i] != 0)
{
return false;
}
}
return true;
}
/**
* Close the TarBuffer. If this is an output buffer, also flush the current
* block before closing.
*/
public void close()
throws IOException
{
if (debug)
{
debug("TarBuffer.closeBuffer().");
}
if (null != output)
{
flushBlock();
if (output != System.out && output != System.err)
{
output.close();
output = null;
}
}
else if (input != null)
{
if (input != System.in)
{
input.close();
input = null;
}
}
}
/**
* Read a record from the input stream and return the data.
*
* @return The record data.
* @throws IOException Description of Exception
*/
public byte[] readRecord()
throws IOException
{
if (debug)
{
final String message = "ReadRecord: recIdx = " + currRecIdx +
" blkIdx = " + currBlkIdx;
debug(message);
}
if (null == input)
{
final String message = "reading from an output buffer";
throw new IOException(message);
}
if (currRecIdx >= recsPerBlock)
{
if (!readBlock())
{
return null;
}
}
final byte[] result = new byte[recordSize];
System.arraycopy(blockBuffer,
(currRecIdx * recordSize),
result,
0,
recordSize);
currRecIdx++;
return result;
}
/**
* Skip over a record on the input stream.
*/
public void skipRecord()
throws IOException
{
if (debug)
{
final String message = "SkipRecord: recIdx = " + currRecIdx +
" blkIdx = " + currBlkIdx;
debug(message);
}
if (null == input)
{
final String message = "reading (via skip) from an output buffer";
throw new IOException(message);
}
if (currRecIdx >= recsPerBlock)
{
if (!readBlock())
{
return; // UNDONE
}
}
currRecIdx++;
}
/**
* Write an archive record to the archive.
*
* @param record The record data to write to the archive.
*/
public void writeRecord(final byte[] record)
throws IOException
{
if (debug)
{
final String message = "WriteRecord: recIdx = " + currRecIdx +
" blkIdx = " + currBlkIdx;
debug(message);
}
if (null == output)
{
final String message = "writing to an input buffer";
throw new IOException(message);
}
if (record.length != recordSize)
{
final String message = "record to write has length '" +
record.length + "' which is not the record size of '" +
recordSize + "'";
throw new IOException(message);
}
if (currRecIdx >= recsPerBlock)
{
writeBlock();
}
System.arraycopy(record,
0,
blockBuffer,
(currRecIdx * recordSize),
recordSize);
currRecIdx++;
}
/**
* Write an archive record to the archive, where the record may be inside of
* a larger array buffer. The buffer must be "offset plus record size" long.
*
* @param buffer The buffer containing the record data to write.
* @param offset The offset of the record data within buf.
*/
public void writeRecord(final byte[] buffer, final int offset)
throws IOException
{
if (debug)
{
final String message = "WriteRecord: recIdx = " + currRecIdx +
" blkIdx = " + currBlkIdx;
debug(message);
}
if (null == output)
{
final String message = "writing to an input buffer";
throw new IOException(message);
}
if ((offset + recordSize) > buffer.length)
{
final String message = "record has length '" + buffer.length +
"' with offset '" + offset + "' which is less than the record size of '" +
recordSize + "'";
throw new IOException(message);
}
if (currRecIdx >= recsPerBlock)
{
writeBlock();
}
System.arraycopy(buffer,
offset,
blockBuffer,
(currRecIdx * recordSize),
recordSize);
currRecIdx++;
}
/**
* Flush the current data block if it has any data in it.
*/
private void flushBlock()
throws IOException
{
if (debug)
{
final String message = "TarBuffer.flushBlock() called.";
debug(message);
}
if (output == null)
{
final String message = "writing to an input buffer";
throw new IOException(message);
}
if (currRecIdx > 0)
{
writeBlock();
}
}
/**
* Initialization common to all constructors.
*/
private void initialize(final int blockSize, final int recordSize)
{
debug = false;
this.blockSize = blockSize;
this.recordSize = recordSize;
recsPerBlock = (this.blockSize / this.recordSize);
blockBuffer = new byte[this.blockSize];
if (null != input)
{
currBlkIdx = -1;
currRecIdx = recsPerBlock;
}
else
{
currBlkIdx = 0;
currRecIdx = 0;
}
}
/**
* @return false if End-Of-File, else true
*/
private boolean readBlock()
throws IOException
{
if (debug)
{
final String message = "ReadBlock: blkIdx = " + currBlkIdx;
debug(message);
}
if (null == input)
{
final String message = "reading from an output buffer";
throw new IOException(message);
}
currRecIdx = 0;
int offset = 0;
int bytesNeeded = blockSize;
while (bytesNeeded > 0)
{
final long numBytes = input.read(blockBuffer, offset, bytesNeeded);
//
// NOTE
// We have fit EOF, and the block is not full!
//
// This is a broken archive. It does not follow the standard
// blocking algorithm. However, because we are generous, and
// it requires little effort, we will simply ignore the error
// and continue as if the entire block were read. This does
// not appear to break anything upstream. We used to return
// false in this case.
//
// Thanks to 'Yohann.Roussel@alcatel.fr' for this fix.
//
if (numBytes == -1)
{
// However, just leaving the unread portion of the buffer dirty does
// cause problems in some cases. This problem is described in
// http://issues.apache.org/bugzilla/show_bug.cgi?id=29877
//
// The solution is to fill the unused portion of the buffer with zeros.
Arrays.fill(blockBuffer, offset, offset + bytesNeeded, (byte) 0);
break;
}
offset += numBytes;
bytesNeeded -= numBytes;
if (numBytes != blockSize)
{
if (debug)
{
System.err.println("ReadBlock: INCOMPLETE READ "
+ numBytes + " of " + blockSize
+ " bytes read.");
}
}
}
currBlkIdx++;
return true;
}
/**
* Write a TarBuffer block to the archive.
*
* @throws IOException Description of Exception
*/
private void writeBlock()
throws IOException
{
if (debug)
{
final String message = "WriteBlock: blkIdx = " + currBlkIdx;
debug(message);
}
if (null == output)
{
final String message = "writing to an input buffer";
throw new IOException(message);
}
output.write(blockBuffer, 0, blockSize);
output.flush();
currRecIdx = 0;
currBlkIdx++;
}
protected void debug(final String message)
{
if (debug)
{
System.err.println(message);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarConstants.java 100644 765 24 7412 11623215064 31170 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
/**
* This class contains all the definitions used in the package.
*
* @author Commons VFS team
*/
final class TarConstants
{
/**
* The length of the mode field in a header buffer.
*/
public static final int MODELEN = 8;
/**
* The length of the user id field in a header buffer.
*/
public static final int UIDLEN = 8;
/**
* The length of the group id field in a header buffer.
*/
public static final int GIDLEN = 8;
/**
* The length of the checksum field in a header buffer.
*/
public static final int CHKSUMLEN = 8;
/**
* The length of the size field in a header buffer.
*/
public static final int SIZELEN = 12;
/**
* The length of the magic field in a header buffer.
*/
public static final int MAGICLEN = 8;
/**
* The length of the modification time field in a header buffer.
*/
public static final int MODTIMELEN = 12;
/**
* The length of the user name field in a header buffer.
*/
public static final int UNAMELEN = 32;
/**
* The length of the group name field in a header buffer.
*/
public static final int GNAMELEN = 32;
/**
* The length of the devices field in a header buffer.
*/
public static final int DEVLEN = 8;
/**
* LF_ constants represent the "link flag" of an entry, or more commonly,
* the "entry type". This is the "old way" of indicating a normal file.
*/
public static final byte LF_OLDNORM = 0;
/**
* Normal file type.
*/
public static final byte LF_NORMAL = (byte) '0';
/**
* Link file type.
*/
public static final byte LF_LINK = (byte) '1';
/**
* Symbolic link file type.
*/
public static final byte LF_SYMLINK = (byte) '2';
/**
* Character device file type.
*/
public static final byte LF_CHR = (byte) '3';
/**
* Block device file type.
*/
public static final byte LF_BLK = (byte) '4';
/**
* Directory file type.
*/
public static final byte LF_DIR = (byte) '5';
/**
* FIFO (pipe) file type.
*/
public static final byte LF_FIFO = (byte) '6';
/**
* Contiguous file type.
*/
public static final byte LF_CONTIG = (byte) '7';
/**
* The magic tag representing a POSIX tar archive.
*/
public static final String TMAGIC = "ustar";
/**
* The magic tag representing a GNU tar archive.
*/
public static final String GNU_TMAGIC = "ustar ";
/**
* The namr of the GNU tar entry which contains a long name.
*/
public static final String GNU_LONGLINK = "././@LongLink";
/**
* Identifies the *next* file on the tape as having a long name.
*/
public static final byte LF_GNUTYPE_LONGNAME = (byte) 'L';
/**
* Prevent instantiation
*/
private TarConstants()
{
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarEntry.java 100644 765 24 41313 11623215064 30333 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
import java.io.File;
import java.util.Date;
import java.util.Locale;
/**
* This class represents an entry in a Tar archive. It consists of the entry's
* header, as well as the entry's File. Entries can be instantiated in one of
* three ways, depending on how they are to be used.
*
* TarEntries that are created from the header bytes read from an archive are
* instantiated with the TarEntry( byte[] ) constructor. These entries will be
* used when extracting from or listing the contents of an archive. These
* entries have their header filled in using the header bytes. They also set the
* File to null, since they reference an archive entry not a file.
*
* TarEntries that are created from Files that are to be written into an archive
* are instantiated with the TarEntry( File ) constructor. These entries have
* their header filled in using the File's information. They also keep a
* reference to the File for convenience when writing entries.
*
* Finally, TarEntries can be constructed from nothing but a name. This allows
* the programmer to construct the entry by hand, for instance when only an
* InputStream is available for writing to the archive, and the header
* information is constructed from other information. In this case the header
* fields are set to defaults and the File is set to null.
*
* The C structure for a Tar Entry's header is:
* struct header {
* char name[NAMSIZ];
* char mode[8];
* char uid[8];
* char gid[8];
* char size[12];
* char mtime[12];
* char chksum[8];
* char linkflag;
* char linkname[NAMSIZ];
* char magic[8];
* char uname[TUNMLEN];
* char gname[TGNMLEN];
* char devmajor[8];
* char devminor[8];
* } header;
*
*
* @author Commons VFS team
* @see TarInputStream
*/
class TarEntry
{
/**
* The length of the name field in a header buffer.
*/
public static final int NAMELEN = 100;
/**
* The entry's modification time.
*/
private int checkSum;
/**
* The entry's group name.
*/
private int devMajor;
/**
* The entry's major device number.
*/
private int devMinor;
/**
* The entry's minor device number.
*/
private File file;
/**
* The entry's user id.
*/
private int groupID;
/**
* The entry's user name.
*/
private StringBuffer groupName;
/**
* The entry's checksum.
*/
private byte linkFlag;
/**
* The entry's link flag.
*/
private StringBuffer linkName;
/**
* The entry's link name.
*/
private StringBuffer magic;
/**
* The entry's size.
*/
private long modTime;
/**
* The entry's name.
*/
private int mode;
private StringBuffer name;
/**
* The entry's group id.
*/
private long size;
/**
* The entry's permission mode.
*/
private int userID;
/**
* The entry's magic tag.
*/
private StringBuffer userName;
/**
* Construct an entry with only a name. This allows the programmer to
* construct the entry's header "by hand". File is set to null.
*
* @param name the name of the entry
*/
TarEntry(final String name)
{
this();
final boolean isDir = name.endsWith("/");
this.name = new StringBuffer(name);
mode = isDir ? 040755 : 0100644;
linkFlag = isDir ? TarConstants.LF_DIR : TarConstants.LF_NORMAL;
modTime = (new Date()).getTime() / 1000;
linkName = new StringBuffer("");
userName = new StringBuffer("");
groupName = new StringBuffer("");
}
/**
* Construct an entry with a name an a link flag.
*
* @param name Description of Parameter
* @param linkFlag Description of Parameter
*/
TarEntry(final String name, final byte linkFlag)
{
this(name);
this.linkFlag = linkFlag;
}
/**
* Construct an entry for a file. File is set to file, and the header is
* constructed from information from the file.
*
* @param file The file that the entry represents.
*/
TarEntry(final File file)
{
this();
this.file = file;
String name = file.getPath();
// Strip off drive letters!
final String osName =
System.getProperty("os.name").toLowerCase(Locale.US);
if (-1 != osName.indexOf("netware"))
{
if (name.length() > 2)
{
final char ch1 = name.charAt(0);
final char ch2 = name.charAt(1);
if (ch2 == ':' &&
((ch1 >= 'a' && ch1 <= 'z') ||
(ch1 >= 'A' && ch1 <= 'Z')))
{
name = name.substring(2);
}
}
}
else if (-1 != osName.indexOf("netware"))
{
final int colon = name.indexOf(':');
if (colon != -1)
{
name = name.substring(colon + 1);
}
}
name = name.replace(File.separatorChar, '/');
// No absolute pathnames
// Windows (and Posix?) paths can start with "\\NetworkDrive\",
// so we loop on starting /'s.
while (name.startsWith("/"))
{
name = name.substring(1);
}
linkName = new StringBuffer("");
this.name = new StringBuffer(name);
if (file.isDirectory())
{
mode = 040755;
linkFlag = TarConstants.LF_DIR;
if (this.name.charAt(this.name.length() - 1) != '/')
{
this.name.append("/");
}
}
else
{
mode = 0100644;
linkFlag = TarConstants.LF_NORMAL;
}
size = file.length();
modTime = file.lastModified() / 1000;
checkSum = 0;
devMajor = 0;
devMinor = 0;
}
/**
* Construct an entry from an archive's header bytes. File is set to null.
*
* @param header The header bytes from a tar archive entry.
*/
TarEntry(final byte[] header)
{
this();
parseTarHeader(header);
}
/**
* Construct an empty entry and prepares the header values.
*/
private TarEntry()
{
magic = new StringBuffer(TarConstants.TMAGIC);
name = new StringBuffer();
linkName = new StringBuffer();
String user = System.getProperty("user.name", "");
if (user.length() > 31)
{
user = user.substring(0, 31);
}
userName = new StringBuffer(user);
groupName = new StringBuffer("");
}
/**
* Set this entry's group id.
*
* @param groupId This entry's new group id.
*/
public void setGroupID(final int groupId)
{
groupID = groupId;
}
/**
* Set this entry's group name.
*
* @param groupName This entry's new group name.
*/
public void setGroupName(final String groupName)
{
this.groupName = new StringBuffer(groupName);
}
/**
* Set this entry's modification time. The parameter passed to this method
* is in "Java time".
*
* @param time This entry's new modification time.
*/
public void setModTime(final long time)
{
modTime = time / 1000;
}
/**
* Set this entry's modification time.
*
* @param time This entry's new modification time.
*/
public void setModTime(final Date time)
{
modTime = time.getTime() / 1000;
}
/**
* Set the mode for this entry
*
* @param mode The new Mode value
*/
public void setMode(final int mode)
{
this.mode = mode;
}
/**
* Set this entry's name.
*
* @param name This entry's new name.
*/
public void setName(final String name)
{
this.name = new StringBuffer(name);
}
/**
* Set this entry's file size.
*
* @param size This entry's new file size.
*/
public void setSize(final long size)
{
this.size = size;
}
/**
* Set this entry's user id.
*
* @param userId This entry's new user id.
*/
public void setUserID(final int userId)
{
userID = userId;
}
/**
* Set this entry's user name.
*
* @param userName This entry's new user name.
*/
public void setUserName(final String userName)
{
this.userName = new StringBuffer(userName);
}
/**
* If this entry represents a file, and the file is a directory, return an
* array of TarEntries for this entry's children.
*
* @return An array of TarEntry's for this entry's children.
*/
public TarEntry[] getDirectoryEntries()
{
if (null == file || !file.isDirectory())
{
return new TarEntry[0];
}
final String[] list = file.list();
final TarEntry[] result = new TarEntry[list.length];
for (int i = 0; i < list.length; ++i)
{
result[i] = new TarEntry(new File(file, list[i]));
}
return result;
}
/**
* Get this entry's file.
*
* @return This entry's file.
*/
public File getFile()
{
return file;
}
/**
* Get this entry's group id.
*
* @return This entry's group id.
*/
public int getGroupID()
{
return groupID;
}
/**
* Get this entry's group name.
*
* @return This entry's group name.
*/
public String getGroupName()
{
return groupName.toString();
}
/**
* Set this entry's modification time.
*
* @return The ModTime value
*/
public Date getModTime()
{
return new Date(modTime * 1000);
}
/**
* Get this entry's mode.
*
* @return This entry's mode.
*/
public int getMode()
{
return mode;
}
/**
* Get this entry's name.
*
* @return This entry's name.
*/
public String getName()
{
return name.toString();
}
/**
* Get this entry's file size.
*
* @return This entry's file size.
*/
public long getSize()
{
return size;
}
/**
* Get this entry's checksum.
*
* @return This entry's checksum.
*/
public int getCheckSum()
{
return checkSum;
}
/**
* Get this entry's user id.
*
* @return This entry's user id.
*/
public int getUserID()
{
return userID;
}
/**
* Get this entry's user name.
*
* @return This entry's user name.
*/
public String getUserName()
{
return userName.toString();
}
/**
* Determine if the given entry is a descendant of this entry. Descendancy
* is determined by the name of the descendant starting with this entry's
* name.
*
* @param desc Entry to be checked as a descendent of
* @return True if entry is a descendant of
*/
public boolean isDescendent(final TarEntry desc)
{
return desc.getName().startsWith(getName());
}
/**
* Return whether or not this entry represents a directory.
*
* @return True if this entry is a directory.
*/
public boolean isDirectory()
{
if (file != null)
{
return file.isDirectory();
}
if (linkFlag == TarConstants.LF_DIR)
{
return true;
}
if (getName().endsWith("/"))
{
return true;
}
return false;
}
/**
* Indicate if this entry is a GNU long name block
*
* @return true if this is a long name extension provided by GNU tar
*/
public boolean isGNULongNameEntry()
{
return linkFlag == TarConstants.LF_GNUTYPE_LONGNAME &&
name.toString().equals(TarConstants.GNU_LONGLINK);
}
/**
* Determine if the two entries are equal. Equality is determined by the
* header names being equal.
*
* @param other Entry to be checked for equality.
* @return True if the entries are equal.
*/
@Override
public boolean equals(final Object other)
{
if (!(other instanceof TarEntry))
{
return false;
}
TarEntry entry = (TarEntry) other;
return getName().equals(entry.getName());
}
@Override
public int hashCode()
{
return getName().hashCode();
}
/**
* Parse an entry's header information from a header buffer.
*
* @param header The tar entry header buffer to get information from.
*/
private void parseTarHeader(final byte[] header)
{
int offset = 0;
name = TarUtils.parseName(header, offset, NAMELEN);
offset += NAMELEN;
mode = (int) TarUtils.parseOctal(header, offset, TarConstants.MODELEN);
offset += TarConstants.MODELEN;
userID = (int) TarUtils.parseOctal(header, offset, TarConstants.UIDLEN);
offset += TarConstants.UIDLEN;
groupID = (int) TarUtils.parseOctal(header, offset, TarConstants.GIDLEN);
offset += TarConstants.GIDLEN;
size = TarUtils.parseOctal(header, offset, TarConstants.SIZELEN);
offset += TarConstants.SIZELEN;
modTime = TarUtils.parseOctal(header, offset, TarConstants.MODTIMELEN);
offset += TarConstants.MODTIMELEN;
checkSum = (int) TarUtils.parseOctal(header, offset, TarConstants.CHKSUMLEN);
offset += TarConstants.CHKSUMLEN;
linkFlag = header[offset++];
linkName = TarUtils.parseName(header, offset, NAMELEN);
offset += NAMELEN;
magic = TarUtils.parseName(header, offset, TarConstants.MAGICLEN);
offset += TarConstants.MAGICLEN;
userName = TarUtils.parseName(header, offset, TarConstants.UNAMELEN);
offset += TarConstants.UNAMELEN;
groupName = TarUtils.parseName(header, offset, TarConstants.GNAMELEN);
offset += TarConstants.GNAMELEN;
devMajor = (int) TarUtils.parseOctal(header, offset, TarConstants.DEVLEN);
offset += TarConstants.DEVLEN;
devMinor = (int) TarUtils.parseOctal(header, offset, TarConstants.DEVLEN);
}
/**
* Write an entry's header information to a header buffer.
*
* @param buffer The tar entry header buffer to fill in.
*/
public void writeEntryHeader(final byte[] buffer)
{
int offset = 0;
offset = TarUtils.getNameBytes(name, buffer, offset, NAMELEN);
offset = TarUtils.getOctalBytes(mode, buffer, offset, TarConstants.MODELEN);
offset = TarUtils.getOctalBytes(userID, buffer, offset, TarConstants.UIDLEN);
offset = TarUtils.getOctalBytes(groupID, buffer, offset, TarConstants.GIDLEN);
offset = TarUtils.getLongOctalBytes(size, buffer, offset, TarConstants.SIZELEN);
offset = TarUtils.getLongOctalBytes(modTime, buffer, offset, TarConstants.MODTIMELEN);
final int checkSumOffset = offset;
for (int i = 0; i < TarConstants.CHKSUMLEN; ++i)
{
buffer[offset++] = (byte) ' ';
}
buffer[offset++] = linkFlag;
offset = TarUtils.getNameBytes(linkName, buffer, offset, NAMELEN);
offset = TarUtils.getNameBytes(magic, buffer, offset, TarConstants.MAGICLEN);
offset = TarUtils.getNameBytes(userName, buffer, offset, TarConstants.UNAMELEN);
offset = TarUtils.getNameBytes(groupName, buffer, offset, TarConstants.GNAMELEN);
offset = TarUtils.getOctalBytes(devMajor, buffer, offset, TarConstants.DEVLEN);
offset = TarUtils.getOctalBytes(devMinor, buffer, offset, TarConstants.DEVLEN);
while (offset < buffer.length)
{
buffer[offset++] = 0;
}
final long checkSum = TarUtils.computeCheckSum(buffer);
TarUtils.getCheckSumOctalBytes(checkSum, buffer, checkSumOffset, TarConstants.CHKSUMLEN);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileObject.java 100644 765 24 11437 11623215064 31244 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
//TODO: Revert to [compress]
//import org.apache.commons.compress.tar.TarEntry;
import java.io.InputStream;
import java.util.HashSet;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
/**
* A file in a Tar file system.
* @author Commons VFS team
*/
public class TarFileObject extends AbstractFileObject implements FileObject
{
/** The TarEntry */
protected TarEntry entry;
private final HashSet children = new HashSet();
private final TarFileSystem fs;
private FileType type;
protected TarFileObject(AbstractFileName name,
TarEntry entry,
TarFileSystem fs,
boolean tarExists) throws FileSystemException
{
super(name, fs);
this.fs = fs;
setTarEntry(entry);
if (!tarExists)
{
type = FileType.IMAGINARY;
}
}
/**
* Sets the details for this file object.
*/
protected void setTarEntry(final TarEntry entry)
{
if (this.entry != null)
{
return;
}
if ((entry == null) || (entry.isDirectory()))
{
type = FileType.FOLDER;
}
else
{
type = FileType.FILE;
}
this.entry = entry;
}
/**
* Attaches a child
*/
protected void attachChild(FileName childName)
{
children.add(childName.getBaseName());
}
/**
* Determines if this file can be written to.
*
* @return true
if this file is writeable, false
if not.
* @throws FileSystemException if an error occurs.
*/
@Override
public boolean isWriteable() throws FileSystemException
{
return false;
}
/**
* Returns the file's type.
*/
@Override
protected FileType doGetType()
{
return type;
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren()
{
try
{
if (!getType().hasChildren())
{
return null;
}
}
catch (FileSystemException e)
{
// should not happen as the type has already been cached.
throw new RuntimeException(e);
}
return children.toArray(new String[children.size()]);
}
/**
* Returns the size of the file content (in bytes). Is only called if
* {@link #doGetType} returns {@link FileType#FILE}.
*/
@Override
protected long doGetContentSize()
{
if (entry == null)
{
return 0;
}
return entry.getSize();
}
/**
* Returns the last modified time of this file.
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
if (entry == null)
{
return 0;
}
return entry.getModTime().getTime();
}
/**
* Creates an input stream to read the file content from. Is only called
* if {@link #doGetType} returns {@link FileType#FILE}. The input stream
* returned by this method is guaranteed to be closed before this
* method is called again.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
// VFS-210: zip allows to gather an input stream even from a directory and will
// return -1 on the first read. getType should not be expensive and keeps the tests
// running
if (!getType().hasContent())
{
throw new FileSystemException("vfs.provider/read-not-file.error", getName());
}
return fs.getInputStream(entry);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileProvider.java 100644 765 24 5764 11623215064 31616 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractLayeredFileProvider;
import org.apache.commons.vfs2.provider.FileProvider;
import org.apache.commons.vfs2.provider.LayeredFileName;
/**
* A file system provider for Tar files. Provides read-only file systems.
* @author Commons VFS team
*/
public class TarFileProvider extends AbstractLayeredFileProvider implements FileProvider
{
/** The provider's capabilities */
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.GET_LAST_MODIFIED,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.URI,
Capability.VIRTUAL
}));
public TarFileProvider()
{
super();
}
/**
* Creates a layered file system. This method is called if the file system
* is not cached.
*
* @param scheme The URI scheme.
* @param file The file to create the file system on top of.
* @return The file system.
*/
@Override
protected FileSystem doCreateFileSystem(final String scheme,
final FileObject file,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
final AbstractFileName rootName =
new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
return new TarFileSystem(rootName, file, fileSystemOptions);
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarFileSystem.java 100644 765 24 20716 11623215064 31322 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
//TODO: Revert to [compress]
//import org.apache.commons.compress.tar.TarEntry;
//import org.apache.commons.compress.tar.TarInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.zip.GZIPInputStream;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VfsLog;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.provider.bzip2.Bzip2FileObject;
/**
* A read-only file system for Tar files.
*
* @author Commons VFS team
*/
public class TarFileSystem extends AbstractFileSystem implements FileSystem
{
private static final Log LOG = LogFactory.getLog(TarFileSystem.class);
private final File file;
private TarInputStream tarFile;
protected TarFileSystem(final AbstractFileName rootName,
final FileObject parentLayer,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
super(rootName, parentLayer, fileSystemOptions);
// Make a local copy of the file
file = parentLayer.getFileSystem().replicateFile(parentLayer, Selectors.SELECT_SELF);
// Open the Tar file
if (!file.exists())
{
// Don't need to do anything
tarFile = null;
return;
}
// tarFile = createTarFile(this.file);
}
@Override
public void init() throws FileSystemException
{
super.init();
// Build the index
try
{
List strongRef = new ArrayList(100);
TarEntry entry;
while ((entry = getTarFile().getNextEntry()) != null)
{
AbstractFileName name = (AbstractFileName) getFileSystemManager().resolveName(getRootName(),
UriParser.encode(entry.getName()));
// Create the file
TarFileObject fileObj;
if (entry.isDirectory() && getFileFromCache(name) != null)
{
fileObj = (TarFileObject) getFileFromCache(name);
fileObj.setTarEntry(entry);
continue;
}
fileObj = createTarFileObject(name, entry);
putFileToCache(fileObj);
strongRef.add(fileObj);
fileObj.holdObject(strongRef);
// Make sure all ancestors exist
// TODO - create these on demand
TarFileObject parent = null;
for (AbstractFileName parentName = (AbstractFileName) name.getParent();
parentName != null;
fileObj = parent, parentName = (AbstractFileName) parentName.getParent())
{
// Locate the parent
parent = (TarFileObject) getFileFromCache(parentName);
if (parent == null)
{
parent = createTarFileObject(parentName, null);
putFileToCache(parent);
strongRef.add(parent);
parent.holdObject(strongRef);
}
// Attach child to parent
parent.attachChild(fileObj.getName());
}
}
}
catch (IOException e)
{
throw new FileSystemException(e);
}
finally
{
closeCommunicationLink();
}
}
public InputStream getInputStream(TarEntry entry) throws FileSystemException
{
resetTarFile();
try
{
while (!tarFile.getNextEntry().equals(entry))
{
}
return tarFile;
}
catch (IOException e)
{
throw new FileSystemException(e);
}
}
protected void resetTarFile() throws FileSystemException
{
// Reading specific entries requires skipping through the tar file from the beginning
// Not especially elegant, but we don't have the ability to seek to specific positions
// with an input stream.
if (this.file.exists())
{
recreateTarFile();
}
}
private void recreateTarFile() throws FileSystemException
{
if (this.tarFile != null)
{
try
{
this.tarFile.close();
}
catch (IOException e)
{
throw new FileSystemException("vfs.provider.tar/close-tar-file.error", file, e);
}
tarFile = null;
}
TarInputStream tarFile = createTarFile(this.file);
this.tarFile = tarFile;
}
protected TarInputStream getTarFile() throws FileSystemException
{
if (tarFile == null && this.file.exists())
{
recreateTarFile();
}
return tarFile;
}
protected TarFileObject createTarFileObject(final AbstractFileName name,
final TarEntry entry) throws FileSystemException
{
return new TarFileObject(name, entry, this, true);
}
protected TarInputStream createTarFile(final File file) throws FileSystemException
{
try
{
if ("tgz".equalsIgnoreCase(getRootName().getScheme()))
{
return new TarInputStream(new GZIPInputStream(new FileInputStream(file)));
}
else if ("tbz2".equalsIgnoreCase(getRootName().getScheme()))
{
return new TarInputStream(Bzip2FileObject.wrapInputStream(file.getAbsolutePath(),
new FileInputStream(file)));
}
return new TarInputStream(new FileInputStream(file));
}
catch (IOException ioe)
{
throw new FileSystemException("vfs.provider.tar/open-tar-file.error", file, ioe);
}
}
@Override
protected void doCloseCommunicationLink()
{
// Release the tar file
try
{
if (tarFile != null)
{
tarFile.close();
tarFile = null;
}
}
catch (final IOException e)
{
// getLogger().warn("vfs.provider.tar/close-tar-file.error :" + file, e);
VfsLog.warn(getLogger(), LOG, "vfs.provider.tar/close-tar-file.error :" + file, e);
}
}
/**
* Returns the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(TarFileProvider.capabilities);
}
/**
* Creates a file object.
*/
@Override
protected FileObject createFile(final AbstractFileName name) throws FileSystemException
{
// This is only called for files which do not exist in the Tar file
return new TarFileObject(name, null, this, false);
}
/**
* will be called after all file-objects closed their streams.
protected void notifyAllStreamsClosed()
{
closeCommunicationLink();
}
*/
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarInputStream.java 100644 765 24 33463 11623215064 31514 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
/**
* The TarInputStream reads a UNIX tar archive as an InputStream. methods are
* provided to position at each successive entry in the archive, and the read
* each entry as a normal input stream using read().
*
* @author Commons VFS team
* @see TarInputStream
* @see TarEntry
*/
class TarInputStream
extends FilterInputStream
{
private TarBuffer buffer;
private TarEntry currEntry;
private boolean debug;
private int entryOffset;
private long entrySize;
private boolean hasHitEOF;
private byte[] oneBuf;
private byte[] readBuf;
/**
* Construct a TarInputStream using specified input
* stream and default block and record sizes.
*
* @param input stream to create TarInputStream from
* @see TarBuffer#DEFAULT_BLOCKSIZE
* @see TarBuffer#DEFAULT_RECORDSIZE
*/
TarInputStream(final InputStream input)
{
this(input, TarBuffer.DEFAULT_BLOCKSIZE, TarBuffer.DEFAULT_RECORDSIZE);
}
/**
* Construct a TarInputStream using specified input
* stream, block size and default record sizes.
*
* @param input stream to create TarInputStream from
* @param blockSize the block size to use
* @see TarBuffer#DEFAULT_RECORDSIZE
*/
TarInputStream(final InputStream input,
final int blockSize)
{
this(input, blockSize, TarBuffer.DEFAULT_RECORDSIZE);
}
/**
* Construct a TarInputStream using specified input
* stream, block size and record sizes.
*
* @param input stream to create TarInputStream from
* @param blockSize the block size to use
* @param recordSize the record size to use
*/
TarInputStream(final InputStream input, final int blockSize, final int recordSize)
{
super(input);
buffer = new TarBuffer(input, blockSize, recordSize);
oneBuf = new byte[1];
}
/**
* Sets the debugging flag.
*
* @param debug The new Debug value
*/
public void setDebug(final boolean debug)
{
this.debug = debug;
buffer.setDebug(debug);
}
/**
* Get the next entry in this tar archive. This will skip over any remaining
* data in the current entry, if there is one, and place the input stream at
* the header of the next entry, and read the header and instantiate a new
* TarEntry from the header bytes and return that entry. If there are no
* more entries in the archive, null will be returned to indicate that the
* end of the archive has been reached.
*
* @return The next TarEntry in the archive, or null.
* @throws IOException Description of Exception
*/
public TarEntry getNextEntry() throws IOException
{
if (hasHitEOF)
{
return null;
}
if (currEntry != null)
{
final long numToSkip = entrySize - entryOffset;
if (debug)
{
final String message = "TarInputStream: SKIP currENTRY '" +
currEntry.getName() + "' SZ " + entrySize +
" OFF " + entryOffset + " skipping " + numToSkip + " bytes";
debug(message);
}
if (numToSkip > 0)
{
// Use our internal skip to move to the end of the current entry
longSkip(numToSkip);
}
readBuf = null;
}
final byte[] headerBuf = buffer.readRecord();
if (headerBuf == null)
{
if (debug)
{
debug("READ NULL RECORD");
}
hasHitEOF = true;
currEntry = null;
}
else if (buffer.isEOFRecord(headerBuf))
{
if (debug)
{
debug("READ EOF RECORD");
}
hasHitEOF = true;
currEntry = null;
}
else
{
currEntry = new TarEntry(headerBuf);
if (!(headerBuf[257] == 'u' && headerBuf[258] == 's' &&
headerBuf[259] == 't' && headerBuf[260] == 'a' &&
headerBuf[261] == 'r'))
{
//Must be v7Format
}
if (debug)
{
final String message = "TarInputStream: SET CURRENTRY '" +
currEntry.getName() + "' size = " + currEntry.getSize();
debug(message);
}
entryOffset = 0;
entrySize = currEntry.getSize();
}
if (null != currEntry && currEntry.isGNULongNameEntry())
{
// read in the name
final StringBuffer longName = new StringBuffer();
final byte[] buffer = new byte[256];
int length = 0;
while ((length = read(buffer)) >= 0)
{
final String str = new String(buffer, 0, length);
longName.append(str);
}
getNextEntry();
// remove trailing null terminator
if (longName.length() > 0
&& longName.charAt(longName.length() - 1) == 0)
{
longName.deleteCharAt(longName.length() - 1);
}
currEntry.setName(longName.toString());
}
return currEntry;
}
/**
* Get the record size being used by this stream's TarBuffer.
*
* @return The TarBuffer record size.
*/
public int getRecordSize()
{
return buffer.getRecordSize();
}
/**
* Get the available data that can be read from the current entry in the
* archive. This does not indicate how much data is left in the entire
* archive, only in the current entry. This value is determined from the
* entry's size header field and the amount of data already read from the
* current entry.
*
* @return The number of available bytes for the current entry.
* @throws IOException when an IO error causes operation to fail
*/
@Override
public int available() throws IOException
{
long remaining = entrySize - entryOffset;
if (remaining > Integer.MAX_VALUE)
{
return Integer.MAX_VALUE;
}
return (int) remaining;
}
/**
* Closes this stream. Calls the TarBuffer's close() method.
*
* @throws IOException when an IO error causes operation to fail
*/
@Override
public void close() throws IOException
{
buffer.close();
}
/**
* Copies the contents of the current tar archive entry directly into an
* output stream.
*
* @param output The OutputStream into which to write the entry's data.
* @throws IOException when an IO error causes operation to fail
*/
public void copyEntryContents(final OutputStream output) throws IOException
{
final byte[] buffer = new byte[32 * 1024];
while (true)
{
final int numRead = read(buffer, 0, buffer.length);
if (numRead == -1)
{
break;
}
output.write(buffer, 0, numRead);
}
}
/**
* Since we do not support marking just yet, we do nothing.
*
* @param markLimit The limit to mark.
*/
@Override
public void mark(int markLimit)
{
}
/**
* Since we do not support marking just yet, we return false.
*
* @return False.
*/
@Override
public boolean markSupported()
{
return false;
}
/**
* Reads a byte from the current tar archive entry. This method simply calls
* read( byte[], int, int ).
*
* @return The byte read, or -1 at EOF.
* @throws IOException when an IO error causes operation to fail
*/
@Override
public int read() throws IOException
{
final int num = read(oneBuf, 0, 1);
if (num == -1)
{
return num;
}
else
{
return oneBuf[0];
}
}
/**
* Reads bytes from the current tar archive entry. This method simply calls
* read( byte[], int, int ).
*
* @param buffer The buffer into which to place bytes read.
* @return The number of bytes read, or -1 at EOF.
* @throws IOException when an IO error causes operation to fail
*/
@Override
public int read(final byte[] buffer) throws IOException
{
return read(buffer, 0, buffer.length);
}
/**
* Reads bytes from the current tar archive entry. This method is aware of
* the boundaries of the current entry in the archive and will deal with
* them as if they were this stream's start and EOF.
*
* @param buffer The buffer into which to place bytes read.
* @param offset The offset at which to place bytes read.
* @param count The number of bytes to read.
* @return The number of bytes read, or -1 at EOF.
* @throws IOException when an IO error causes operation to fail
*/
@Override
public int read(final byte[] buffer, final int offset, final int count) throws IOException
{
int position = offset;
int numToRead = count;
int totalRead = 0;
if (entryOffset >= entrySize)
{
return -1;
}
if ((numToRead + entryOffset) > entrySize)
{
numToRead = (int) (entrySize - entryOffset);
}
if (null != readBuf)
{
final int size =
(numToRead > readBuf.length) ? readBuf.length : numToRead;
System.arraycopy(readBuf, 0, buffer, position, size);
if (size >= readBuf.length)
{
readBuf = null;
}
else
{
final int newLength = readBuf.length - size;
final byte[] newBuffer = new byte[newLength];
System.arraycopy(readBuf, size, newBuffer, 0, newLength);
readBuf = newBuffer;
}
totalRead += size;
numToRead -= size;
position += size;
}
while (numToRead > 0)
{
final byte[] rec = this.buffer.readRecord();
if (null == rec)
{
// Unexpected EOF!
final String message =
"unexpected EOF with " + numToRead + " bytes unread";
throw new IOException(message);
}
int size = numToRead;
final int recordLength = rec.length;
if (recordLength > size)
{
System.arraycopy(rec, 0, buffer, position, size);
readBuf = new byte[recordLength - size];
System.arraycopy(rec, size, readBuf, 0, recordLength - size);
}
else
{
size = recordLength;
System.arraycopy(rec, 0, buffer, position, recordLength);
}
totalRead += size;
numToRead -= size;
position += size;
}
entryOffset += totalRead;
return totalRead;
}
/**
* Since we do not support marking just yet, we do nothing.
*/
@Override
public void reset()
{
}
public void longSkip(final long numToSkip) throws IOException
{
for (long skipped = 0; skipped < numToSkip;)
{
if (numToSkip - skipped > Integer.MAX_VALUE)
{
skip(Integer.MAX_VALUE);
skipped += Integer.MAX_VALUE;
}
else
{
skip((int) (numToSkip - skipped));
skipped += numToSkip - skipped;
}
}
}
/**
* Skip bytes in the input buffer. This skips bytes in the current entry's
* data, not the entire archive, and will stop at the end of the current
* entry's data if the number to skip extends beyond that point.
*
* @param numToSkip The number of bytes to skip.
* @throws IOException when an IO error causes operation to fail
*/
public void skip(final int numToSkip) throws IOException
{
// REVIEW
// This is horribly inefficient, but it ensures that we
// properly skip over bytes via the TarBuffer...
//
final byte[] skipBuf = new byte[8 * 1024];
int num = numToSkip;
while (num > 0)
{
final int count = (num > skipBuf.length) ? skipBuf.length : num;
final int numRead = read(skipBuf, 0, count);
if (numRead == -1)
{
break;
}
num -= numRead;
}
}
/**
* Utility method to do debugging.
* Capable of being overidden in sub-classes.
*
* @param message the message to use in debugging
*/
protected void debug(final String message)
{
if (debug)
{
System.err.println(message);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TarUtils.java 100644 765 24 15752 11623215064 30342 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
/**
* This class provides static utility methods to work with byte streams.
*
* @author Commons VFS team
*/
final class TarUtils
{
/**
* Private constructor since this is a utility class with only static methods.
*/
private TarUtils()
{
}
/**
* Parse the checksum octal integer from a header buffer.
*
* @param offset The offset into the buffer from which to parse.
* @param length The number of header bytes to parse.
* @param value Description of Parameter
* @param buf Description of Parameter
* @return The integer value of the entry's checksum.
*/
public static int getCheckSumOctalBytes(final long value,
final byte[] buf,
final int offset,
final int length)
{
getOctalBytes(value, buf, offset, length);
buf[offset + length - 1] = (byte) ' ';
buf[offset + length - 2] = 0;
return offset + length;
}
/**
* Parse an octal long integer from a header buffer.
*
* @param offset The offset into the buffer from which to parse.
* @param length The number of header bytes to parse.
* @param value Description of Parameter
* @param buf Description of Parameter
* @return The long value of the octal bytes.
*/
public static int getLongOctalBytes(final long value,
final byte[] buf,
final int offset,
final int length)
{
byte[] temp = new byte[length + 1];
getOctalBytes(value, temp, 0, length + 1);
System.arraycopy(temp, 0, buf, offset, length);
return offset + length;
}
/**
* Determine the number of bytes in an entry name.
*
* @param offset The offset into the buffer from which to parse.
* @param length The number of header bytes to parse.
* @param name Description of Parameter
* @param buffer Description of Parameter
* @return The number of bytes in a header's entry name.
*/
public static int getNameBytes(final StringBuffer name,
final byte[] buffer,
final int offset,
final int length)
{
int i;
for (i = 0; i < length && i < name.length(); ++i)
{
buffer[offset + i] = (byte) name.charAt(i);
}
for (; i < length; ++i)
{
buffer[offset + i] = 0;
}
return offset + length;
}
/**
* Parse an octal integer from a header buffer.
*
* @param offset The offset into the buffer from which to parse.
* @param length The number of header bytes to parse.
* @return The integer value of the octal bytes.
*/
public static int getOctalBytes(final long value,
final byte[] buffer,
final int offset,
final int length)
{
int idx = length - 1;
buffer[offset + idx] = 0;
--idx;
buffer[offset + idx] = (byte) ' ';
--idx;
if (value == 0)
{
buffer[offset + idx] = (byte) '0';
--idx;
}
else
{
long val = value;
while (idx >= 0 && val > 0)
{
buffer[offset + idx] = (byte) ((byte) '0' + (byte) (val & 7));
val = val >> 3;
idx--;
}
}
while (idx >= 0)
{
buffer[offset + idx] = (byte) ' ';
idx--;
}
return offset + length;
}
/**
* Compute the checksum of a tar entry header.
*
* @param buffer The tar entry's header buffer.
* @return The computed checksum.
*/
public static long computeCheckSum(final byte[] buffer)
{
long sum = 0;
for (int i = 0; i < buffer.length; ++i)
{
sum += 255 & buffer[i];
}
return sum;
}
/**
* Parse an entry name from a header buffer.
*
* @param header The header buffer from which to parse.
* @param offset The offset into the buffer from which to parse.
* @param length The number of header bytes to parse.
* @return The header's entry name.
*/
public static StringBuffer parseName(final byte[] header,
final int offset,
final int length)
{
StringBuffer result = new StringBuffer(length);
int end = offset + length;
for (int i = offset; i < end; ++i)
{
if (header[i] == 0)
{
break;
}
result.append((char) header[i]);
}
return result;
}
/**
* Parse an octal string from a header buffer. This is used for the file
* permission mode value.
*
* @param header The header buffer from which to parse.
* @param offset The offset into the buffer from which to parse.
* @param length The number of header bytes to parse.
* @return The long value of the octal string.
*/
public static long parseOctal(final byte[] header,
final int offset,
final int length)
{
long result = 0;
boolean stillPadding = true;
int end = offset + length;
for (int i = offset; i < end; ++i)
{
if (header[i] == 0)
{
break;
}
if (header[i] == (byte) ' ' || header[i] == '0')
{
if (stillPadding)
{
continue;
}
if (header[i] == (byte) ' ')
{
break;
}
}
stillPadding = false;
result = (result << 3) + (header[i] - '0');
}
return result;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/Tbz2FileProvider.java 100644 765 24 3240 11623215064 31674 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.provider.CompositeFileProvider;
/**
* A file system provider for Tar files. Provides read-only file systems.
* @author Commons VFS team
*/
public class Tbz2FileProvider extends CompositeFileProvider
{
/** The provider's capabilities */
protected static final Collection capabilities = TarFileProvider.capabilities;
private static final String[] SCHEMES = new String[]
{
"bz2",
"tar"
};
public Tbz2FileProvider()
{
super();
}
@Override
protected String[] getSchemes()
{
return SCHEMES;
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/tar/TgzFileProvider.java 100644 765 24 3235 11623215064 31623 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.tar;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.provider.CompositeFileProvider;
/**
* A file system provider for Tar files. Provides read-only file systems.
* @author Commons VFS team
*/
public class TgzFileProvider extends CompositeFileProvider
{
/** The provider's capabilities */
protected static final Collection capabilities = TarFileProvider.capabilities;
private static final String[] SCHEMES = new String[]
{
"gz",
"tar"
};
public TgzFileProvider()
{
super();
}
@Override
protected String[] getSchemes()
{
return SCHEMES;
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/temp/package.html 100644 765 24 1553 11623215064 30342 0 ustar rgoers staff 0 0
The Temporary Filespace Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/temp/TemporaryFileProvider.java 100644 765 24 10360 11623215064 33235 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.temp;
import java.io.File;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileProvider;
import org.apache.commons.vfs2.provider.FileProvider;
import org.apache.commons.vfs2.provider.UriParser;
import org.apache.commons.vfs2.provider.local.DefaultLocalFileProvider;
import org.apache.commons.vfs2.provider.local.LocalFileSystem;
/**
* A provider for temporary files.
*
* @author Commons VFS team
*/
public class TemporaryFileProvider
extends AbstractFileProvider
implements FileProvider, Comparable
{
private File rootFile;
/*
private final static FileName tmpFileName = new AbstractFileName("tmp", "/")
{
protected FileName createName(String absPath)
{
return null;
}
protected void appendRootUri(StringBuffer buffer)
{
}
};
*/
public TemporaryFileProvider(final File rootFile)
{
this();
this.rootFile = rootFile;
}
public TemporaryFileProvider()
{
super();
}
public int compareTo(Object o)
{
int h1 = hashCode();
int h2 = o.hashCode();
if (h1 < h2)
{
return -1;
}
if (h1 > h2)
{
return 1;
}
return 0;
}
/**
* Locates a file object, by absolute URI.
* @param baseFile The base FileObject.
* @param uri The URI of the file to be located.
* @param properties FileSystemOptions to use to locate or create the file.
* @return The FileObject.
* @throws FileSystemException if an error occurs.
*/
public synchronized FileObject findFile(final FileObject baseFile, final String uri,
final FileSystemOptions properties)
throws FileSystemException
{
// Parse the name
final StringBuilder buffer = new StringBuilder(uri);
final String scheme = UriParser.extractScheme(uri, buffer);
UriParser.fixSeparators(buffer);
FileType fileType = UriParser.normalisePath(buffer);
final String path = buffer.toString();
// Create the temp file system if it does not exist
// FileSystem filesystem = findFileSystem( this, (Properties) null);
FileSystem filesystem = findFileSystem(this, properties);
if (filesystem == null)
{
if (rootFile == null)
{
rootFile = getContext().getTemporaryFileStore().allocateFile("tempfs");
}
final FileName rootName =
getContext().parseURI(scheme + ":" + FileName.ROOT_PATH);
// final FileName rootName =
// new LocalFileName(scheme, scheme + ":", FileName.ROOT_PATH);
filesystem = new LocalFileSystem(rootName, rootFile.getAbsolutePath(), properties);
addFileSystem(this, filesystem);
}
// Find the file
return filesystem.resolveFile(path);
}
public Collection getCapabilities()
{
return DefaultLocalFileProvider.capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/TemporaryFileStore.java 100644 765 24 2663 11623215065 31562 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.File;
import org.apache.commons.vfs2.FileSystemException;
/**
* Manages a repository of temporary local files.
*
* @author Commons VFS team
*/
public interface TemporaryFileStore
{
/**
* Allocates a new temporary file. The file (and all its descendents)
* will be deleted when this store is closed.
*
* @param basename The name of the file.
* @return The temporary file.
* @throws FileSystemException if an error occurs.
*/
File allocateFile(String basename) throws FileSystemException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/UriParser.java 100644 765 24 41144 11623215065 27714 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.VFS;
import org.apache.commons.vfs2.util.Os;
/**
* Utilities for dealing with URIs. See RFC 2396 for details.
*
* @author Commons VFS team
* 2005) $
*/
public final class UriParser
{
/**
* The set of valid separators. These are all converted to the normalised
* one. Does not contain the normalised separator
*/
// public static final char[] separators = {'\\'};
public static final char TRANS_SEPARATOR = '\\';
/**
* The normalised separator to use.
*/
private static final char SEPARATOR_CHAR = FileName.SEPARATOR_CHAR;
private static final int HEX_BASE = 16;
private static final int BITS_IN_HALF_BYTE = 4;
private static final char LOW_MASK = 0x0F;
private UriParser()
{
}
/**
* Extracts the first element of a path.
* @param name StringBuilder containing the path.
* @return The first element of the path.
*/
public static String extractFirstElement(final StringBuilder name)
{
final int len = name.length();
if (len < 1)
{
return null;
}
int startPos = 0;
if (name.charAt(0) == SEPARATOR_CHAR)
{
startPos = 1;
}
for (int pos = startPos; pos < len; pos++)
{
if (name.charAt(pos) == SEPARATOR_CHAR)
{
// Found a separator
final String elem = name.substring(startPos, pos);
name.delete(startPos, pos + 1);
return elem;
}
}
// No separator
final String elem = name.substring(startPos);
name.setLength(0);
return elem;
}
/**
* Normalises a path. Does the following:
*
* Removes empty path elements.
* Handles '.' and '..' elements.
* Removes trailing separator.
*
*
* Its assumed that the separators are already fixed.
*
* @param path The path to normalize.
* @return The FileType.
* @throws FileSystemException if an error occurs.
*
* @see #fixSeparators
*/
public static FileType normalisePath(final StringBuilder path)
throws FileSystemException
{
FileType fileType = FileType.FOLDER;
if (path.length() == 0)
{
return fileType;
}
if (path.charAt(path.length() - 1) != '/')
{
fileType = FileType.FILE;
}
// Adjust separators
// fixSeparators(path);
// Determine the start of the first element
int startFirstElem = 0;
if (path.charAt(0) == SEPARATOR_CHAR)
{
if (path.length() == 1)
{
return fileType;
}
startFirstElem = 1;
}
// Iterate over each element
int startElem = startFirstElem;
int maxlen = path.length();
while (startElem < maxlen)
{
// Find the end of the element
int endElem = startElem;
for (; endElem < maxlen && path.charAt(endElem) != SEPARATOR_CHAR; endElem++)
{
}
final int elemLen = endElem - startElem;
if (elemLen == 0)
{
// An empty element - axe it
path.delete(endElem, endElem + 1);
maxlen = path.length();
continue;
}
if (elemLen == 1 && path.charAt(startElem) == '.')
{
// A '.' element - axe it
path.delete(startElem, endElem + 1);
maxlen = path.length();
continue;
}
if (elemLen == 2 && path.charAt(startElem) == '.'
&& path.charAt(startElem + 1) == '.')
{
// A '..' element - remove the previous element
if (startElem == startFirstElem)
{
// Previous element is missing
throw new FileSystemException(
"vfs.provider/invalid-relative-path.error");
}
// Find start of previous element
int pos = startElem - 2;
for (; pos >= 0 && path.charAt(pos) != SEPARATOR_CHAR; pos--)
{
}
startElem = pos + 1;
path.delete(startElem, endElem + 1);
maxlen = path.length();
continue;
}
// A regular element
startElem = endElem + 1;
}
// Remove trailing separator
if (!VFS.isUriStyle())
{
if (maxlen > 0 && path.charAt(maxlen - 1) == SEPARATOR_CHAR
&& maxlen > 1)
{
path.delete(maxlen - 1, maxlen);
}
}
return fileType;
}
/**
* Normalises the separators in a name.
* @param name The StringBuilder containing the name
* @return true if the StringBuilder was modified.
*/
public static boolean fixSeparators(final StringBuilder name)
{
boolean changed = false;
final int maxlen = name.length();
for (int i = 0; i < maxlen; i++)
{
final char ch = name.charAt(i);
if (ch == TRANS_SEPARATOR)
{
name.setCharAt(i, SEPARATOR_CHAR);
changed = true;
}
}
return changed;
}
/**
* Extracts the scheme from a URI.
*
* @param uri The URI.
* @return The scheme name. Returns null if there is no scheme.
*/
public static String extractScheme(final String uri)
{
return extractScheme(uri, null);
}
/**
* Extracts the scheme from a URI. Removes the scheme and ':' delimiter from
* the front of the URI.
*
* @param uri The URI.
* @param buffer Returns the remainder of the URI.
* @return The scheme name. Returns null if there is no scheme.
*/
public static String extractScheme(final String uri, final StringBuilder buffer)
{
if (buffer != null)
{
buffer.setLength(0);
buffer.append(uri);
}
final int maxPos = uri.length();
for (int pos = 0; pos < maxPos; pos++)
{
final char ch = uri.charAt(pos);
if (ch == ':')
{
// Found the end of the scheme
final String scheme = uri.substring(0, pos);
if (scheme.length() <= 1 && Os.isFamily(Os.OS_FAMILY_WINDOWS))
{
// This is not a scheme, but a Windows drive letter
return null;
}
if (buffer != null)
{
buffer.delete(0, pos + 1);
}
return scheme.intern();
}
if ((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z'))
{
// A scheme character
continue;
}
if (pos > 0
&& ((ch >= '0' && ch <= '9') || ch == '+' || ch == '-' || ch == '.'))
{
// A scheme character (these are not allowed as the first
// character of the scheme, but can be used as subsequent
// characters.
continue;
}
// Not a scheme character
break;
}
// No scheme in URI
return null;
}
/**
* Removes %nn encodings from a string.
* @param encodedStr The encoded String.
* @return The decoded String.
* @throws FileSystemException if an error occurs.
*/
public static String decode(final String encodedStr)
throws FileSystemException
{
if (encodedStr == null)
{
return null;
}
if (encodedStr.indexOf('%') < 0)
{
return encodedStr;
}
final StringBuilder buffer = new StringBuilder(encodedStr);
decode(buffer, 0, buffer.length());
return buffer.toString();
}
/**
* Removes %nn encodings from a string.
* @param buffer StringBuilder containing the string to decode.
* @param offset The position in the string to start decoding.
* @param length The number of characters to decode.
* @throws FileSystemException if an error occurs.
*/
public static void decode(final StringBuilder buffer, final int offset, final int length)
throws FileSystemException
{
int index = offset;
int count = length;
for (; count > 0; count--, index++)
{
final char ch = buffer.charAt(index);
if (ch != '%')
{
continue;
}
if (count < 3)
{
throw new FileSystemException(
"vfs.provider/invalid-escape-sequence.error", buffer
.substring(index, index + count));
}
// Decode
int dig1 = Character.digit(buffer.charAt(index + 1), HEX_BASE);
int dig2 = Character.digit(buffer.charAt(index + 2), HEX_BASE);
if (dig1 == -1 || dig2 == -1)
{
throw new FileSystemException(
"vfs.provider/invalid-escape-sequence.error", buffer
.substring(index, index + 3));
}
char value = (char) (dig1 << BITS_IN_HALF_BYTE | dig2);
// Replace
buffer.setCharAt(index, value);
buffer.delete(index + 1, index + 3);
count -= 2;
}
}
/**
* Encodes and appends a string to a StringBuilder.
* @param buffer The StringBuilder to append to.
* @param unencodedValue The String to encode and append.
* @param reserved characters to encode.
*/
public static void appendEncoded(final StringBuilder buffer,
final String unencodedValue, final char[] reserved)
{
final int offset = buffer.length();
buffer.append(unencodedValue);
encode(buffer, offset, unencodedValue.length(), reserved);
}
/**
* Encodes a set of reserved characters in a StringBuilder, using the URI %nn
* encoding. Always encodes % characters.
* @param buffer The StringBuilder to append to.
* @param offset The position in the buffer to start encoding at.
* @param length The number of characters to encode.
* @param reserved characters to encode.
*/
public static void encode(final StringBuilder buffer, final int offset,
final int length, final char[] reserved)
{
int index = offset;
int count = length;
for (; count > 0; index++, count--)
{
final char ch = buffer.charAt(index);
boolean match = ch == '%';
if (reserved != null)
{
for (int i = 0; !match && i < reserved.length; i++)
{
if (ch == reserved[i])
{
match = true;
}
}
}
if (match)
{
// Encode
char[] digits =
{Character.forDigit(((ch >> BITS_IN_HALF_BYTE) & LOW_MASK), HEX_BASE),
Character.forDigit((ch & LOW_MASK), HEX_BASE)};
buffer.setCharAt(index, '%');
buffer.insert(index + 1, digits);
index += 2;
}
}
}
/**
* Removes %nn encodings from a string.
* @param decodedStr The decoded String.
* @return The encoded String.
*/
public static String encode(final String decodedStr)
{
return encode(decodedStr, null);
}
/**
* Converts "special" characters to their %nn value.
* @param decodedStr The decoded String.
* @param reserved Characters to encode.
* @return The encoded String
*/
public static String encode(final String decodedStr, final char[] reserved)
{
if (decodedStr == null)
{
return null;
}
final StringBuilder buffer = new StringBuilder(decodedStr);
encode(buffer, 0, buffer.length(), reserved);
return buffer.toString();
}
/**
* Encode an array of Strings.
* @param strings The array of Strings to encode.
* @return An array of encoded Strings.
*/
public static String[] encode(String[] strings)
{
if (strings == null)
{
return null;
}
for (int i = 0; i < strings.length; i++)
{
strings[i] = encode(strings[i]);
}
return strings;
}
/**
* Decodes the String.
* @param uri The String to decode.
* @throws FileSystemException if an error occurs.
*/
public static void checkUriEncoding(String uri) throws FileSystemException
{
decode(uri);
}
public static void canonicalizePath(StringBuilder buffer, int offset,
int length, FileNameParser fileNameParser)
throws FileSystemException
{
int index = offset;
int count = length;
for (; count > 0; count--, index++)
{
final char ch = buffer.charAt(index);
if (ch == '%')
{
if (count < 3)
{
throw new FileSystemException(
"vfs.provider/invalid-escape-sequence.error",
buffer.substring(index, index + count));
}
// Decode
int dig1 = Character.digit(buffer.charAt(index + 1), HEX_BASE);
int dig2 = Character.digit(buffer.charAt(index + 2), HEX_BASE);
if (dig1 == -1 || dig2 == -1)
{
throw new FileSystemException(
"vfs.provider/invalid-escape-sequence.error",
buffer.substring(index, index + 3));
}
char value = (char) (dig1 << BITS_IN_HALF_BYTE | dig2);
boolean match = value == '%'
|| (fileNameParser != null && fileNameParser.encodeCharacter(value));
if (match)
{
// this is a reserved character, not allowed to decode
index += 2;
count -= 2;
continue;
}
// Replace
buffer.setCharAt(index, value);
buffer.delete(index + 1, index + 3);
count -= 2;
}
else if (fileNameParser.encodeCharacter(ch))
{
// Encode
char[] digits =
{Character.forDigit(((ch >> BITS_IN_HALF_BYTE) & LOW_MASK), HEX_BASE),
Character.forDigit((ch & LOW_MASK), HEX_BASE) };
buffer.setCharAt(index, '%');
buffer.insert(index + 1, digits);
index += 2;
}
}
}
/**
* Extract the query String from the URI.
* @param name StringBuilder containing the URI.
* @return The query string, if any. null otherwise.
*/
public static String extractQueryString(StringBuilder name)
{
for (int pos = 0; pos < name.length(); pos++)
{
if (name.charAt(pos) == '?')
{
String queryString = name.substring(pos + 1);
name.delete(pos, name.length());
return queryString;
}
}
return null;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/url/package.html 100644 765 24 1576 11623215064 30204 0 ustar rgoers staff 0 0
The Default File Provider, which wraps java.net.URL.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileName.java 100644 765 24 4310 11623215064 30716 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.url;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.URLFileName;
/**
* A URL FileName.
* @author Commons VFS team
*/
public class UrlFileName extends URLFileName
{
/**
* The constructor.
* @param scheme The scheme to use.
* @param hostName The host name.
* @param port The port.
* @param defaultPort The default port.
* @param userName The user's login id.
* @param password The user's credentials.
* @param path The file path.
* @param type The file type.
* @param queryString Parameters to use when locating or creating the file name.
*/
public UrlFileName(final String scheme, final String hostName, final int port, final int defaultPort,
final String userName, final String password, final String path, final FileType type,
final String queryString)
{
super(scheme, hostName, port, defaultPort, userName, password, path, type, queryString);
}
@Override
protected void appendRootUri(final StringBuilder buffer, boolean addPassword)
{
if (getHostName() != null && !"".equals(getHostName()))
{
super.appendRootUri(buffer, addPassword);
return;
}
buffer.append(getScheme());
buffer.append(":");
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileNameParser.java 100644 765 24 7611 11623215064 32102 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.url;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.provider.AbstractFileNameParser;
import org.apache.commons.vfs2.provider.URLFileName;
import org.apache.commons.vfs2.provider.URLFileNameParser;
import org.apache.commons.vfs2.provider.VfsComponentContext;
import org.apache.commons.vfs2.provider.local.GenericFileNameParser;
/**
* Implementation for any java.net.url based filesystem.
* Composite of URLFilenameParser and GenericFilenameParser
*
* @author Commons VFS team
*/
public class UrlFileNameParser extends AbstractFileNameParser
{
private final URLFileNameParser url = new URLFileNameParser(80);
private final GenericFileNameParser generic = new GenericFileNameParser();
public UrlFileNameParser()
{
super();
}
@Override
public boolean encodeCharacter(char ch)
{
return super.encodeCharacter(ch) || ch == '?';
}
/**
* Parse a URI.
* @param context The component context.
* @param base The base FileName.
* @param filename The target file name.
* @return The FileName.
* @throws FileSystemException if an error occurs
*/
public FileName parseUri(final VfsComponentContext context, final FileName base, final String filename)
throws FileSystemException
{
if (isUrlBased(base, filename))
{
return url.parseUri(context, base, filename);
}
return generic.parseUri(context, base, filename);
}
/**
* Guess is the given filename is a url with host or not. VFS treats such urls differently.
* A filename is url-based if the base is a URLFileName
or there are only 2 slashes
* after the scheme.
* e.g: http://host/path, file:/path/to/file, file:///path/to/file
*
*/
protected boolean isUrlBased(final FileName base, final String filename)
{
if (base instanceof URLFileName)
{
return true;
}
int nuofSlash = countSlashes(filename);
return nuofSlash == 2;
}
/**
* This method counts the slashes after the scheme.
*
* @param filename The file name.
* @return number of slashes
*/
protected int countSlashes(final String filename)
{
int state = 0;
int nuofSlash = 0;
for (int pos = 0; pos < filename.length(); pos++)
{
char c = filename.charAt(pos);
if (state == 0)
{
if (c >= 'a' && c <= 'z')
{
continue;
}
if (c == ':')
{
state++;
continue;
}
}
else if (state == 1)
{
if (c == '/')
{
nuofSlash++;
}
else
{
return nuofSlash;
}
}
}
return nuofSlash;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileObject.java 100644 765 24 11542 11623215064 31271 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.url;
import java.io.FileNotFoundException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
import org.apache.commons.vfs2.provider.URLFileName;
/**
* A {@link FileObject} implementation backed by a {@link URL}.
*
* @author Commons VFS team
* @todo Implement set lastModified and get/set attribute
* @todo Implement getOutputStream()
*/
public class UrlFileObject extends AbstractFileObject implements FileObject
{
private URL url;
protected UrlFileObject(final UrlFileSystem fs,
final AbstractFileName fileName)
{
super(fileName, fs);
}
/**
* Attaches this file object to its file resource. This method is called
* before any of the doBlah() or onBlah() methods. Sub-classes can use
* this method to perform lazy initialisation.
*/
@Override
protected void doAttach() throws Exception
{
if (url == null)
{
// url = new URL(getName().getURI());
url = createURL(getName());
}
}
protected URL createURL(final FileName name) throws MalformedURLException, FileSystemException, URIException
{
if (name instanceof URLFileName)
{
URLFileName urlName = (URLFileName) getName();
// TODO: charset
return new URL(urlName.getURIEncoded(null));
}
return new URL(getName().getURI());
}
/**
* Determines the type of the file.
*/
@Override
protected FileType doGetType() throws Exception
{
try
{
// Attempt to connect & check status
final URLConnection conn = url.openConnection();
final InputStream in = conn.getInputStream();
try
{
if (conn instanceof HttpURLConnection)
{
final int status = ((HttpURLConnection) conn).getResponseCode();
// 200 is good, maybe add more later...
if (HttpURLConnection.HTTP_OK != status)
{
return FileType.IMAGINARY;
}
}
return FileType.FILE;
}
finally
{
in.close();
}
}
catch (final FileNotFoundException e)
{
return FileType.IMAGINARY;
}
}
/**
* Returns the size of the file content (in bytes).
*/
@Override
protected long doGetContentSize() throws Exception
{
final URLConnection conn = url.openConnection();
final InputStream in = conn.getInputStream();
try
{
return conn.getContentLength();
}
finally
{
in.close();
}
}
/**
* Returns the last modified time of this file.
*/
@Override
protected long doGetLastModifiedTime()
throws Exception
{
final URLConnection conn = url.openConnection();
final InputStream in = conn.getInputStream();
try
{
return conn.getLastModified();
}
finally
{
in.close();
}
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren() throws Exception
{
throw new FileSystemException("Not implemented.");
}
/**
* Creates an input stream to read the file content from.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
return url.openStream();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileProvider.java 100644 765 24 7234 11623215064 31640 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.url;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileProvider;
/**
* A file provider backed by Java's URL API.
*
* @author Commons VFS team
*/
public class UrlFileProvider
extends AbstractFileProvider
{
/** The provider's capabilities */
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.READ_CONTENT,
Capability.URI,
Capability.GET_LAST_MODIFIED
}));
public UrlFileProvider()
{
super();
setFileNameParser(new UrlFileNameParser());
}
/**
* Locates a file object, by absolute URI.
* @param baseFile The base FileObject.
* @param uri The uri of the file to locate.
* @param fileSystemOptions The FileSystemOptions
* @return The FileObject
* @throws FileSystemException if an error occurs.
*/
public synchronized FileObject findFile(final FileObject baseFile,
final String uri,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
try
{
final URL url = new URL(uri);
URL rootUrl = new URL(url, "/");
final String key = this.getClass().getName() + rootUrl.toString();
FileSystem fs = findFileSystem(key, fileSystemOptions);
if (fs == null)
{
String extForm = rootUrl.toExternalForm();
final FileName rootName =
getContext().parseURI(extForm);
// final FileName rootName =
// new BasicFileName(rootUrl, FileName.ROOT_PATH);
fs = new UrlFileSystem(rootName, fileSystemOptions);
addFileSystem(key, fs);
}
return fs.resolveFile(url.getPath());
}
catch (final MalformedURLException e)
{
throw new FileSystemException("vfs.provider.url/badly-formed-uri.error", uri, e);
}
}
@Override
public FileSystemConfigBuilder getConfigBuilder()
{
return org.apache.commons.vfs2.provider.res.ResourceFileSystemConfigBuilder.getInstance();
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/url/UrlFileSystem.java 100644 765 24 3727 11623215064 31335 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.url;
import java.util.Collection;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
/**
* A File system backed by Java's URL API.
*
* @author Commons VFS team
*/
public class UrlFileSystem
extends AbstractFileSystem
implements FileSystem
{
protected UrlFileSystem(final FileName rootName, final FileSystemOptions fileSystemOptions)
{
super(rootName, null, fileSystemOptions);
}
/**
* Creates a file object.
*/
@Override
protected FileObject createFile(final AbstractFileName name)
{
return new UrlFileObject(this, name);
}
/**
* Returns the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(UrlFileProvider.capabilities);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/URLFileName.java 100644 765 24 11473 11623215065 30045 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.util.URIUtil;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
/**
* @author Commons VFS team
*/
public class URLFileName extends GenericFileName
{
private static final int BUFFSZ = 250;
private final String queryString;
public URLFileName(final String scheme,
final String hostName,
final int port,
final int defaultPort,
final String userName,
final String password,
final String path,
final FileType type,
final String queryString)
{
super(scheme, hostName, port, defaultPort, userName, password, path, type);
this.queryString = queryString;
}
/**
* Get the query string.
*
* @return the query string part of the filename
*/
public String getQueryString()
{
return queryString;
}
/**
* Get the path and query string e.g. /path/servlet?param1=true.
*
* @return the path and its query string
*/
public String getPathQuery()
{
StringBuilder sb = new StringBuilder(BUFFSZ);
sb.append(getPath());
sb.append("?");
sb.append(getQueryString());
return sb.toString();
}
/**
* Get the path encoded suitable for url like filesystem e.g. (http, webdav).
*
* @param charset the charset used for the path encoding
* @return The encoded path.
* @throws URIException If an error occurs encoding the URI.
* @throws FileSystemException If some other error occurs.
*/
public String getPathQueryEncoded(String charset) throws URIException, FileSystemException
{
if (getQueryString() == null)
{
if (charset != null)
{
return URIUtil.encodePath(getPathDecoded(), charset);
}
else
{
return URIUtil.encodePath(getPathDecoded());
}
}
StringBuilder sb = new StringBuilder(BUFFSZ);
if (charset != null)
{
sb.append(URIUtil.encodePath(getPathDecoded(), charset));
}
else
{
sb.append(URIUtil.encodePath(getPathDecoded()));
}
sb.append("?");
sb.append(getQueryString());
return sb.toString();
}
/**
* Create a FileName.
* @param absPath The absolute path.
* @param type The FileType.
* @return The FileName
*/
@Override
public FileName createName(final String absPath, FileType type)
{
return new URLFileName(getScheme(),
getHostName(),
getPort(),
getDefaultPort(),
getUserName(),
getPassword(),
absPath,
type,
getQueryString());
}
/**
* Append query string to the uri.
*
* @return the uri
*/
@Override
protected String createURI()
{
if (getQueryString() != null)
{
StringBuilder sb = new StringBuilder(BUFFSZ);
sb.append(super.createURI());
sb.append("?");
sb.append(getQueryString());
return sb.toString();
}
return super.createURI();
}
/**
* Encode a URI.
* @param charset The character set.
* @return The encoded URI
* @throws FileSystemException if some other exception occurs.
* @throws URIException if an exception occurs encoding the URI.
*/
public String getURIEncoded(String charset) throws FileSystemException, URIException
{
StringBuilder sb = new StringBuilder(BUFFSZ);
appendRootUri(sb, true);
sb.append(getPathQueryEncoded(charset));
return sb.toString();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/URLFileNameParser.java 100644 765 24 4721 11623215065 31200 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
/**
* Implementation for any url based filesystem.
* Parses the url into user/password/host/port/path/queryString
*
* @author Commons VFS team
*/
public class URLFileNameParser extends HostFileNameParser
{
public URLFileNameParser(final int defaultPort)
{
super(defaultPort);
}
@Override
public boolean encodeCharacter(char ch)
{
return super.encodeCharacter(ch) || ch == '?';
}
@Override
public FileName parseUri(final VfsComponentContext context, FileName base, final String filename)
throws FileSystemException
{
// FTP URI are generic URI (as per RFC 2396)
final StringBuilder name = new StringBuilder();
// Extract the scheme and authority parts
final Authority auth = extractToPath(filename, name);
// Extract the queryString
String queryString = UriParser.extractQueryString(name);
// Decode and normalise the file name
UriParser.canonicalizePath(name, 0, name.length(), this);
UriParser.fixSeparators(name);
FileType fileType = UriParser.normalisePath(name);
final String path = name.toString();
return new URLFileName(
auth.getScheme(),
auth.getHostName(),
auth.getPort(),
getDefaultPort(),
auth.getUserName(),
auth.getPassword(),
path,
fileType,
queryString);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponent.java 100644 765 24 3513 11623215065 30377 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import org.apache.commons.logging.Log;
import org.apache.commons.vfs2.FileSystemException;
/**
* This interface is used to manage the lifecycle of all VFS components.
* This includes all implementations of the following interfaces:
*
* {@link FileProvider}
* {@link org.apache.commons.vfs2.FileSystem}
* {@link FileReplicator}
* {@link TemporaryFileStore}
*
*
* @author Commons VFS team
*/
public interface VfsComponent
{
/**
* Sets the Logger to use for the component.
*
* @param logger The Log
*/
void setLogger(Log logger);
/**
* Sets the context for the component.
*
* @param context The context.
*/
void setContext(VfsComponentContext context);
/**
* Initialises the component.
* @throws FileSystemException if an error occurs.
*/
void init() throws FileSystemException;
/**
* Closes the component.
*/
void close();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/VfsComponentContext.java 100644 765 24 7061 11623215065 31746 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider;
import java.io.File;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* Allows VFS components to access the services they need, such as the file
* replicator. A VFS component is supplied with a context as part of its
* initialisation.
*
* @author Commons VFS team
* @see VfsComponent#setContext
*/
public interface VfsComponentContext
{
/**
* Locate a file by name. See
* {@link FileSystemManager#resolveFile(FileObject, String)} for a
* description of how this works.
* @param baseFile The base FileObject.
* @param name The name of the file to locate.
* @param fileSystemOptions The FileSystemOptions.
* @return The FileObject for the located file.
* @throws FileSystemException if an error occurs.
*/
FileObject resolveFile(FileObject baseFile, String name, FileSystemOptions fileSystemOptions)
throws FileSystemException;
/**
* Locate a file by name. See
* {@link FileSystemManager#resolveFile( String)} for a
* description of how this works.
* @param name The name of the file to locate.
* @param fileSystemOptions The FileSystemOptions.
* @return The FileObject for the located file.
* @throws FileSystemException if an error occurs.
*/
FileObject resolveFile(String name, FileSystemOptions fileSystemOptions)
throws FileSystemException;
/**
* Parse a URI into a FileName.
* @param uri The URI String.
* @return The FileName.
* @throws FileSystemException if an error occurs.
*/
FileName parseURI(String uri) throws FileSystemException;
/**
* Locates a file replicator for the provider to use.
* @return The FileReplicator.
* @throws FileSystemException if an error occurs.
*/
FileReplicator getReplicator() throws FileSystemException;
/**
* Locates a temporary file store for the provider to use.
* @return The TemporaryFileStore.
* @throws FileSystemException if an error occurs.
*/
TemporaryFileStore getTemporaryFileStore() throws FileSystemException;
/**
* Returns a {@link FileObject} for a local file.
* @param file The File to convert to a FileObject.
* @return the FileObject.
* @throws FileSystemException if an error occurs.
*/
FileObject toFileObject(File file) throws FileSystemException;
/**
* Returns the filesystem manager for the current context.
*
* @return the filesystem manager
*/
FileSystemManager getFileSystemManager();
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/ExceptionConverter.java 100644 765 24 7136 11623215065 33061 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import java.lang.reflect.Constructor;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.xml.DomUtil;
import org.w3c.dom.Element;
/**
* ExceptionConverter
converts WebDAV exceptions into FileSystemExceptions.
* @author Commons VFS team
* @since 2.0
*/
public final class ExceptionConverter
{
// avoid instanciation
private ExceptionConverter()
{
}
public static FileSystemException generate(DavException davExc) throws FileSystemException
{
return generate(davExc, null);
}
public static FileSystemException generate(DavException davExc, DavMethod method)
throws FileSystemException
{
String msg = davExc.getMessage();
if (davExc.hasErrorCondition())
{
try
{
Element error = davExc.toXml(DomUtil.BUILDER_FACTORY.newDocumentBuilder().newDocument());
if (DomUtil.matches(error, DavException.XML_ERROR, DavConstants.NAMESPACE))
{
if (DomUtil.hasChildElement(error, "exception", null))
{
Element exc = DomUtil.getChildElement(error, "exception", null);
if (DomUtil.hasChildElement(exc, "message", null))
{
msg = DomUtil.getChildText(exc, "message", null);
}
if (DomUtil.hasChildElement(exc, "class", null))
{
Class> cl = Class.forName(DomUtil.getChildText(exc, "class", null));
Constructor> excConstr = cl.getConstructor(new Class[]{String.class});
if (excConstr != null)
{
Object o = excConstr.newInstance(new Object[]{msg});
if (o instanceof FileSystemException)
{
return (FileSystemException) o;
}
else if (o instanceof Exception)
{
return new FileSystemException(msg, (Exception) o);
}
}
}
}
}
}
catch (Exception e)
{
throw new FileSystemException(e);
}
}
return new FileSystemException(msg);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/package.html 100644 765 24 1534 11623215065 30645 0 ustar rgoers staff 0 0
The WebDAV File Provider
././@LongLink 100644 0 0 155 11623215455 10260 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileContentInfoFactory.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileContentInfoFact100644 765 24 5200 11623215065 33256 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileContentInfo;
import org.apache.commons.vfs2.FileContentInfoFactory;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.impl.DefaultFileContentInfo;
import org.apache.commons.vfs2.provider.URLFileName;
import org.apache.commons.vfs2.util.FileObjectUtils;
import org.apache.jackrabbit.webdav.property.DavProperty;
import org.apache.jackrabbit.webdav.property.DavPropertyName;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
/**
* Determines the content information for files accessed via WebDAV.
*
* @author Commons VFS team
* @since 2.0
*/
public class WebdavFileContentInfoFactory implements FileContentInfoFactory
{
public FileContentInfo create(FileContent fileContent) throws FileSystemException
{
WebdavFileObject file = (WebdavFileObject) (FileObjectUtils
.getAbstractFileObject(fileContent.getFile()));
String contentType = null;
String contentEncoding = null;
DavPropertyNameSet nameSet = new DavPropertyNameSet();
nameSet.add(DavPropertyName.GETCONTENTTYPE);
DavPropertySet propertySet = file.getProperties((URLFileName) file.getName(), nameSet, true);
DavProperty property = propertySet.get(DavPropertyName.GETCONTENTTYPE);
if (property != null)
{
contentType = (String) property.getValue();
}
property = propertySet.get(WebdavFileObject.RESPONSE_CHARSET);
if (property != null)
{
contentEncoding = (String) property.getValue();
}
return new DefaultFileContentInfo(contentType, contentEncoding);
}
}
././@LongLink 100644 0 0 145 11623215455 10257 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileNameParser.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileNameParser.java100644 765 24 2632 11623215065 33215 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import org.apache.commons.vfs2.provider.FileNameParser;
import org.apache.commons.vfs2.provider.http.HttpFileNameParser;
/**
* Implementation for http. set default port to 80
* @author Commons VFS team
* @since 2.0
*/
public class WebdavFileNameParser extends HttpFileNameParser
{
private static final WebdavFileNameParser INSTANCE = new WebdavFileNameParser();
public WebdavFileNameParser()
{
super();
}
public static FileNameParser getInstance()
{
return INSTANCE;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileObject.java 100644 765 24 65443 11623215065 32417 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodBase;
import org.apache.commons.httpclient.HttpStatus;
import org.apache.commons.httpclient.URIException;
import org.apache.commons.httpclient.methods.ByteArrayRequestEntity;
import org.apache.commons.httpclient.methods.RequestEntity;
import org.apache.commons.httpclient.params.HttpMethodParams;
import org.apache.commons.httpclient.util.DateUtil;
import org.apache.commons.vfs2.FileContentInfoFactory;
import org.apache.commons.vfs2.FileNotFolderException;
import org.apache.commons.vfs2.FileNotFoundException;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.DefaultFileContent;
import org.apache.commons.vfs2.provider.URLFileName;
import org.apache.commons.vfs2.provider.http.HttpFileObject;
import org.apache.commons.vfs2.util.FileObjectUtils;
import org.apache.commons.vfs2.util.MonitorOutputStream;
import org.apache.jackrabbit.webdav.DavConstants;
import org.apache.jackrabbit.webdav.DavException;
import org.apache.jackrabbit.webdav.MultiStatus;
import org.apache.jackrabbit.webdav.MultiStatusResponse;
import org.apache.jackrabbit.webdav.client.methods.CheckinMethod;
import org.apache.jackrabbit.webdav.client.methods.CheckoutMethod;
import org.apache.jackrabbit.webdav.client.methods.DavMethod;
import org.apache.jackrabbit.webdav.client.methods.DeleteMethod;
import org.apache.jackrabbit.webdav.client.methods.MkColMethod;
import org.apache.jackrabbit.webdav.client.methods.MoveMethod;
import org.apache.jackrabbit.webdav.client.methods.PropFindMethod;
import org.apache.jackrabbit.webdav.client.methods.PropPatchMethod;
import org.apache.jackrabbit.webdav.client.methods.PutMethod;
import org.apache.jackrabbit.webdav.client.methods.UncheckoutMethod;
import org.apache.jackrabbit.webdav.client.methods.VersionControlMethod;
import org.apache.jackrabbit.webdav.property.DavProperty;
import org.apache.jackrabbit.webdav.property.DavPropertyName;
import org.apache.jackrabbit.webdav.property.DavPropertyNameSet;
import org.apache.jackrabbit.webdav.property.DavPropertySet;
import org.apache.jackrabbit.webdav.property.DefaultDavProperty;
import org.apache.jackrabbit.webdav.version.DeltaVConstants;
import org.apache.jackrabbit.webdav.version.VersionControlledResource;
import org.apache.jackrabbit.webdav.xml.Namespace;
import org.w3c.dom.Node;
/**
* A WebDAV file.
*
* @author Commons VFS team
* @since 2.0
*/
public class WebdavFileObject extends HttpFileObject implements FileObject
{
/** The character set property name. */
public static final DavPropertyName RESPONSE_CHARSET = DavPropertyName.create(
"response-charset");
private final WebdavFileSystem fileSystem;
private final String urlCharset;
/** The FileSystemConfigBuilder */
private final WebdavFileSystemConfigBuilder builder;
protected WebdavFileObject(final AbstractFileName name, final WebdavFileSystem fileSystem)
{
super(name, fileSystem);
this.fileSystem = fileSystem;
builder = (WebdavFileSystemConfigBuilder) WebdavFileSystemConfigBuilder.getInstance();
this.urlCharset = builder.getUrlCharset(getFileSystem().getFileSystemOptions());
}
protected void configureMethod(HttpMethodBase httpMethod)
{
httpMethod.getParams().setParameter(HttpMethodParams.RETRY_HANDLER, WebdavMethodRetryHandler.getInstance());
}
/**
* Determines the type of this file. Must not return null. The return
* value of this method is cached, so the implementation can be expensive.
*/
@Override
protected FileType doGetType() throws Exception
{
try
{
return isDirectory((URLFileName) getName()) ? FileType.FOLDER : FileType.FILE;
}
catch (FileNotFolderException fnfe)
{
return FileType.IMAGINARY;
}
catch (FileNotFoundException fnfe)
{
return FileType.IMAGINARY;
}
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren() throws Exception
{
// use doListChildrenResolved for performance
return null;
}
/**
* Lists the children of the file.
*/
@Override
protected FileObject[] doListChildrenResolved() throws Exception
{
PropFindMethod method = null;
try
{
URLFileName name = (URLFileName) getName();
if (isDirectory(name))
{
DavPropertyNameSet nameSet = new DavPropertyNameSet();
nameSet.add(DavPropertyName.create(DavConstants.PROPERTY_DISPLAYNAME));
method = new PropFindMethod(urlString(name), nameSet,
DavConstants.DEPTH_1);
execute(method);
List vfs = new ArrayList();
if (method.succeeded())
{
MultiStatusResponse[] responses =
method.getResponseBodyAsMultiStatus().getResponses();
for (int i = 0; i < responses.length; ++i)
{
MultiStatusResponse response = responses[i];
if (isCurrentFile(response.getHref(), name))
{
continue;
}
String resourceName = resourceName(response.getHref());
if (resourceName != null && resourceName.length() > 0)
{
WebdavFileObject fo = (WebdavFileObject) FileObjectUtils.
getAbstractFileObject(getFileSystem().resolveFile(
getFileSystem().getFileSystemManager().
resolveName(getName(), resourceName,
NameScope.CHILD)));
vfs.add(fo);
}
}
}
return vfs.toArray(new WebdavFileObject[vfs.size()]);
}
throw new FileNotFolderException(getName());
}
catch (FileNotFolderException fnfe)
{
throw fnfe;
}
catch (DavException e)
{
throw new FileSystemException(e.getMessage(), e);
}
catch (IOException e)
{
throw new FileSystemException(e.getMessage(), e);
}
finally
{
if (method != null)
{
method.releaseConnection();
}
}
}
/**
* Creates this file as a folder.
*/
@Override
protected void doCreateFolder() throws Exception
{
DavMethod method = new MkColMethod(urlString((URLFileName) getName()));
setupMethod(method);
try
{
execute(method);
}
catch (FileSystemException fse)
{
throw new FileSystemException("vfs.provider.webdav/create-collection.error", getName(),
fse);
}
}
/**
* Deletes the file.
*/
@Override
protected void doDelete() throws Exception
{
DavMethod method = new DeleteMethod(urlString((URLFileName) getName()));
setupMethod(method);
execute(method);
}
/**
* Rename the file.
*/
@Override
protected void doRename(FileObject newfile) throws Exception
{
String url = encodePath(urlString((URLFileName) getName()));
String dest = urlString((URLFileName) newfile.getName(), false);
DavMethod method = new MoveMethod(url, dest, false);
setupMethod(method);
execute(method);
}
/**
* Returns the size of the file content (in bytes).
*/
@Override
protected long doGetContentSize() throws Exception
{
DavProperty property = getProperty((URLFileName) getName(),
DavConstants.PROPERTY_GETCONTENTLENGTH);
if (property != null)
{
String value = (String) property.getValue();
return Long.parseLong(value);
}
return 0;
}
/**
* Returns the last modified time of this file. Is only called if
* {@link #doGetType} does not return {@link FileType#IMAGINARY}.
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
DavProperty property = getProperty((URLFileName) getName(),
DavConstants.PROPERTY_GETLASTMODIFIED);
if (property != null)
{
String value = (String) property.getValue();
return DateUtil.parseDate(value).getTime();
}
return 0;
}
/**
* Returns the properties of the Webdav resource.
*/
@Override
protected Map doGetAttributes() throws Exception
{
final Map attributes = new HashMap();
try
{
URLFileName fileName = (URLFileName) getName();
DavPropertySet properties = getProperties(fileName, PropFindMethod.PROPFIND_ALL_PROP,
new DavPropertyNameSet(), false);
@SuppressWarnings("unchecked") // iterator() is documented to return DavProperty instances
Iterator iter = properties.iterator();
while (iter.hasNext())
{
DavProperty property = iter.next();
attributes.put(property.getName().toString(), property.getValue());
}
properties = getPropertyNames(fileName);
@SuppressWarnings("unchecked") // iterator() is documented to return DavProperty instances
Iterator iter2 = properties.iterator();
while (iter2.hasNext())
{
DavProperty property = iter2.next();
if (!attributes.containsKey(property.getName().getName()))
{
property = getProperty(fileName, property.getName());
if (property != null)
{
Object name = property.getName();
Object value = property.getValue();
if (name != null && value != null)
{
attributes.put(name.toString(), value);
}
}
}
}
return attributes;
}
catch (Exception e)
{
throw new FileSystemException("vfs.provider.webdav/propfind.error", getName(), e);
}
}
/**
* Sets an attribute of this file. Is only called if {@link #doGetType}
* does not return {@link FileType#IMAGINARY}.
*
* This implementation throws an exception.
*/
@Override
protected void doSetAttribute(final String attrName, final Object value)
throws Exception
{
try
{
URLFileName fileName = (URLFileName) getName();
String urlStr = urlString(fileName);
DavPropertySet properties = new DavPropertySet();
DavPropertyNameSet propertyNameSet = new DavPropertyNameSet();
DavProperty property = new DefaultDavProperty(attrName, value, Namespace.EMPTY_NAMESPACE);
if (value != null)
{
properties.add(property);
}
else
{
propertyNameSet.add(property.getName()); // remove property
}
PropPatchMethod method = new PropPatchMethod(urlStr, properties, propertyNameSet);
setupMethod(method);
execute(method);
if (!method.succeeded())
{
throw new FileSystemException("Property '" + attrName + "' could not be set.");
}
}
catch (FileSystemException fse)
{
throw fse;
}
catch (Exception e)
{
throw new FileSystemException("vfs.provider.webdav/propfind.error", getName(), e);
}
}
@Override
protected OutputStream doGetOutputStream(boolean bAppend) throws Exception
{
return new WebdavOutputStream(this);
}
@Override
protected FileContentInfoFactory getFileContentInfoFactory()
{
return new WebdavFileContentInfoFactory();
}
/**
* Prepares a Method object.
*
* @param method the HttpMethod.
* @throws FileSystemException if an error occurs encoding the uri.
* @throws URIException if the URI is in error.
*/
@Override
protected void setupMethod(final HttpMethod method) throws FileSystemException, URIException
{
String pathEncoded = ((URLFileName) getName()).getPathQueryEncoded(urlCharset);
method.setPath(pathEncoded);
// All the WebDav methods are EntityEnclosingMethods and are not allowed to redirect.
method.setFollowRedirects(false);
method.setRequestHeader("User-Agent", "Jakarta-Commons-VFS");
method.addRequestHeader("Cache-control", "no-cache");
method.addRequestHeader("Cache-store", "no-store");
method.addRequestHeader("Pragma", "no-cache");
method.addRequestHeader("Expires", "0");
}
/**
* Execute a 'Workspace' operation.
*
* @param method The DavMethod to invoke.
* @throws FileSystemException If an error occurs.
*/
private void execute(DavMethod method) throws FileSystemException
{
try
{
int status = fileSystem.getClient().executeMethod(method);
if (status == HttpURLConnection.HTTP_NOT_FOUND
|| status == HttpURLConnection.HTTP_GONE)
{
throw new FileNotFoundException(method.getURI());
}
method.checkSuccess();
}
catch (FileSystemException fse)
{
throw fse;
}
catch (IOException e)
{
throw new FileSystemException(e);
}
catch (DavException e)
{
throw ExceptionConverter.generate(e);
}
finally
{
if (method != null)
{
method.releaseConnection();
}
}
}
private boolean isDirectory(URLFileName name) throws IOException
{
try
{
DavProperty property = getProperty(name, DavConstants.PROPERTY_RESOURCETYPE);
Node node;
if (property != null && (node = (Node) property.getValue()) != null)
{
return node.getLocalName().equals(DavConstants.XML_COLLECTION);
}
else
{
return false;
}
}
catch (FileNotFoundException fse)
{
throw new FileNotFolderException(name);
}
}
DavProperty getProperty(URLFileName fileName, String property)
throws FileSystemException
{
return getProperty(fileName, DavPropertyName.create(property));
}
DavProperty getProperty(URLFileName fileName, DavPropertyName name)
throws FileSystemException
{
DavPropertyNameSet nameSet = new DavPropertyNameSet();
nameSet.add(name);
DavPropertySet propertySet = getProperties(fileName, nameSet, false);
return propertySet.get(name);
}
DavPropertySet getProperties(URLFileName name, DavPropertyNameSet nameSet, boolean addEncoding)
throws FileSystemException
{
return getProperties(name, PropFindMethod.PROPFIND_BY_PROPERTY, nameSet, addEncoding);
}
DavPropertySet getProperties(URLFileName name) throws FileSystemException
{
return getProperties(name, PropFindMethod.PROPFIND_ALL_PROP, new DavPropertyNameSet(),
false);
}
DavPropertySet getPropertyNames(URLFileName name) throws FileSystemException
{
return getProperties(name, PropFindMethod.PROPFIND_PROPERTY_NAMES,
new DavPropertyNameSet(), false);
}
DavPropertySet getProperties(URLFileName name, int type, DavPropertyNameSet nameSet,
boolean addEncoding)
throws FileSystemException
{
try
{
String urlStr = urlString(name);
PropFindMethod method = new PropFindMethod(urlStr, type, nameSet, DavConstants.DEPTH_0);
setupMethod(method);
execute(method);
if (method.succeeded())
{
MultiStatus multiStatus = method.getResponseBodyAsMultiStatus();
MultiStatusResponse response = multiStatus.getResponses()[0];
DavPropertySet props = response.getProperties(HttpStatus.SC_OK);
if (addEncoding)
{
DavProperty prop = new DefaultDavProperty(RESPONSE_CHARSET,
method.getResponseCharSet());
props.add(prop);
}
return props;
}
return new DavPropertySet();
}
catch (FileSystemException fse)
{
throw fse;
}
catch (Exception e)
{
throw new FileSystemException("vfs.provider.webdav/propfind.error", getName(), e);
}
}
/**
* Returns the resource name from the path.
*
* @param path the path to the file.
* @return The resource name
*/
private String resourceName(String path)
{
if (path.endsWith("/"))
{
path = path.substring(0, path.length() - 1);
}
final int i = path.lastIndexOf("/");
return (i >= 0) ? path.substring(i + 1) : path;
}
private String urlString(URLFileName name)
{
return urlString(name, true);
}
/**
* Convert the FileName to an encoded url String.
*
* @param name The FileName.
* @param includeUserInfo true if user information should be included.
* @return The encoded URL String.
*/
private String urlString(URLFileName name, boolean includeUserInfo)
{
String user = null;
String password = null;
if (includeUserInfo)
{
user = name.getUserName();
password = name.getPassword();
}
URLFileName newFile = new URLFileName("http", name.getHostName(), name.getPort(),
name.getDefaultPort(), user, password,
name.getPath(), name.getType(), name.getQueryString());
try
{
return newFile.getURIEncoded(urlCharset);
}
catch (Exception e)
{
return name.getURI();
}
}
private boolean isCurrentFile(String href, URLFileName fileName)
{
String name = hrefString(fileName);
if (href.endsWith("/") && !name.endsWith("/"))
{
name += "/";
}
return href.equals(name);
}
/**
* Convert the FileName to an encoded url String.
*
* @param name The FileName.
* @return The encoded URL String.
*/
private String hrefString(URLFileName name)
{
URLFileName newFile = new URLFileName("http", name.getHostName(), name.getPort(),
name.getDefaultPort(), null, null,
name.getPath(), name.getType(), name.getQueryString());
try
{
return newFile.getURIEncoded(urlCharset);
}
catch (Exception e)
{
return name.getURI();
}
}
/**
* An OutputStream that writes to a Webdav resource.
*
* @todo Use piped stream to avoid temporary file
*/
private class WebdavOutputStream extends MonitorOutputStream
{
private WebdavFileObject file;
public WebdavOutputStream(WebdavFileObject file)
{
super(new ByteArrayOutputStream());
this.file = file;
}
/**
* Called after this stream is closed.
*/
@Override
protected void onClose() throws IOException
{
RequestEntity entity = new ByteArrayRequestEntity(((ByteArrayOutputStream) out).toByteArray());
URLFileName fileName = (URLFileName) getName();
String urlStr = urlString(fileName);
if (builder.isVersioning(getFileSystem().getFileSystemOptions()))
{
DavPropertySet set = null;
boolean fileExists = true;
boolean isCheckedIn = true;
try
{
set = getPropertyNames(fileName);
}
catch (FileNotFoundException fnfe)
{
fileExists = false;
}
if (fileExists && set != null)
{
if (set.contains(VersionControlledResource.CHECKED_OUT))
{
isCheckedIn = false;
}
else if (!set.contains(VersionControlledResource.CHECKED_IN))
{
DavProperty prop = set.get(VersionControlledResource.AUTO_VERSION);
if (prop != null)
{
prop = getProperty(fileName, VersionControlledResource.AUTO_VERSION);
if (DeltaVConstants.XML_CHECKOUT_CHECKIN.equals(prop.getValue()))
{
createVersion(urlStr);
}
}
}
}
if (fileExists && isCheckedIn)
{
try
{
CheckoutMethod checkout = new CheckoutMethod(urlStr);
setupMethod(checkout);
execute(checkout);
isCheckedIn = false;
}
catch (FileSystemException ex)
{
// Ignore the exception checking out.
}
}
try
{
PutMethod method = new PutMethod(urlStr);
method.setRequestEntity(entity);
setupMethod(method);
execute(method);
setUserName(fileName, urlStr);
}
catch (FileSystemException ex)
{
if (!isCheckedIn)
{
try
{
UncheckoutMethod method = new UncheckoutMethod(urlStr);
setupMethod(method);
execute(method);
isCheckedIn = true;
}
catch (Exception e)
{
// Ignore the exception. Going to throw original.
}
throw ex;
}
}
if (!fileExists)
{
createVersion(urlStr);
try
{
DavPropertySet props = getPropertyNames(fileName);
isCheckedIn = !props.contains(VersionControlledResource.CHECKED_OUT);
}
catch (FileNotFoundException fnfe)
{
// Ignore the error
}
}
if (!isCheckedIn)
{
CheckinMethod checkin = new CheckinMethod(urlStr);
setupMethod(checkin);
execute(checkin);
}
}
else
{
PutMethod method = new PutMethod(urlStr);
method.setRequestEntity(entity);
setupMethod(method);
execute(method);
try
{
setUserName(fileName, urlStr);
}
catch (IOException e)
{
// Ignore the exception if unable to set the user name.
}
}
((DefaultFileContent) this.file.getContent()).resetAttributes();
}
private void setUserName(URLFileName fileName, String urlStr)
throws IOException
{
List list = new ArrayList();
String name = builder.getCreatorName(getFileSystem().getFileSystemOptions());
String userName = fileName.getUserName();
if (name == null)
{
name = userName;
}
else
{
if (userName != null)
{
String comment = "Modified by user " + userName;
list.add(new DefaultDavProperty(DeltaVConstants.COMMENT, comment));
}
}
list.add(new DefaultDavProperty(DeltaVConstants.CREATOR_DISPLAYNAME, name));
PropPatchMethod method = new PropPatchMethod(urlStr, list);
setupMethod(method);
execute(method);
}
private boolean createVersion(String urlStr)
{
try
{
VersionControlMethod method = new VersionControlMethod(urlStr);
setupMethod(method);
execute(method);
return true;
}
catch (Exception ex)
{
return false;
}
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileProvider.java 100644 765 24 11626 11623215065 32775 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.UserAuthenticationData;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.provider.http.HttpClientFactory;
import org.apache.commons.vfs2.provider.http.HttpFileProvider;
import org.apache.commons.vfs2.util.UserAuthenticatorUtils;
/**
* A provider for WebDAV.
*
* @author Commons VFS team
* @since 2.0
*/
public class WebdavFileProvider
extends HttpFileProvider
{
/** The authenticator types used by the WebDAV provider. */
public static final UserAuthenticationData.Type[] AUTHENTICATOR_TYPES = new UserAuthenticationData.Type[]
{
UserAuthenticationData.USERNAME, UserAuthenticationData.PASSWORD
};
/** The capabilities of the WebDAV provider */
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.CREATE,
Capability.DELETE,
Capability.RENAME,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.URI,
Capability.WRITE_CONTENT,
Capability.GET_LAST_MODIFIED,
Capability.ATTRIBUTES,
Capability.RANDOM_ACCESS_READ,
Capability.DIRECTORY_READ_CONTENT,
}));
public WebdavFileProvider()
{
super();
setFileNameParser(WebdavFileNameParser.getInstance());
}
/**
* Creates a {@link FileSystem}. If you're looking at this method and wondering how to
* get a FileSystemOptions object bearing the proxy host and credentials configuration through
* to this method so it's used for resolving a {@link FileObject} in the FileSystem, then be sure
* to use correct signature of the {@link FileSystemManager} resolveFile method.
* @see org.apache.commons.vfs2.impl.DefaultFileSystemManager#resolveFile(FileObject, String, FileSystemOptions)
*/
@Override
protected FileSystem doCreateFileSystem(final FileName name, final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
// Create the file system
final GenericFileName rootName = (GenericFileName) name;
FileSystemOptions fsOpts = (fileSystemOptions == null) ? new FileSystemOptions() : fileSystemOptions;
UserAuthenticationData authData = null;
HttpClient httpClient;
try
{
authData = UserAuthenticatorUtils.authenticate(fsOpts, AUTHENTICATOR_TYPES);
httpClient = HttpClientFactory.createConnection(
WebdavFileSystemConfigBuilder.getInstance(),
"http",
rootName.getHostName(),
rootName.getPort(),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.USERNAME, UserAuthenticatorUtils.toChar(rootName.getUserName()))),
UserAuthenticatorUtils.toString(UserAuthenticatorUtils.getData(authData,
UserAuthenticationData.PASSWORD, UserAuthenticatorUtils.toChar(rootName.getPassword()))),
fsOpts);
}
finally
{
UserAuthenticatorUtils.cleanup(authData);
}
return new WebdavFileSystem(rootName, httpClient, fsOpts);
}
@Override
public FileSystemConfigBuilder getConfigBuilder()
{
return WebdavFileSystemConfigBuilder.getInstance();
}
@Override
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystem.java 100644 765 24 5275 11623215065 32452 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import java.net.URLStreamHandler;
import java.util.Collection;
import org.apache.commons.httpclient.HttpClient;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.DefaultURLStreamHandler;
import org.apache.commons.vfs2.provider.GenericFileName;
import org.apache.commons.vfs2.provider.http.HttpFileSystem;
/**
* A WebDAV file system.
*
* @author Commons VFS team
* @since 2.0
*/
public class WebdavFileSystem extends HttpFileSystem implements FileSystem
{
protected WebdavFileSystem(final GenericFileName rootName, final HttpClient client,
final FileSystemOptions fileSystemOptions)
{
super(rootName, client, fileSystemOptions);
}
@Override
protected HttpClient getClient()
{
return super.getClient();
}
/**
* Returns the capabilities of this file system.
* @caps The Capabilities to add.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(WebdavFileProvider.capabilities);
}
/**
* Creates a file object. This method is called only if the requested
* file is not cached.
* @param name the FileName.
* @return The created FileObject.
*/
@Override
protected FileObject createFile(final AbstractFileName name)
{
return new WebdavFileObject(name, this);
}
/**
* Return a URLStreamHandler.
* @return The URLStreamHandler.
*/
public URLStreamHandler getURLStreamHandler()
{
return new DefaultURLStreamHandler(getContext(), getFileSystemOptions());
}
}
././@LongLink 100644 0 0 156 11623215455 10261 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystemConfigBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavFileSystemConfigBui100644 765 24 5560 11623215065 33315 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.provider.http.HttpFileSystemConfigBuilder;
/**
* Configuration options for WebDav.
*
* @author Commons VFS team
* @since 2.0
*/
public final class WebdavFileSystemConfigBuilder extends HttpFileSystemConfigBuilder
{
private static final WebdavFileSystemConfigBuilder BUILDER = new WebdavFileSystemConfigBuilder();
private WebdavFileSystemConfigBuilder()
{
super("webdav.");
}
public static HttpFileSystemConfigBuilder getInstance()
{
return BUILDER;
}
/**
* The user name to be associated with changes to the file.
* @param opts The FileSystem options
* @param creatorName The creator name to be associated with the file.
*/
public void setCreatorName(FileSystemOptions opts, String creatorName)
{
setParam(opts, "creatorName", creatorName);
}
/**
* Return the user name to be associated with changes to the file.
* @param opts The FileSystem options
* @return The creatorName.
*/
public String getCreatorName(FileSystemOptions opts)
{
return getString(opts, "creatorName");
}
/**
* Whether to use versioning.
* @param opts The FileSystem options.
* @param versioning true if versioning should be enabled.
*/
public void setVersioning(FileSystemOptions opts, boolean versioning)
{
setParam(opts, "versioning", Boolean.valueOf(versioning));
}
/**
* The cookies to add to the request.
* @param opts The FileSystem options.
* @return true if versioning is enabled.
*/
public boolean isVersioning(FileSystemOptions opts)
{
return getBoolean(opts, "versioning", false);
}
/**
* @return The Webdav FileSystem Class object.
*/
@Override
protected Class extends FileSystem> getConfigClass()
{
return WebdavFileSystem.class;
}
}
././@LongLink 100644 0 0 151 11623215455 10254 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavMethodRetryHandler.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/webdav/WebdavMethodRetryHandler.100644 765 24 3327 11623215065 33264 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.webdav;
import java.io.IOException;
import org.apache.commons.httpclient.HttpMethod;
import org.apache.commons.httpclient.HttpMethodRetryHandler;
/**
* A retry handler which will retry a failed webdav method one time.
* Now that webdavlib didnt support adding a MethodRetryHandler only a few operations are restartable yet.
*
* @author Commons VFS team
* @since 2.0
*/
public final class WebdavMethodRetryHandler implements HttpMethodRetryHandler
{
private static final WebdavMethodRetryHandler INSTANCE = new WebdavMethodRetryHandler();
private WebdavMethodRetryHandler()
{
}
public static WebdavMethodRetryHandler getInstance()
{
return INSTANCE;
}
public boolean retryMethod(HttpMethod method, IOException exception, int executionCount)
{
return executionCount < 2;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/zip/package.html 100644 765 24 1540 11623215065 30174 0 ustar rgoers staff 0 0
The Zip File Provider.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileObject.java 100644 765 24 11271 11623215065 31271 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.zip;
import java.io.InputStream;
import java.util.HashSet;
import java.util.zip.ZipEntry;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileObject;
/**
* A file in a Zip file system.
*
* @author Commons VFS team
*/
public class ZipFileObject extends AbstractFileObject implements FileObject
{
/** The ZipEntry. */
protected ZipEntry entry;
private final HashSet children = new HashSet();
private final ZipFileSystem fs;
// protected final ZipFile file;
private FileType type;
protected ZipFileObject(AbstractFileName name,
ZipEntry entry,
ZipFileSystem fs,
boolean zipExists) throws FileSystemException
{
super(name, fs);
this.fs = fs;
setZipEntry(entry);
if (!zipExists)
{
type = FileType.IMAGINARY;
}
}
/**
* Sets the details for this file object.
*/
protected void setZipEntry(final ZipEntry entry)
{
if (this.entry != null)
{
return;
}
if ((entry == null) || (entry.isDirectory()))
{
type = FileType.FOLDER;
}
else
{
type = FileType.FILE;
}
this.entry = entry;
}
/**
* Attaches a child.
* @param childName The name of the child.
*/
public void attachChild(FileName childName)
{
children.add(childName.getBaseName());
}
/**
* Determines if this file can be written to.
*
* @return true
if this file is writeable, false
if not.
* @throws FileSystemException if an error occurs.
*/
@Override
public boolean isWriteable() throws FileSystemException
{
return false;
}
/**
* Returns the file's type.
*/
@Override
protected FileType doGetType()
{
return type;
}
/**
* Lists the children of the file.
*/
@Override
protected String[] doListChildren()
{
try
{
if (!getType().hasChildren())
{
return null;
}
}
catch (FileSystemException e)
{
// should not happen as the type has already been cached.
throw new RuntimeException(e);
}
return children.toArray(new String[children.size()]);
}
/**
* Returns the size of the file content (in bytes). Is only called if
* {@link #doGetType} returns {@link FileType#FILE}.
*/
@Override
protected long doGetContentSize()
{
return entry.getSize();
}
/**
* Returns the last modified time of this file.
*/
@Override
protected long doGetLastModifiedTime() throws Exception
{
return entry.getTime();
}
/**
* Creates an input stream to read the file content from. Is only called
* if {@link #doGetType} returns {@link FileType#FILE}. The input stream
* returned by this method is guaranteed to be closed before this
* method is called again.
*/
@Override
protected InputStream doGetInputStream() throws Exception
{
// VFS-210: zip allows to gather an input stream even from a directory and will
// return -1 on the first read. getType should not be expensive and keeps the tests
// running
if (!getType().hasContent())
{
throw new FileSystemException("vfs.provider/read-not-file.error", getName());
}
return fs.getZipFile().getInputStream(entry);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileProvider.java 100644 765 24 6054 11623215065 31640 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.zip;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractLayeredFileProvider;
import org.apache.commons.vfs2.provider.FileProvider;
import org.apache.commons.vfs2.provider.LayeredFileName;
/**
* A file system provider for Zip files. Provides read-only file systems.
*
* @author Commons VFS team
*/
public class ZipFileProvider extends AbstractLayeredFileProvider implements FileProvider
{
/** The list of capabilities this provider supports */
protected static final Collection capabilities =
Collections.unmodifiableCollection(Arrays.asList(new Capability[]
{
Capability.GET_LAST_MODIFIED,
Capability.GET_TYPE,
Capability.LIST_CHILDREN,
Capability.READ_CONTENT,
Capability.URI,
Capability.COMPRESS,
Capability.VIRTUAL
}));
public ZipFileProvider()
{
super();
}
/**
* Creates a layered file system. This method is called if the file system
* is not cached.
*
* @param scheme The URI scheme.
* @param file The file to create the file system on top of.
* @return The file system.
*/
@Override
protected FileSystem doCreateFileSystem(final String scheme,
final FileObject file,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
final AbstractFileName rootName =
new LayeredFileName(scheme, file.getName(), FileName.ROOT_PATH, FileType.FOLDER);
return new ZipFileSystem(rootName, file, fileSystemOptions);
}
public Collection getCapabilities()
{
return capabilities;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/provider/zip/ZipFileSystem.java 100644 765 24 15172 11623215065 31353 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.provider.zip;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Enumeration;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystem;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.VfsLog;
import org.apache.commons.vfs2.provider.AbstractFileName;
import org.apache.commons.vfs2.provider.AbstractFileSystem;
import org.apache.commons.vfs2.provider.UriParser;
/**
* A read-only file system for Zip/Jar files.
*
* @author Commons VFS team
*/
public class ZipFileSystem extends AbstractFileSystem implements FileSystem
{
private static final Log LOG = LogFactory.getLog(ZipFileSystem.class);
private final File file;
private ZipFile zipFile;
public ZipFileSystem(final AbstractFileName rootName,
final FileObject parentLayer,
final FileSystemOptions fileSystemOptions)
throws FileSystemException
{
super(rootName, parentLayer, fileSystemOptions);
// Make a local copy of the file
file = parentLayer.getFileSystem().replicateFile(parentLayer, Selectors.SELECT_SELF);
// Open the Zip file
if (!file.exists())
{
// Don't need to do anything
zipFile = null;
return;
}
// zipFile = createZipFile(this.file);
}
@Override
public void init() throws FileSystemException
{
super.init();
try
{
// Build the index
List strongRef = new ArrayList(100);
Enumeration extends ZipEntry> entries = getZipFile().entries();
while (entries.hasMoreElements())
{
ZipEntry entry = entries.nextElement();
AbstractFileName name = (AbstractFileName) getFileSystemManager().resolveName(getRootName(),
UriParser.encode(entry.getName()));
// Create the file
ZipFileObject fileObj;
if (entry.isDirectory() && getFileFromCache(name) != null)
{
fileObj = (ZipFileObject) getFileFromCache(name);
fileObj.setZipEntry(entry);
continue;
}
fileObj = createZipFileObject(name, entry);
putFileToCache(fileObj);
strongRef.add(fileObj);
fileObj.holdObject(strongRef);
// Make sure all ancestors exist
// TODO - create these on demand
ZipFileObject parent;
for (AbstractFileName parentName = (AbstractFileName) name.getParent();
parentName != null;
fileObj = parent, parentName = (AbstractFileName) parentName.getParent())
{
// Locate the parent
parent = (ZipFileObject) getFileFromCache(parentName);
if (parent == null)
{
parent = createZipFileObject(parentName, null);
putFileToCache(parent);
strongRef.add(parent);
parent.holdObject(strongRef);
}
// Attach child to parent
parent.attachChild(fileObj.getName());
}
}
}
finally
{
closeCommunicationLink();
}
}
protected ZipFile getZipFile() throws FileSystemException
{
if (zipFile == null && this.file.exists())
{
ZipFile zipFile = createZipFile(this.file);
this.zipFile = zipFile;
}
return zipFile;
}
protected ZipFileObject createZipFileObject(final AbstractFileName name,
final ZipEntry entry) throws FileSystemException
{
return new ZipFileObject(name, entry, this, true);
}
protected ZipFile createZipFile(final File file) throws FileSystemException
{
try
{
return new ZipFile(file);
}
catch (IOException ioe)
{
throw new FileSystemException("vfs.provider.zip/open-zip-file.error", file, ioe);
}
}
@Override
protected void doCloseCommunicationLink()
{
// Release the zip file
try
{
if (zipFile != null)
{
zipFile.close();
zipFile = null;
}
}
catch (final IOException e)
{
// getLogger().warn("vfs.provider.zip/close-zip-file.error :" + file, e);
VfsLog.warn(getLogger(), LOG, "vfs.provider.zip/close-zip-file.error :" + file, e);
}
}
/**
* Returns the capabilities of this file system.
*/
@Override
protected void addCapabilities(final Collection caps)
{
caps.addAll(ZipFileProvider.capabilities);
}
/**
* Creates a file object.
*/
@Override
protected FileObject createFile(final AbstractFileName name) throws FileSystemException
{
// This is only called for files which do not exist in the Zip file
return new ZipFileObject(name, null, this, false);
}
/**
* will be called after all file-objects closed their streams.
protected void notifyAllStreamsClosed()
{
closeCommunicationLink();
}
*/
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/RandomAccessContent.java 100644 765 24 6270 11623215066 30025 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import java.io.InputStream;
/**
* Random Access Content.
*
* @author Commons VFS team
*/
public interface RandomAccessContent extends DataOutput, DataInput
{
/**
* Returns the current offset in this file.
*
* @return the offset from the beginning of the file, in bytes,
* at which the next read or write occurs.
* @throws IOException if an I/O error occurs.
*/
long getFilePointer() throws IOException;
/**
* Sets the file-pointer offset, measured from the beginning of this
* file, at which the next read or write occurs. The offset may be
* set beyond the end of the file. Setting the offset beyond the end
* of the file does not change the file length. The file length will
* change only by writing after the offset has been set beyond the end
* of the file.
*
* Notice: If you use {@link #getInputStream()} you have to reget the InputStream after
* calling {@link #seek(long)}
*
* @param pos the offset position, measured in bytes from the
* beginning of the file, at which to set the file
* pointer.
* @throws IOException if pos
is less than
* 0
or if an I/O error occurs.
*/
void seek(long pos) throws IOException;
/**
* Returns the length of this file.
*
* @return the length of this file, measured in bytes.
* @throws IOException if an I/O error occurs.
*/
long length() throws IOException;
/**
* Closes this random access file stream and releases any system
* resources associated with the stream. A closed random access
* file cannot perform input or output operations and cannot be
* reopened.
*
* If this file has an associated channel then the channel is closed
* as well.
*
* @throws IOException if an I/O error occurs.
*/
void close() throws IOException;
/**
* Get the input stream.
*
* Notice: If you use {@link #seek(long)} you have to reget the InputStream
* @return the InputStream.
* @throws IOException if an I/O error occurs.
*/
InputStream getInputStream() throws IOException;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/Resources.properties 100644 765 24 45235 11623215066 27401 0 ustar rgoers staff 0 0 # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
# $Id: Resources.properties 1034665 2010-11-13 05:50:50Z rgoers $
# Factory
vfs/create-manager.error=Could not create a file system manager of class "{0}".
# AbstractFileObject
vfs.provider/delete-not-supported.error=This file type does not support delete.
vfs.provider/rename-not-supported.error=This file type does not support rename.
vfs.provider/write-append-not-supported.error=The file type does not support append mode.
vfs.provider/random-access-not-supported.error=The file type does not support random access.
vfs.provider/random-access-read-not-supported.error=The file type does not support read in random access mode.
vfs.provider/random-access-write-not-supported.error=The file type does not support write in random access mode.
vfs.provider/create-folder-not-supported.error=This file type does not support folder creation.
vfs.provider/get-last-modified-not-supported.error=This file type does not support retriving last modified time.
vfs.provider/set-last-modified-not-supported.error=This file type does not support setting last modified time.
vfs.provider/set-attribute-not-supported.error=This file type does not support setting attributes.
vfs.provider/remove-attribute-not-supported.error=This file type does not support removing attributes.
vfs.provider/get-attribute-not-supported.error=This file type does not support getting attributes.
vfs.provider/write-not-supported.error=This file type cannot be written to.
vfs.provider/get-type.error=Could not determine the type of file "{0}".
vfs.provider/list-children-not-folder.error=Could not list the contents of "{0}" because it is not a folder.
vfs.provider/list-children.error=Could not list the contents of folder "{0}".
vfs.provider/delete-read-only.error=Could not delete "{0}" because it is read-only.
vfs.provider/rename-read-only.error=Could not rename "{0}" because it is read-only.
vfs.provider/rename-parent-read-only.error=Could not rename "{0}" because "{1}" is read-only.
vfs.provider/rename-dest-exists.error=Destination "{0}" already existent.
vfs.provider/delete.error=Could not delete "{0}".
vfs.provider/rename.error=Could not rename "{0}" to "{1}".
vfs.provider/create-folder-mismatched-type.error=Could not create folder "{0}" because it already exists and is a file.
vfs.provider/create-folder-read-only.error=Could not create folder "{0}" because its parent folder is read-only.
vfs.provider/create-folder.error=Could not create folder "{0}".
vfs.provider/create-file.error=Could not create file "{0}".
vfs.provider/write-read-only.error=Could not write to "{0}" because it is read-only.
vfs.provider/write-not-file.error=Could not write to "{0}" because it is not a file.
vfs.provider/write.error=Could not write to "{0}".
vfs.provider/copy-file.error=Could not copy "{0}" to "{1}".
vfs.provider/rename-filename.error=You can only rename within the same folder. Invalid Filename: "{0}".
vfs.provider/copy-read-only.error=Could not copy {0} "{1}" to "{2}" because the destination file is read-only.
vfs.provider/copy-missing-file.error=Could not copy "{0}" because it does not exist.
vfs.provider/find-files.error=Could not find files in "{0}".
vfs.provider/check-is-hidden.error=Could not determine if file "{0}" is hidden.
vfs.provider/check-is-writeable.error=Could not determine if file "{0}" is writeable.
vfs.provider/check-is-readable.error=Could not determine if file "{0}" is readable.
vfs.provider/get-url.error=Could not create URL for "{0}".
vfs.provider/resync.error=Could not resync "{0}".
vfs.provider/close.error=Could not close "{0}".
vfs.provider/read.error=Could not read file "{0}".
vfs.provider/random-access.error=Could not read/write file "{0}".
vfs.provider/read-not-readable.error=File "{0}" is not readable.
vfs.provider/read-not-file.error=Could not read from "{0}" because it is a not a file.
vfs.provider/closed.error=File closed.
# DefaultFileContent
vfs.provider/get-size-not-file.error=Could not determine the size of "{0}" because it is not a file.
vfs.provider/get-size-write.error=Could not determine the size of file "{0}" because it is being written to.
vfs.provider/get-size.error=Could not determine the size of file "{0}".
vfs.provider/read-in-use.error=Could not read file "{0}" because it is currently being written to.
vfs.provider/write-in-use.error=Could not write to "{0}" because it is currently in use.
vfs.provider/random-in-use.error=Could not read/write file "{0}" because it is currently in use.
vfs.provider/get-last-modified-writing.error=Could not determine the last modified timestamp of "{0}" because it is being written to.
vfs.provider/get-last-modified-no-exist.error=Could not determine the last modified timestamp of "{0}" because it does not exist.
vfs.provider/get-last-modified.error=Could not determine the last modified timestamp of "{0}".
vfs.provider/set-last-modified-writing.error=Could not set the last modified timestamp of "{0}" because it is being written to.
vfs.provider/set-last-modified-no-exist.error=Could not set the last modified timestamp of "{0}" because it does not exist.
vfs.provider/set-last-modified.error=Could not set the last modified timestamp of "{0}".
vfs.provider/get-certificates-no-exist.error=Could not retrieve the certificates of "{0}" because it does not exist.
vfs.provider/get-certificates-writing.error=Could not retrieve the certificates of "{0}" because it is being written to.
vfs.provider/get-certificates.error=Could not retrieve the certificates of "{0}".
vfs.provider/close-instr.error=Could not close the input stream for file "{0}".
vfs.provider/close-outstr.error=Could not close the output stream for file "{0}".
vfs.provider/exists-attribute-no-exist.error=Could not check if attribute "{0}" of "{1}" exists because attributes are not supported.
vfs.provider/get-attributes-no-exist.error=Could not get attributes for file "{0}" because it does not exist.
vfs.provider/get-attributes.error=Could not get attributes "{0}".
vfs.provider/set-attribute-no-exist.error=Could not set attribute "{0}" of "{1}" because it does not exist.
vfs.provider/set-attribute.error=Could not set attribute "{0}" of "{1}".
vfs.provider/remove-attribute-no-exist.error=Could not check if attribute "{0}" of "{1}" exists because attributes are not supported.
vfs.provider/remove-attribute.error=Could not remove attribute "{0}" of "{1}".
# AbstractFileSystemProvider
vfs.provider/invalid-absolute-uri.error=Invalid absolute URI "{0}".
vfs.provider/not-layered-fs.error=File system for URL scheme "{0}" is not a layered file system.
vfs.provider/no-config-builder.error=File provider for URL scheme "{0}" do not provide a configuration builder.
vfs.provider/config-key-invalid.error=The configuration builder for scheme "{0}" has no option "{1}".
vfs.provider/config-value-invalid.error=The delegating configuration builder cant convert value "{2}" for key "{1}" scheme "{0}".
vfs.provider/config-too-many-values.error=Too many values for configuration builder for scheme "{0}" key "{1}".
vfs.provider/config-unexpected-primitive.error=Unexpected primitive "{0}".
vfs.provider/config-unexpected-value-class.error=Cant convert a "{0}" value for scheme "{1}" key "{2}".
# AbstractFileSystem
vfs.provider/files-cache-missing.error=No files-cache implementation set.
vfs.provider/mismatched-fs-for-name.error=Incorrect file system URI "{2}" in name "{0}", was expecting "{1}".
vfs.provider/junctions-not-supported.error=Junctions not supported for file system "{0}".
vfs.provider/notify-listener.warn=Could not notify listener of change to "{0}".
vfs.provider/replicate-missing-file.error=Could not replicate "{0}" as it does not exist.
vfs.provider/replicate-file.error=Could not replicate "{0}".
vfs.provider/resolve-file.error=Could not resolve file "{0}".
# AbstractFileProvider
vfs.provider/filename-parser-missing.error=No filename-parser implementation set.
# AbstractFileName
vfs.provider/filename-type.error=A filename can only be of type FileType.FOLDER or FileType.FILE
# Operations
vfs.operation/wrong-type.error=Can't lookup operation, wrong type: "{0}"
vfs.operation/not-found.error=Operation not found, type: "{0}"
vfs.operation/cant-register.error=Can't register operation, wrong type: "{0}"
vfs.operation/operation-not-supported.error=Operation "{0}" not supported.
vfs.operation/operation-provider-already-added.error=Operation provider already added to scheme "{0}"
# RandomAccess
vfs.provider/random-access-invalid-position.error=Invalid position: "{0}"
vfs.provider/random-access-open-failed.error=Could not access file "{0}" because it does not exist.
# UriParser
vfs.provider/missing-double-slashes.error=Expecting // to follow the scheme in URI "{0}".
vfs.provider/missing-hostname.error=Hostname missing from URI "{0}".
vfs.provider/missing-port.error=Port number is missing from URI "{0}".
vfs.provider/missing-hostname-path-sep.error=Expecting / to follow the hostname in URI "{0}".
vfs.provider/invalid-descendent-name.error=Invalid descendent file name "{0}".
vfs.provider/invalid-escape-sequence.error=Invalid URI escape sequence "{0}".
vfs.provider/invalid-relative-path.error=Invalid relative file name.
# DefaultFileSystemManager
vfs.impl/unknown-scheme.error=Unknown scheme "{0}" in URI "{1}".
vfs.impl/find-rel-file.error=Could not find file with URI "{0}" because it is a relative path, and no base URI was provided.
vfs.impl/multiple-providers-for-scheme.error=Multiple providers registered for URL scheme "{0}".
vfs.impl/configuration-already-set.error=FilesCache implementation already set.
vfs.impl/configuration-already-in-use.error=The configuration is already attached to an filesystemmanager. You cant change it anymore.
vfs.impl/unknown-provider.error=No file provider is registered with URI scheme "{0}" to handle file "{1}".
vfs.impl/no-provider-for-file.error=Could not find a file provider that can handle file "{0}".
vfs.impl/no-local-file-provider.error=Could not find a file provider which can handle local files.
vfs.impl/no-replicator.error=No file replicator configured.
vfs.impl/no-temp-file-store.error=No temporary file store configured.
vfs.impl/replicate-file.error=Could not replicate "{0}".
vfs.impl/delete-temp.warn=Could not clean up temporary file "{0}".
vfs.impl/init-replicator.error=Could not initialise file replicator.
vfs.impl/already-inited.error=Manager already inited, cant change the configuration now.
vfs.impl/invalid-decorator.error="{0}" is not a valid decorator. It has to extend "DecoratedFileObject" and must provide a single argument constructor which takes a "FileObject"
vfs.impl/temp-dir.info=Using "{0}" as temporary files store.
# StandardFileSystemManager
vfs.impl/find-config-file.error=Could not find VFS configuration resource "{0}".
vfs.impl/load-config.error=Could not load VFS configuration from "{0}".
vfs.impl/create-provider.error=Could not create file provider of class "{0}".
vfs.impl/create-files-cache.error=Could not create files-cache implementation of class "{0}".
vfs.impl/create-client-factory.error=Could not create client factory of class "{0}".
vfs.impl/skipping-provider.debug=Skipping provider "{0}" because required class "{1}" is not available.
vfs.impl/skipping-provider-scheme.debug=Skipping provider "{0}" because required scheme "{1}" is not available.
# FileTypeMap
vfs.impl/multiple-schemes.error=This file requires multiple schemes. Use getSchemes() instead.
# VFSClassLoader
vfs.impl/pkg-sealing-unsealed=Trying to seal package "{0}" that exists as unsealed.
vfs.impl/pkg-sealed-other-url=Package "{0}" exists and is sealed with other URL.
# VirtualFileSystem
vfs.impl/nested-junction.error=Attempting to create a nested junction at "{0}". Nested junctions are not supported.
vfs.impl/create-junction.error=Could not create a junction at "{0}".
# SoftRefFilesCache
vfs.impl/SoftRefReleaseThread-interrupt.info=SoftRefFilesCache - Release Thread interrupted.
vfs.impl/SoftRefReleaseThread-already-running.warn=SoftRefFilesCache - Release Thread already running.
# Local Provider
vfs.provider.local/get-type.error=Could not determine the type of "{0}".
vfs.provider.local/delete-file.error=Could not delete "{0}".
vfs.provider.local/rename-file.error=Could not rename file "{0}" to "{1}".
vfs.provider.local/create-folder.error=Could not create directory "{0}".
vfs.provider.local/not-absolute-file-name.error=URI "{0}" is not an absolute file name.
vfs.provider.local/missing-share-name.error=Share name missing from UNC file name "{0}".
# Temp Provider
vfs.provider.temp/get-type.error=Could not determine the type of "{0}".
vfs.provider.temp/delete-file.error=Could not delete "{0}".
vfs.provider.temp/rename-file.error=Could not rename file "{0}" to "{1}".
vfs.provider.temp/create-folder.error=Could not create directory "{0}".
vfs.provider.temp/not-absolute-file-name.error=URI "{0}" is not an absolute file name.
vfs.provider.temp/missing-share-name.error=Share name missing from UNC file name "{0}".
# SMB Provider
vfs.provider.smb/missing-share-name.error=The share name is missing from URI "{0}".
vfs.provider.smb/get-type.error=Could not detemine the type of "{0}".
# Zip Provider
vfs.provider.zip/open-zip-file.error=Could not open Zip file "{0}".
vfs.provider.zip/close-zip-file.error=Could not close Zip file "{0}".
# Bzip2 Provider
vfs.provider.bzip2/not-a-bzip2-file.error=File "{0}" is not bzip2 compressed.
# JarFileSystem
vfs.provider.jar/open-jar-file.error=Could not open Jar file "{0}".
# JarURLConnectionImpl
vfs.provider.jar/jar-file-no-access.error=JarURLConnections in VFS does not give access to the JarFile.
vfs.provider.jar/jar-entry-no-access.error=JarURLConnections in VFS does not give access to the JarEntry.
# FTP Provider
vfs.provider.ftp/get-type.error=Could not determine the file type of "{0}".
vfs.provider.ftp/delete-file.error=Could not delete FTP file "{0}".
vfs.provider.ftp/rename-file.error=Could not rename FTP file "{0}" to "{1}".
vfs.provider.ftp/create-folder.error=Could not create FTP directory "{0}".
vfs.provider.ftp/finish-get.error=Could not get FTP file "{0}".
vfs.provider.ftp/finish-put.error=Could not put FTP file "{0}".
vfs.provider.ftp/connect-rejected.error=Connection to FTP server on "{0}" rejected.
vfs.provider.ftp/login.error=Could not login to FTP server on "{0}" as user "{1}".
vfs.provider.ftp/set-binary.error=Could not switch to binary transfer mode.
vfs.provider.ftp/connect.error=Could not connect to FTP server on "{0}".
vfs.provider.ftp/close-connection.error=Could not close connection to FTP server.
vfs.provider.ftp/change-work-directory.error=Could not change to work directory "{0}".
vfs.provider.ftp/invalid-directory-entry.debug=Invalid directory entry at line "{0}" (directory "{1}").
vfs.provider.ftp/output-error.debug=Cant open output connection for file "{0}". Reason: "{1}".
vfs.provider.ftp/input-error.debug=Cant open input connection for file "{0}". Reason: "{1}".
vfs.provider.ftp.wrapper/change-work-directory-back.error=Could not change back to work directory "{0}".
# URL Provider
vfs.provider.url/badly-formed-uri.error=Badly formed URI "{0}".
# Http Provider
vfs.provider.http/get.error=GET method failed for "{0}".
vfs.provider.http/head.error=HEAD method failed for "{0}".
vfs.provider.http/last-modified.error=No Last-Modified header in HTTP response.
vfs.provider.http/get-range.error=GET method failed for "{0}" range "{1}-".
vfs.provider.http/connect.error=Could not connect to HTTP server on "{0}".
# WebDAV Provider
vfs.provider.webdav/write-file.error=Write to file failed with message: "{0}".
vfs.provider.webdav/list-children.error=List child resources failed with message: "{0}".
vfs.provider.webdav/create-collection.error=Create collection failed with message: "{0}".
vfs.provider.webdav/delete-file.error=Delete file failed with message: "{0}".
vfs.provider.webdav/create-client.error=Could not create client for server "{0}".
vfs.provider.webdav/rename-file.error=Rename file failed with message: "{0}".
# SFTP Provider
vfs.provider.sftp/connect.error=Could not connect to SFTP server at "{0}".
vfs.provider.sftp/change-work-directory.error=Could not change to work directory "{0}".
vfs.provider.sftp/unknown-permissions.error=File permissions not fetched.
vfs.provider.sftp/unknown-size.error=File size not fetched.
vfs.provider.sftp/create-folder.error=Folder creation failed with unknown error.
vfs.provider.sftp/delete.error=Delete failed with unknown error.
vfs.provider.sftp/list-children.error=List folder contents failed with unknown error.
vfs.provider.sftp/put-file.error=Write file contents failed with unknown error.
vfs.provider.sftp/get-file.error=Read file contents failed with unknown error.
vfs.provider.sftp/load-private-key.error=Could not load private key from "{0}".
vfs.provider.sftp/config-sshdir.error=SSH-Folder "{0}" non existent or not a folder.
vfs.provider.sftp/unknown-modtime.error=Last modification time not fetched.
vfs.provider.sftp/known-hosts.error=Error during processing known-hosts file "{0}".
vfs.provider.sftp/StrictHostKeyChecking-arg.error=Illegal argument "{0}" hostKeyChecking can only be "ask", "yes" or "no"
vfs.provider.sftp/change-work-directory-back.error=Could not change back to work directory "{0}".
# Ant tasks
vfs.tasks/sync.no-destination.error=No destination file or directory specified.
vfs.tasks/sync.too-many-destinations.error=Cannot specify both a destination file and a destination directory.
vfs.tasks/sync.no-source-files.warn=No source files specified.
vfs.tasks/sync.no-source-file.error=No source file specified.
vfs.tasks/sync.too-many-source-files.error=Too many source files specified.
vfs.tasks/sync.source-not-file.error=Source file "{0}" is not a file, or does not exist.
vfs.tasks/sync.src-file-no-exist.warn=Source file "{0}" does not exist.
vfs.tasks/sync.duplicate-source-files.warn=Multiple source files for destination file "{0}".
vfs.tasks/delete.no-source-files.error=No files to delete specified.
vfs.tasks/mkdir.create-folder.info=Creating directory "{0}".
# Selectors
vfs.selectors/filefilter.missing.error=Configure a fileFilter or override accept();
# Utils
vfs.util/find-abstract-file-object.error=Object didnt extend from AbstractFileObject. Object "{0}"
vfs.util/missing-capability.error=The Filesystem do not provide the required capability "{0}"
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/Selectors.java 100644 765 24 4621 11623215066 26071 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* Several standard file selectors.
*
* @author Commons VFS team
*/
public final class Selectors
{
/**
* A {@link FileSelector} that selects only the base file/folder.
*/
public static final FileSelector SELECT_SELF = new FileDepthSelector(0, 0);
/**
* A {@link FileSelector} that selects the base file/folder and its
* direct children.
*/
public static final FileSelector SELECT_SELF_AND_CHILDREN = new FileDepthSelector(0, 1);
/**
* A {@link FileSelector} that selects only the direct children
* of the base folder.
*/
public static final FileSelector SELECT_CHILDREN = new FileDepthSelector(1, 1);
/**
* A {@link FileSelector} that selects all the descendents of the
* base folder, but does not select the base folder itself.
*/
public static final FileSelector EXCLUDE_SELF = new FileDepthSelector(1, Integer.MAX_VALUE);
/**
* A {@link FileSelector} that only files (not folders).
*/
public static final FileSelector SELECT_FILES = new FileTypeSelector(FileType.FILE);
/**
* A {@link FileSelector} that only folders (not files).
*/
public static final FileSelector SELECT_FOLDERS = new FileTypeSelector(FileType.FOLDER);
/**
* A {@link FileSelector} that selects the base file/folder, plus all
* its descendents.
*/
public static final FileSelector SELECT_ALL = new AllFileSelector();
/**
* Prevent the class from being instantiated.
*/
private Selectors()
{
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/AbstractSyncTask.java 100644 765 24 34602 11623215065 30517 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Set;
import java.util.StringTokenizer;
import org.apache.commons.vfs2.FileName;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileType;
import org.apache.commons.vfs2.NameScope;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.util.Messages;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.Project;
/**
* An abstract file synchronization task. Scans a set of source files and
* folders, and a destination folder, and performs actions on missing and
* out-of-date files. Specifically, performs actions on the following:
*
* Missing destination file.
* Missing source file.
* Out-of-date destination file.
* Up-to-date destination file.
*
*
* @author Commons VFS team
* @todo Deal with case where dest file maps to a child of one of the source files
* @todo Deal with case where dest file already exists and is incorrect type (not file, not a folder)
* @todo Use visitors
* @todo Add default excludes
* @todo Allow selector, mapper, filters, etc to be specified.
* @todo Handle source/dest directories as well
* @todo Allow selector to be specified for choosing which dest files to sync
*/
public abstract class AbstractSyncTask
extends VfsTask
{
private final ArrayList srcFiles = new ArrayList();
private String destFileUrl;
private String destDirUrl;
private String srcDirUrl;
private boolean srcDirIsBase;
private boolean failonerror = true;
private String filesList;
/**
* Sets the destination file.
* @param destFile The destination file name.
*/
public void setDestFile(final String destFile)
{
this.destFileUrl = destFile;
}
/**
* Sets the destination directory.
* @param destDir The destination directory.
*/
public void setDestDir(final String destDir)
{
this.destDirUrl = destDir;
}
/**
* Sets the source file.
* @param srcFile The source file name.
*/
public void setSrc(final String srcFile)
{
final SourceInfo src = new SourceInfo();
src.setFile(srcFile);
addConfiguredSrc(src);
}
/**
* Sets the source directory.
* @param srcDir The source directory.
*/
public void setSrcDir(final String srcDir)
{
this.srcDirUrl = srcDir;
}
/**
* Sets whether the source directory should be consider as the base directory.
* @param srcDirIsBase true if the source directory is the base directory.
*/
public void setSrcDirIsBase(final boolean srcDirIsBase)
{
this.srcDirIsBase = srcDirIsBase;
}
/**
* Sets whether we should fail if there was an error or not.
* @param failonerror true if the operation should fail if there is an error.
*/
public void setFailonerror(final boolean failonerror)
{
this.failonerror = failonerror;
}
/**
* Sets whether we should fail if there was an error or not.
* @return true if the operation should fail if there was an error.
*/
public boolean isFailonerror()
{
return failonerror;
}
/**
* Sets the files to includes.
* @param filesList The list of files to include.
*/
public void setIncludes(final String filesList)
{
this.filesList = filesList;
}
/**
* Adds a nested <src> element.
* @param srcInfo A nested source element.
* @throws BuildException if the SourceInfo doesn't reference a file.
*/
public void addConfiguredSrc(final SourceInfo srcInfo)
throws BuildException
{
if (srcInfo.file == null)
{
final String message = Messages.getString("vfs.tasks/sync.no-source-file.error");
throw new BuildException(message);
}
srcFiles.add(srcInfo);
}
/**
* Executes this task.
* @throws BuildException if an error occurs.
*/
@Override
public void execute() throws BuildException
{
// Validate
if (destFileUrl == null && destDirUrl == null)
{
final String message =
Messages.getString("vfs.tasks/sync.no-destination.error");
logOrDie(message, Project.MSG_WARN);
return;
}
if (destFileUrl != null && destDirUrl != null)
{
final String message =
Messages.getString("vfs.tasks/sync.too-many-destinations.error");
logOrDie(message, Project.MSG_WARN);
return;
}
// Add the files of the includes attribute to the list
if (srcDirUrl != null && !srcDirUrl.equals(destDirUrl) && filesList != null && filesList.length() > 0)
{
if (!srcDirUrl.endsWith("/"))
{
srcDirUrl += "/";
}
StringTokenizer tok = new StringTokenizer(filesList, ", \t\n\r\f", false);
while (tok.hasMoreTokens())
{
String nextFile = tok.nextToken();
// Basic compatibility with Ant fileset for directories
if (nextFile.endsWith("/**"))
{
nextFile = nextFile.substring(0, nextFile.length() - 2);
}
final SourceInfo src = new SourceInfo();
src.setFile(srcDirUrl + nextFile);
addConfiguredSrc(src);
}
}
if (srcFiles.size() == 0)
{
final String message = Messages.getString("vfs.tasks/sync.no-source-files.warn");
logOrDie(message, Project.MSG_WARN);
return;
}
// Perform the sync
try
{
if (destFileUrl != null)
{
handleSingleFile();
}
else
{
handleFiles();
}
}
catch (final BuildException e)
{
throw e;
}
catch (final Exception e)
{
throw new BuildException(e.getMessage(), e);
}
}
protected void logOrDie(final String message, int level)
{
if (!isFailonerror())
{
log(message, level);
return;
}
throw new BuildException(message);
}
/**
* Copies the source files to the destination.
*/
private void handleFiles() throws Exception
{
// Locate the destination folder, and make sure it exists
final FileObject destFolder = resolveFile(destDirUrl);
destFolder.createFolder();
// Locate the source files, and make sure they exist
FileName srcDirName = null;
if (srcDirUrl != null)
{
srcDirName = resolveFile(srcDirUrl).getName();
}
final ArrayList srcs = new ArrayList();
for (int i = 0; i < srcFiles.size(); i++)
{
// Locate the source file, and make sure it exists
final SourceInfo src = srcFiles.get(i);
final FileObject srcFile = resolveFile(src.file);
if (!srcFile.exists())
{
final String message =
Messages.getString("vfs.tasks/sync.src-file-no-exist.warn", srcFile);
logOrDie(message, Project.MSG_WARN);
}
else
{
srcs.add(srcFile);
}
}
// Scan the source files
final Set destFiles = new HashSet();
for (int i = 0; i < srcs.size(); i++)
{
final FileObject rootFile = srcs.get(i);
final FileName rootName = rootFile.getName();
if (rootFile.getType() == FileType.FILE)
{
// Build the destination file name
String relName = null;
if (srcDirName == null || !srcDirIsBase)
{
relName = rootName.getBaseName();
}
else
{
relName = srcDirName.getRelativeName(rootName);
}
final FileObject destFile = destFolder.resolveFile(relName, NameScope.DESCENDENT);
// Do the copy
handleFile(destFiles, rootFile, destFile);
}
else
{
// Find matching files
// If srcDirIsBase is true, select also the sub-directories
final FileObject[] files = rootFile.findFiles(srcDirIsBase
? Selectors.SELECT_ALL : Selectors.SELECT_FILES);
for (int j = 0; j < files.length; j++)
{
final FileObject srcFile = files[j];
// Build the destination file name
String relName = null;
if (srcDirName == null || !srcDirIsBase)
{
relName = rootName.getRelativeName(srcFile.getName());
}
else
{
relName = srcDirName.getRelativeName(srcFile.getName());
}
final FileObject destFile =
destFolder.resolveFile(relName, NameScope.DESCENDENT);
// Do the copy
handleFile(destFiles, srcFile, destFile);
}
}
}
// Scan the destination files for files with no source file
if (detectMissingSourceFiles())
{
final FileObject[] allDestFiles = destFolder.findFiles(Selectors.SELECT_FILES);
for (int i = 0; i < allDestFiles.length; i++)
{
final FileObject destFile = allDestFiles[i];
if (!destFiles.contains(destFile))
{
handleMissingSourceFile(destFile);
}
}
}
}
/**
* Handles a single file, checking for collisions where more than one
* source file maps to the same destination file.
*/
private void handleFile(final Set destFiles,
final FileObject srcFile,
final FileObject destFile) throws Exception
{
// Check for duplicate source files
if (destFiles.contains(destFile))
{
final String message = Messages.getString("vfs.tasks/sync.duplicate-source-files.warn", destFile);
logOrDie(message, Project.MSG_WARN);
}
else
{
destFiles.add(destFile);
}
// Handle the file
handleFile(srcFile, destFile);
}
/**
* Copies a single file.
*/
private void handleSingleFile() throws Exception
{
// Make sure there is exactly one source file, and that it exists
// and is a file.
if (srcFiles.size() > 1)
{
final String message =
Messages.getString("vfs.tasks/sync.too-many-source-files.error");
logOrDie(message, Project.MSG_WARN);
return;
}
final SourceInfo src = srcFiles.get(0);
final FileObject srcFile = resolveFile(src.file);
if (srcFile.getType() != FileType.FILE)
{
final String message =
Messages.getString("vfs.tasks/sync.source-not-file.error", srcFile);
logOrDie(message, Project.MSG_WARN);
return;
}
// Locate the destination file
final FileObject destFile = resolveFile(destFileUrl);
// Do the copy
handleFile(srcFile, destFile);
}
/**
* Handles a single source file.
*/
private void handleFile(final FileObject srcFile,
final FileObject destFile)
throws Exception
{
if (!destFile.exists()
|| srcFile.getContent().getLastModifiedTime() > destFile.getContent().getLastModifiedTime())
{
// Destination file is out-of-date
handleOutOfDateFile(srcFile, destFile);
}
else
{
// Destination file is up-to-date
handleUpToDateFile(srcFile, destFile);
}
}
/**
* Handles an out-of-date file (a file where the destination file
* either doesn't exist, or is older than the source file).
* This implementation does nothing.
*/
protected void handleOutOfDateFile(final FileObject srcFile,
final FileObject destFile)
throws Exception
{
}
/**
* Handles an up-to-date file (where the destination file exists and is
* newer than the source file). This implementation does nothing.
*/
protected void handleUpToDateFile(final FileObject srcFile,
final FileObject destFile)
throws Exception
{
}
/**
* Handles a destination for which there is no corresponding source file.
* This implementation does nothing.
*/
protected void handleMissingSourceFile(final FileObject destFile)
throws Exception
{
}
/**
* Check if this task cares about destination files with a missing source
* file. This implementation returns false.
*/
protected boolean detectMissingSourceFiles()
{
return false;
}
/**
* Information about a source file.
*/
public static class SourceInfo
{
private String file;
public void setFile(final String file)
{
this.file = file;
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/antlib.xml 100644 765 24 2611 11623215065 26377 0 ustar rgoers staff 0 0
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/CopyTask.java 100644 765 24 6645 11623215065 27017 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.Selectors;
/**
* An Ant task that copies matching files.
*
* @author Commons VFS team
* @todo Copy folders that do not contain files
*/
public class CopyTask
extends AbstractSyncTask
{
private boolean overwrite;
private boolean preserveLastModified = true;
/**
* Enable/disable overwriting of up-to-date files.
* @param overwrite true if the file should be overwritten.
*/
public void setOverwrite(boolean overwrite)
{
this.overwrite = overwrite;
}
/**
* Enable/disable preserving last modified time of copied files.
* @param preserveLastModified true if the last modified time should be preserved.
*/
public void setPreserveLastModified(boolean preserveLastModified)
{
this.preserveLastModified = preserveLastModified;
}
/**
* @return the current value of overwrite
*/
public boolean isOverwrite()
{
return overwrite;
}
/**
* @return the current value of preserveLastModified
*/
public boolean isPreserveLastModified()
{
return preserveLastModified;
}
/**
* Handles an out-of-date file.
* @param srcFile The source FileObject.
* @param destFile The destination FileObject.
*/
@Override
protected void handleOutOfDateFile(final FileObject srcFile,
final FileObject destFile)
throws FileSystemException
{
log("Copying " + srcFile + " to " + destFile);
destFile.copyFrom(srcFile, Selectors.SELECT_SELF);
if (preserveLastModified
&& srcFile.getFileSystem().hasCapability(Capability.GET_LAST_MODIFIED)
&& destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE))
{
final long lastModTime = srcFile.getContent().getLastModifiedTime();
destFile.getContent().setLastModifiedTime(lastModTime);
}
}
/**
* Handles an up-to-date file.
* @param srcFile The source FileObject.
* @param destFile The destination FileObject.
*/
@Override
protected void handleUpToDateFile(final FileObject srcFile,
final FileObject destFile)
throws FileSystemException
{
if (overwrite)
{
// Copy the file anyway
handleOutOfDateFile(srcFile, destFile);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/DeleteTask.java 100644 765 24 6420 11623215065 27276 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import java.util.StringTokenizer;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.Selectors;
import org.apache.commons.vfs2.util.Messages;
import org.apache.tools.ant.BuildException;
/**
* An Ant task that deletes matching files.
*
* @author Commons VFS team
* @todo Allow selector to be specified.
*/
public class DeleteTask
extends VfsTask
{
private String file;
private String srcDirUrl;
private String filesList;
/**
* Sets the file/folder to delete.
*
* @param file The name of the file.
*/
public void setFile(final String file)
{
this.file = file;
}
/**
* Sets the source directory.
* @param srcDir The source directory.
*/
public void setSrcDir(final String srcDir)
{
this.srcDirUrl = srcDir;
}
/**
* Sets the files to include.
* @param filesList The list of files.
*/
public void setIncludes(final String filesList)
{
this.filesList = filesList;
}
/**
* Executes this task.
* @throws BuildException if an error occurs.
*/
@Override
public void execute() throws BuildException
{
if ((file == null && srcDirUrl == null) || (srcDirUrl != null && filesList == null))
{
final String message = Messages.getString("vfs.tasks/delete.no-source-files.error");
throw new BuildException(message);
}
try
{
if (srcDirUrl != null && filesList != null)
{
log("Deleting " + filesList + " in the directory " + srcDirUrl);
if (!srcDirUrl.endsWith("/"))
{
srcDirUrl += "/";
}
StringTokenizer tok = new StringTokenizer(filesList, ", \t\n\r\f", false);
while (tok.hasMoreTokens())
{
String nextFile = tok.nextToken();
final FileObject srcFile = resolveFile(srcDirUrl + nextFile);
srcFile.delete(Selectors.SELECT_ALL);
}
}
else
{
final FileObject srcFile = resolveFile(file);
log("Deleting " + srcFile);
srcFile.delete(Selectors.SELECT_ALL);
}
}
catch (final Exception e)
{
throw new BuildException(e);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/MkdirTask.java 100644 765 24 4125 11623215065 27142 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.util.Messages;
import org.apache.tools.ant.BuildException;
/**
* An Ant task that creates a directory.
*
* @author Commons VFS team
*/
public class MkdirTask
extends VfsTask
{
private String dirName;
/**
* Sets the directory to create.
*
* @param dir The directory name.
*/
public void setDir(final String dir)
{
dirName = dir;
}
/**
* Executes the task.
* @throws BuildException if an exception occurs.
*/
@Override
public void execute() throws BuildException
{
if (dirName == null)
{
final String message = Messages.getString("vfs.tasks/no-directory-specified.error");
throw new BuildException(message);
}
try
{
final FileObject dir = resolveFile(dirName);
final String message = Messages.getString("vfs.tasks/mkdir.create-folder.info", dir);
log(message);
dir.createFolder();
}
catch (final FileSystemException e)
{
throw new BuildException(e);
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/MoveTask.java 100644 765 24 4467 11623215065 27013 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import org.apache.commons.vfs2.Capability;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.Selectors;
/**
* An Ant task that moves matching files.
*
* @author Commons VFS team
* @todo Delete matching folders
*/
public class MoveTask
extends CopyTask
{
private boolean tryRename;
/**
* Enable/disable move/rename of file (if possible).
* @param tryRename true if the file should be renamed.
*/
public void setTryRename(boolean tryRename)
{
this.tryRename = tryRename;
}
/**
* Handles a single source file.
*/
@Override
protected void handleOutOfDateFile(final FileObject srcFile,
final FileObject destFile)
throws FileSystemException
{
if (!tryRename || !srcFile.canRenameTo(destFile))
{
super.handleOutOfDateFile(srcFile, destFile);
log("Deleting " + srcFile);
srcFile.delete(Selectors.SELECT_SELF);
}
else
{
log("Rename " + srcFile + " to " + destFile);
srcFile.moveTo(destFile);
if (!isPreserveLastModified()
&& destFile.getFileSystem().hasCapability(Capability.SET_LAST_MODIFIED_FILE))
{
destFile.getContent().setLastModifiedTime(System.currentTimeMillis());
}
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/package.html 100644 765 24 1534 11623215065 26670 0 ustar rgoers staff 0 0
The VFS Ant Tasks.
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/ShowFileTask.java 100644 765 24 11507 11623215065 27636 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Date;
import org.apache.commons.vfs2.FileContent;
import org.apache.commons.vfs2.FileObject;
import org.apache.tools.ant.BuildException;
/**
* An Ant task that writes the details of a file to Ant's log.
*
* @author Commons VFS team
*/
public class ShowFileTask
extends VfsTask
{
private static final String INDENT = " ";
private String url;
private boolean showContent;
private boolean recursive;
/**
* The URL of the file to display.
* @param url The url of the file.
*/
public void setFile(final String url)
{
this.url = url;
}
/**
* Shows the content. Assumes the content is text, encoded using the
* platform's default encoding.
* @param showContent true if the content should be shown.
*/
public void setShowContent(final boolean showContent)
{
this.showContent = showContent;
}
/**
* Recursively shows the descendents of the file.
* @param recursive true if descendents should be shown.
*/
public void setRecursive(final boolean recursive)
{
this.recursive = recursive;
}
/**
* Executes the task.
* @throws BuildException if any exception is thrown.
*/
@Override
public void execute() throws BuildException
{
try
{
final FileObject file = resolveFile(url);
log("Details of " + file.getName().getURI());
showFile(file, INDENT);
}
catch (final Exception e)
{
throw new BuildException(e);
}
}
/**
* Logs the details of a file.
*/
private void showFile(final FileObject file, final String prefix) throws Exception
{
// Write details
StringBuilder msg = new StringBuilder(prefix);
msg.append(file.getName().getBaseName());
if (file.exists())
{
msg.append(" (");
msg.append(file.getType().getName());
msg.append(")");
}
else
{
msg.append(" (unknown)");
}
log(msg.toString());
if (file.exists())
{
final String newPrefix = prefix + INDENT;
if (file.getType().hasContent())
{
final FileContent content = file.getContent();
log(newPrefix + "Content-Length: " + content.getSize());
log(newPrefix + "Last-Modified" + new Date(content.getLastModifiedTime()));
if (showContent)
{
log(newPrefix + "Content:");
logContent(file, newPrefix);
}
}
if (file.getType().hasChildren())
{
final FileObject[] children = file.getChildren();
for (int i = 0; i < children.length; i++)
{
FileObject child = children[i];
if (recursive)
{
showFile(child, newPrefix);
}
else
{
log(newPrefix + child.getName().getBaseName());
}
}
}
}
}
/**
* Writes the content of the file to Ant log.
*/
private void logContent(final FileObject file, final String prefix)
throws Exception
{
final InputStream instr = file.getContent().getInputStream();
try
{
final BufferedReader reader = new BufferedReader(new InputStreamReader(instr));
while (true)
{
final String line = reader.readLine();
if (line == null)
{
break;
}
log(prefix + line);
}
}
finally
{
instr.close();
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/SyncTask.java 100644 765 24 3157 11623215065 27014 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import org.apache.commons.vfs2.FileObject;
/**
* A task that synchronises the destination folder to look exactly like
* the source folder (or folders).
*
* @author Commons VFS team
*/
public class SyncTask
extends CopyTask
{
/**
* Handles a destination for which there is no corresponding source file.
*/
@Override
protected void handleMissingSourceFile(final FileObject destFile)
throws Exception
{
log("deleting " + destFile);
//destFile.delete( Selectors.SELECT_SELF );
}
/**
* Check if this task cares about destination files with a missing source
* file.
*/
@Override
protected boolean detectMissingSourceFiles()
{
return true;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/tasks.properties 100644 765 24 2111 11623215065 27642 0 ustar rgoers staff 0 0 # Licensed to the Apache Software Foundation (ASF) under one or more
# contributor license agreements. See the NOTICE file distributed with
# this work for additional information regarding copyright ownership.
# The ASF licenses this file to You under the Apache License, Version 2.0
# (the "License"); you may not use this file except in compliance with
# the License. You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
v-copy=org.apache.commons.vfs2.tasks.CopyTask
v-move=org.apache.commons.vfs2.tasks.MoveTask
v-sync=org.apache.commons.vfs2.tasks.SyncTask
v-delete=org.apache.commons.vfs2.tasks.DeleteTask
v-mkdir=org.apache.commons.vfs2.tasks.MkdirTask
v-show-file=org.apache.commons.vfs2.tasks.ShowFileTask
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/tasks/VfsTask.java 100644 765 24 11712 11623215065 26652 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.tasks;
import org.apache.commons.logging.Log;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.impl.StandardFileSystemManager;
import org.apache.tools.ant.BuildEvent;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.SubBuildListener;
import org.apache.tools.ant.Task;
/**
* Base class for the VFS Ant tasks. Takes care of creating a FileSystemManager,
* and for cleaning it up at the end of the build. Also provides some
* utility methods.
*
* @author Commons VFS team
*/
public class VfsTask
extends Task
{
private static StandardFileSystemManager manager;
/**
* Resolves a URI to a file, relative to the project's base directory.
*
* @param uri The URI to resolve.
*/
protected FileObject resolveFile(final String uri)
throws FileSystemException
{
if (manager == null)
{
StandardFileSystemManager mngr = new StandardFileSystemManager();
mngr.setLogger(new AntLogger());
mngr.init();
manager = mngr;
getProject().addBuildListener(new CloseListener());
}
return manager.resolveFile(getProject().getBaseDir(), uri);
}
/**
* Close the manager
*/
protected void closeManager()
{
if (manager != null)
{
manager.close();
manager = null;
}
}
/**
* Closes the VFS manager when the project finishes.
*/
private class CloseListener
implements SubBuildListener
{
public void subBuildStarted(BuildEvent buildEvent)
{
}
public void subBuildFinished(BuildEvent buildEvent)
{
closeManager();
}
public void buildFinished(BuildEvent event)
{
closeManager();
}
public void buildStarted(BuildEvent event)
{
}
public void messageLogged(BuildEvent event)
{
}
public void targetFinished(BuildEvent event)
{
}
public void targetStarted(BuildEvent event)
{
}
public void taskFinished(BuildEvent event)
{
}
public void taskStarted(BuildEvent event)
{
}
}
/**
* A commons-logging wrapper for Ant logging.
*/
private class AntLogger
implements Log
{
public void debug(final Object o)
{
log(String.valueOf(o), Project.MSG_DEBUG);
}
public void debug(Object o, Throwable throwable)
{
debug(o);
}
public void error(Object o)
{
log(String.valueOf(o), Project.MSG_ERR);
}
public void error(Object o, Throwable throwable)
{
error(o);
}
public void fatal(Object o)
{
log(String.valueOf(o), Project.MSG_ERR);
}
public void fatal(Object o, Throwable throwable)
{
fatal(o);
}
public void info(Object o)
{
log(String.valueOf(o), Project.MSG_INFO);
}
public void info(Object o, Throwable throwable)
{
info(o);
}
public void trace(Object o)
{
}
public void trace(Object o, Throwable throwable)
{
}
public void warn(Object o)
{
log(String.valueOf(o), Project.MSG_WARN);
}
public void warn(Object o, Throwable throwable)
{
warn(o);
}
public boolean isDebugEnabled()
{
return true;
}
public boolean isErrorEnabled()
{
return true;
}
public boolean isFatalEnabled()
{
return true;
}
public boolean isInfoEnabled()
{
return true;
}
public boolean isTraceEnabled()
{
return false;
}
public boolean isWarnEnabled()
{
return true;
}
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/UserAuthenticationData.java 100644 765 24 7612 11623215066 30541 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
import java.util.Iterator;
import java.util.Map;
import java.util.TreeMap;
/**
* Container for various authentication data.
* @author Commons VFS team
*/
public class UserAuthenticationData
{
/**
* Inner class to represent portions of the user authentication data.
*/
public static class Type implements Comparable
{
/** The type name */
private final String type;
public Type(String type)
{
this.type = type;
}
@Override
public boolean equals(Object o)
{
if (this == o)
{
return true;
}
if (o == null || getClass() != o.getClass())
{
return false;
}
Type type1 = (Type) o;
if (type != null ? !type.equals(type1.type) : type1.type != null)
{
return false;
}
return true;
}
public int compareTo(Type o)
{
return type.compareTo(o.type);
}
/**
* @return The hash code.
* @since 2.0
* */
@Override
public int hashCode()
{
return type != null ? type.hashCode() : 0;
}
/**
* @return The type.
* @since 2.0
* */
@Override
public String toString()
{
return type;
}
}
/** The user name. */
public static final Type USERNAME = new Type("username");
/** The password. */
public static final Type PASSWORD = new Type("password");
/** The user's domain. */
public static final Type DOMAIN = new Type("domain");
/** The authentication data. */
private final Map authenticationData = new TreeMap();
public UserAuthenticationData()
{
}
/**
* set a data to this collection.
* @param type The Type to add
* @param data The data associated with the Type
*/
public void setData(Type type, char[] data)
{
authenticationData.put(type, data);
}
/**
* get a data from the collection.
* @param type The Type to retrieve.
* @return a character array containing the data associated with the type.
*/
public char[] getData(Type type)
{
return authenticationData.get(type);
}
/**
* deleted all data stored within this authenticator.
*/
public void cleanup()
{
// step 1: nullify character buffers
Iterator iterAuthenticationData = authenticationData.values().iterator();
while (iterAuthenticationData.hasNext())
{
char[] data = iterAuthenticationData.next();
if (data == null || data.length < 0)
{
continue;
}
for (int i = 0; i < data.length; i++)
{
data[i] = 0;
}
}
// step 2: allow data itself to gc
authenticationData.clear();
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/UserAuthenticator.java 100644 765 24 2734 11623215066 27602 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2;
/**
* The user authenticator is used to query credentials from the user. Since a UserAuthenticator
* is provided with the {@link FileSystemOptions} to a {@link FileSystem} it should also implement
* reasonable equals and hashCode functions if the FileSystem should be shared.
* @author Commons VFS team
*/
public interface UserAuthenticator
{
/**
* Queries the given type from the user.
* @param types An array containing the user's credentials
* @return The UserAuthenticationData.
*/
UserAuthenticationData requestAuthentication(UserAuthenticationData.Type[] types);
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/util/CombinedResources.java 100644 765 24 7740 11623215066 30523 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.util;
import java.io.IOException;
import java.net.URL;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Properties;
import java.util.ResourceBundle;
/**
* @author Commons VFS team
* @since 2.0
*/
public class CombinedResources extends ResourceBundle
{
// locale.getLanguage()
// locale.getCountry()
// locale.getVariant()
private final String resourceName;
private boolean inited;
private final Properties properties = new Properties();
public CombinedResources(String resourceName)
{
this.resourceName = resourceName;
}
protected void init()
{
if (inited)
{
return;
}
loadResources(getResourceName());
loadResources(Locale.getDefault());
loadResources(getLocale());
inited = true;
}
protected void loadResources(Locale locale)
{
if (locale == null)
{
return;
}
String[] parts = new String[]{locale.getLanguage(), locale.getCountry(), locale.getVariant()};
StringBuilder sb = new StringBuilder();
for (int i = 0; i < 3; i++)
{
sb.append(getResourceName());
for (int j = 0; j < i; j++)
{
sb.append('_').append(parts[j]);
}
if (parts[i].length() != 0)
{
sb.append('_').append(parts[i]);
loadResources(sb.toString());
}
sb.setLength(0);
}
}
protected void loadResources(String resourceName)
{
ClassLoader loader = getClass().getClassLoader();
if (loader == null)
{
loader = ClassLoader.getSystemClassLoader();
}
resourceName = resourceName.replace('.', '/') + ".properties";
try
{
Enumeration resources = loader.getResources(resourceName);
while (resources.hasMoreElements())
{
URL resource = resources.nextElement();
try
{
properties.load(resource.openConnection().getInputStream());
}
catch (IOException e)
{
// ignore
}
}
}
catch (IOException e)
{
// ignore
}
}
public String getResourceName()
{
return resourceName;
}
@Override
public Enumeration getKeys()
{
if (!inited)
{
init();
}
return new Enumeration()
{
public boolean hasMoreElements()
{
return properties.keys().hasMoreElements();
}
public String nextElement()
{
// We know that our properties will only ever contain Strings
return (String) properties.keys().nextElement();
}
};
}
@Override
protected Object handleGetObject(String key)
{
if (!inited)
{
init();
}
return properties.get(key);
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/util/Cryptor.java 100644 765 24 2663 11623215066 26551 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.util;
/**
* @author Commons VFS team
* @since 2.0
*/
public interface Cryptor
{
/**
* Encrypt the plain text password.
* @param plainKey The password.
* @return The encrypted password String.
* @throws Exception If an error occurs.
*/
String encrypt(String plainKey) throws Exception;
/**
* Decrypts the password.
* @param encryptedKey the encrypted password.
* @return The plain text password.
* @throws Exception If an error occurs.
*/
String decrypt(String encryptedKey) throws Exception;
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/util/CryptorFactory.java 100644 765 24 4710 11623215066 30074 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.util;
/**
* Factory to create an instance of a Cryptor.
* @author Commons VFS team
* @since 2.0
*/
public final class CryptorFactory
{
/**
* The System property name to identify the Cryptor class to be used.
*/
public static final String CRYPTOR_CLASS = "org.apache.commons.vfs2.cryptor";
private static Cryptor instance;
/**
* Prevent instantiation of the class.
*/
private CryptorFactory()
{
}
/**
* Allows the Cryptor class to be set programmatically.
* @param cryptor The Cryptor.
*/
public static synchronized void setCryptor(Cryptor cryptor)
{
instance = cryptor;
}
/**
* Return the Cryptor. If one has not been previously set, create it. The Cryptor class
* can be set by setting the "org.apache.commons.vfs2.cryptor" System property to the
* name of the Cryptor class.
* @return The Cryptor.
*/
public static synchronized Cryptor getCryptor()
{
if (instance != null)
{
return instance;
}
String cryptorClass = System.getProperty(CRYPTOR_CLASS);
if (cryptorClass != null)
{
try
{
Class> clazz = Class.forName(cryptorClass);
instance = (Cryptor) clazz.newInstance();
return instance;
}
catch (Exception ex)
{
throw new RuntimeException("Unable to create Cryptor " + cryptorClass, ex);
}
}
instance = new DefaultCryptor();
return instance;
}
}
commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/util/DefaultCryptor.java 100644 765 24 11043 11623215066 30066 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.util;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
/**
* Allows passwords to be encrypted and decrypted.
* @author Commons VFS team
* @since 2.0
*/
public class DefaultCryptor implements Cryptor
{
private static final char[] HEX_CHARS =
{'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};
private static final byte[] KEY_BYTES = {0x41, 0x70, 0x61, 0x63, 0x68, 0x65, 0x43, 0x6F, 0x6D, 0x6D,
0x6F, 0x6E, 0x73, 0x56, 0x46, 0x53};
private static final int INDEX_NOT_FOUND = -1;
private static final int BITS_IN_HALF_BYTE = 4;
private static final char MASK = 0x0f;
/**
* Encrypt the plain text password.
* @param plainKey The password.
* @return The encrypted password String.
* @throws Exception If an error occurs.
*/
public String encrypt(String plainKey) throws Exception
{
byte[] input = plainKey.getBytes();
SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
Cipher cipher = Cipher.getInstance("AES");
// encryption pass
cipher.init(Cipher.ENCRYPT_MODE, key);
byte[] cipherText = new byte[cipher.getOutputSize(input.length)];
int ctLength = cipher.update(input, 0, input.length, cipherText, 0);
ctLength += cipher.doFinal(cipherText, ctLength);
return encode(cipherText);
}
/**
* Decrypts the password.
* @param encryptedKey the encrypted password.
* @return The plain text password.
* @throws Exception If an error occurs.
*/
public String decrypt(String encryptedKey) throws Exception
{
SecretKeySpec key = new SecretKeySpec(KEY_BYTES, "AES");
Cipher cipher = Cipher.getInstance("AES");
cipher.init(Cipher.DECRYPT_MODE, key);
byte[] decoded = decode(encryptedKey);
byte[] plainText = new byte[cipher.getOutputSize(decoded.length)];
int ptLength = cipher.update(decoded, 0, decoded.length, plainText, 0);
ptLength += cipher.doFinal(plainText, ptLength);
return new String(plainText).substring(0, ptLength);
}
private String encode(byte[] bytes)
{
StringBuilder builder = new StringBuilder();
for (int i = 0; i < bytes.length; ++i)
{
builder.append(HEX_CHARS[(bytes[i] >> BITS_IN_HALF_BYTE) & MASK]);
builder.append(HEX_CHARS[bytes[i] & MASK]);
}
return builder.toString();
}
private byte[] decode(String str)
{
int length = str.length() / 2;
byte[] decoded = new byte[length];
char[] chars = str.toCharArray();
int index = 0;
for (int i = 0; i < chars.length; ++i)
{
int id1 = indexOf(HEX_CHARS, chars[i]);
if (id1 == -1)
{
throw new IllegalArgumentException("Character " + chars[i] + " at position " + i
+ " is not a valid hexidecimal character");
}
int id2 = indexOf(HEX_CHARS, chars[++i]);
if (id2 == -1)
{
throw new IllegalArgumentException("Character " + chars[i] + " at position " + i
+ " is not a valid hexidecimal character");
}
decoded[index++] = (byte) ((id1 << BITS_IN_HALF_BYTE) | id2);
}
return decoded;
}
private int indexOf(char[] array, char valueToFind)
{
if (array == null)
{
return INDEX_NOT_FOUND;
}
for (int i = 0; i < array.length; i++)
{
if (valueToFind == array[i])
{
return i;
}
}
return INDEX_NOT_FOUND;
}
}
././@LongLink 100644 0 0 150 11623215455 10253 L ustar 0 0 commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilder.java commons-vfs-2.0/core/src/main/java/org/apache/commons/vfs2/util/DelegatingFileSystemOptionsBuilder.j100644 765 24 37103 11623215066 33367 0 ustar rgoers staff 0 0 /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.vfs2.util;
import java.lang.reflect.Array;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.commons.vfs2.FileSystemConfigBuilder;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemManager;
import org.apache.commons.vfs2.FileSystemOptions;
/**
* This class use reflection to set a configuration value using the fileSystemConfigBuilder
* associated the a scheme.
* Example:
*
* FileSystemOptions fso = new FileSystemOptions();
* DelegatingFileSystemOptionsBuilder delegate = new DelegatingFileSystemOptionsBuilder(VFS.getManager());
* delegate.setConfigString(fso, "sftp", "identities", "c:/tmp/test.ident");
* delegate.setConfigString(fso, "http", "proxyPort", "8080");
* delegate.setConfigClass(fso, "sftp", "userinfo", TrustEveryoneUserInfo.class);
*
*
* @author Commons VFS team
*/
public class DelegatingFileSystemOptionsBuilder
{
@SuppressWarnings("unchecked") // OK, it is a String
private static final Class[] STRING_PARAM = new Class[]{String.class};
private static final Map> PRIMATIVE_TO_OBJECT = new TreeMap>();
private final Log log = LogFactory.getLog(DelegatingFileSystemOptionsBuilder.class);
private final FileSystemManager manager;
private final Map