pax_global_header 0000666 0000000 0000000 00000000064 13562475444 0014530 g ustar 00root root 0000000 0000000 52 comment=b2aafb60a3492b0d572fb536f9b1b3eafe852b46
jboss-vfs-3.2.15.Final/ 0000775 0000000 0000000 00000000000 13562475444 0014564 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/.gitignore 0000664 0000000 0000000 00000000123 13562475444 0016550 0 ustar 00root root 0000000 0000000 .idea
*.iml
*.ipr
*.iws
.classpath
.project
.settings
target/
.classpath
.project
jboss-vfs-3.2.15.Final/LICENSE.txt 0000664 0000000 0000000 00000026136 13562475444 0016417 0 ustar 00root root 0000000 0000000
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed 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.
jboss-vfs-3.2.15.Final/archives/ 0000775 0000000 0000000 00000000000 13562475444 0016370 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/ 0000775 0000000 0000000 00000000000 13562475444 0021177 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/ear/ 0000775 0000000 0000000 00000000000 13562475444 0021746 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/ear/pom.xml 0000664 0000000 0000000 00000002565 13562475444 0023273 0 ustar 00root root 0000000 0000000 4.0.0web_pkg_scope earorg.jboss.vfsweb_pkg_scope_ear1.0-SNAPSHOTearorg.jboss.vfsweb_pkg_scope_web1.0-SNAPSHOTwarweb_pkg_scope
jboss-vfs-3.2.15.Final/archives/web_pkg_scope/pom.xml 0000664 0000000 0000000 00000001033 13562475444 0022511 0 ustar 00root root 0000000 0000000 4.0.0web_pkg_scope parentorg.jboss.vfsweb_pkg_scope1.0-SNAPSHOTpomearwar
jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/ 0000775 0000000 0000000 00000000000 13562475444 0021770 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/pom.xml 0000664 0000000 0000000 00000001337 13562475444 0023311 0 ustar 00root root 0000000 0000000 4.0.0web_pkg_scope warorg.jboss.vfsweb_pkg_scope_webwar1.0-SNAPSHOTorg.jboss.vfsweb_pkg_scope1.0-SNAPSHOTweb_pkg_scope_web
jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/ 0000775 0000000 0000000 00000000000 13562475444 0022557 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/ 0000775 0000000 0000000 00000000000 13562475444 0023503 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/java/ 0000775 0000000 0000000 00000000000 13562475444 0024424 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/java/web_pkg_scope/ 0000775 0000000 0000000 00000000000 13562475444 0027233 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/java/web_pkg_scope/entity/ 0000775 0000000 0000000 00000000000 13562475444 0030547 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/java/web_pkg_scope/entity/Account.java 0000664 0000000 0000000 00000001527 13562475444 0033013 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2007, Red Hat Middleware LLC, and individual contributors
* by the @authors tag.
*
* Licensed 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 web_pkg_scope.entity;
/**
* Placeholder for an entity bean
* @author Scott.Stark@jboss.org
* @version $Revision:$
*/
public class Account
{
}
jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/java/web_pkg_scope/servlet/ 0000775 0000000 0000000 00000000000 13562475444 0030717 5 ustar 00root root 0000000 0000000 JpaServlet.java 0000664 0000000 0000000 00000001526 13562475444 0033566 0 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/java/web_pkg_scope/servlet /*
* JBoss, Home of Professional Open Source
* Copyright 2007, Red Hat Middleware LLC, and individual contributors
* by the @authors tag.
*
* Licensed 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 web_pkg_scope.servlet;
/**
* Placeholder for a servlet
* @author Scott.Stark@jboss.org
* @version $Revision:$
*/
public class JpaServlet
{
}
jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/resources/ 0000775 0000000 0000000 00000000000 13562475444 0025515 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/resources/META-INF/ 0000775 0000000 0000000 00000000000 13562475444 0026655 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/resources/META-INF/persistence.xml 0000664 0000000 0000000 00000000543 13562475444 0031725 0 ustar 00root root 0000000 0000000
Persistence Unit Package Testsjdbc/DB1
jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/webapp/ 0000775 0000000 0000000 00000000000 13562475444 0024761 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/webapp/WEB-INF/ 0000775 0000000 0000000 00000000000 13562475444 0026010 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/archives/web_pkg_scope/war/src/main/webapp/WEB-INF/web.xml 0000664 0000000 0000000 00000002037 13562475444 0027311 0 ustar 00root root 0000000 0000000
web_pkg_scopeServletTestweb_pkg_scope.servlet.JpaServletServletTest/ServletTest54My Entity Managerpersistence/MyEMAccountManagerTransaction
jboss-vfs-3.2.15.Final/checkstyle.xml 0000664 0000000 0000000 00000005607 13562475444 0017454 0 ustar 00root root 0000000 0000000
jboss-vfs-3.2.15.Final/pom.xml 0000664 0000000 0000000 00000015656 13562475444 0016116 0 ustar 00root root 0000000 0000000
org.jbossjboss-parent204.0.0org.jbossjboss-vfsjar3.2.15.FinalJBoss VFShttp://www.jboss.orgA VFS libraryaslhttp://repository.jboss.org/licenses/apache-2.0.txtrepoJBoss, A division of Red Hat, Inchttp://www.jboss.orgJIRAhttps://issues.jboss.org/browse/JBVFSscm:git:git://github.com/jbossas/jboss-vfs.gitscm:git:git@github.com:jbossas/jboss-vfs.githttps://github.com/jbossas/jboss-vfsjboss-vfs-3.2.7.Final3.1.4.GA1.2.0.Final1.1.9.GA4.111.61.61.7org.apache.maven.pluginsmaven-checkstyle-pluginorg.apache.maven.pluginsmaven-surefire-plugin${version.surefire.plugin}falsetrueorg.apache.maven.pluginsmaven-checkstyle-plugin${version.checkstyle.plugin}checkstyle.xmltruetruetrue**/*$logger.java,**/*$bundle.javacheck-stylecompilecheckstyleorg.jboss.loggingjboss-logging${version.org.jboss.logging.jboss-logging}compileorg.jboss.loggingjboss-logging-annotations${version.org.jboss.logging.jboss-logging-tools}providedorg.jboss.loggingjboss-logging-processor${version.org.jboss.logging.jboss-logging-tools}providedorg.jboss.testjboss-test${version.jboss.test}testorg.apache.antantorg.apache.antant-junitorg.jboss.jbossasjboss-server-managerjboss.profiler.jvmtijboss-profiler-jvmtilog4jlog4jorg.jboss.loggingjboss-logging-spiorg.jboss.loggingjboss-logging-log4jjunitjunit${version.junit}test
jboss-vfs-3.2.15.Final/src/ 0000775 0000000 0000000 00000000000 13562475444 0015353 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/ 0000775 0000000 0000000 00000000000 13562475444 0016277 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/ 0000775 0000000 0000000 00000000000 13562475444 0017220 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/ 0000775 0000000 0000000 00000000000 13562475444 0020007 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/ 0000775 0000000 0000000 00000000000 13562475444 0021127 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/ 0000775 0000000 0000000 00000000000 13562475444 0021725 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/BasicMountHandle.java 0000664 0000000 0000000 00000004247 13562475444 0025757 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import org.jboss.vfs.spi.FileSystem;
import org.jboss.vfs.spi.MountHandle;
/**
* MountHandle implementation. Provides the default behavior
* of delegating to the FileSystem to get the mount source as
* well as cleaning up resources.
*
* @author John Bailey
*/
class BasicMountHandle implements MountHandle {
private final FileSystem fileSystem;
private final Closeable mountHandle;
private final Closeable[] closeables;
/**
* Create new DefaultMountHandle with a FileSystem and an array of closeable.
*
* @param fileSystem to use to retrieve the mount source
* @param mountHandle the handle to close the actual mount
* @param additionalCloseables addition Closeable to execute on close
*/
BasicMountHandle(final FileSystem fileSystem, Closeable mountHandle, Closeable... additionalCloseables) {
this.fileSystem = fileSystem;
this.mountHandle = mountHandle;
this.closeables = additionalCloseables;
}
/* {@inheritDoc} */
public File getMountSource() {
return fileSystem.getMountSource();
}
/* {@inheritDoc} */
public void close() throws IOException {
VFSUtils.safeClose(fileSystem);
VFSUtils.safeClose(mountHandle);
for (Closeable closeable : closeables) {
VFSUtils.safeClose(closeable);
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/TempDir.java 0000664 0000000 0000000 00000007356 13562475444 0024147 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A temporary directory which exists until it is closed, at which time its contents will be removed.
*
* @author David M. Lloyd
*/
public final class TempDir implements Closeable {
private final TempFileProvider provider;
private final File root;
private final AtomicBoolean open = new AtomicBoolean(true);
TempDir(TempFileProvider provider, File root) {
this.provider = provider;
this.root = root;
}
/**
* Get the {@code File} that represents the root of this temporary directory. The returned file is only valid as
* long as the tempdir exists.
*
* @return the root file
* @throws IOException if the directory was closed at the time of this invocation
*/
public File getRoot() throws IOException {
if (!open.get()) {
throw VFSMessages.MESSAGES.tempDirectoryClosed();
}
return root;
}
/**
* Get the {@code File} for a relative path. The returned file is only valid as long as the tempdir exists.
*
* @param relativePath the relative path
* @return the corresponding file
* @throws IOException if the directory was closed at the time of this invocation
*/
public File getFile(String relativePath) throws IOException {
if (!open.get()) {
throw VFSMessages.MESSAGES.tempDirectoryClosed();
}
return new File(root, relativePath);
}
/**
* Create a file within this temporary directory, prepopulating the file from the given input stream.
*
* @param relativePath the relative path name
* @param sourceData the source input stream to use
* @return the file
* @throws IOException if the directory was closed at the time of this invocation or an error occurs
*/
public File createFile(String relativePath, InputStream sourceData) throws IOException {
final File tempFile = getFile(relativePath);
boolean ok = false;
try {
final FileOutputStream fos = new FileOutputStream(tempFile);
try {
VFSUtils.copyStream(sourceData, fos);
fos.close();
sourceData.close();
ok = true;
return tempFile;
} finally {
VFSUtils.safeClose(fos);
}
} finally {
VFSUtils.safeClose(sourceData);
if (!ok) {
tempFile.delete();
}
}
}
/**
* Close this directory. The contents of the directory will be removed.
*
* @throws IOException if an I/O error occurs
*/
public void close() throws IOException {
if (open.getAndSet(false)) {
provider.delete(root);
}
}
protected void finalize() throws Throwable {
VFSUtils.safeClose(this);
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/TempFileProvider.java 0000664 0000000 0000000 00000022110 13562475444 0026004 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
/**
* A provider for temporary physical files and directories.
*
* @author David M. Lloyd
* @author Ales Justin
*/
public final class TempFileProvider implements Closeable {
private static final String JBOSS_TMP_DIR_PROPERTY = "jboss.server.temp.dir";
private static final String JVM_TMP_DIR_PROPERTY = "java.io.tmpdir";
private static final File TMP_ROOT;
private static final int RETRIES = 10;
private final AtomicBoolean open = new AtomicBoolean(true);
static {
String configTmpDir = System.getProperty(JBOSS_TMP_DIR_PROPERTY);
if (configTmpDir == null) { configTmpDir = System.getProperty(JVM_TMP_DIR_PROPERTY); }
try {
TMP_ROOT = new File(configTmpDir, "vfs");
TMP_ROOT.mkdirs();
} catch (Exception e) {
throw VFSMessages.MESSAGES.cantSetupTempFileProvider(e);
}
}
/**
* Create a temporary file provider for a given type.
*
* This is the same as calling {@link #create(String, java.util.concurrent.ScheduledExecutorService, boolean) create(final String providerType, final ScheduledExecutorService executor, false)}
*
* @param providerType the provider type string (used as a prefix in the temp file dir name)
* @param executor the executor
* @return the new provider
* @throws IOException if an I/O error occurs
*/
public static TempFileProvider create(String providerType, ScheduledExecutorService executor) throws IOException {
return create(providerType, executor, false);
}
/**
* Create a temporary file provider for a given type.
*
* @param providerType The provider type string (used as a prefix in the temp file dir name)
* @param executor Executor which will be used to manage temp file provider tasks (like cleaning up/deleting the temp files when needed)
* @param cleanExisting If this is true, then this method will *try* to delete the existing temp content (if any) for the providerType. The attempt to delete the existing content (if any)
* will be done in the background and this method will not wait for the deletion to complete. The method will immediately return back with a usable {@link TempFileProvider}. Note that the
* cleanExisting will just act as a hint for this method to trigger the deletion of existing content. The method may not always be able to delete the existing contents.
* @return The new provider
* @throws IOException if an I/O error occurs
*/
public static TempFileProvider create(final String providerType, final ScheduledExecutorService executor, final boolean cleanExisting) throws IOException {
if (cleanExisting) {
try {
// The "clean existing" logic is as follows:
// 1) Rename the root directory "foo" corresponding to the provider type to "bar"
// 2) Submit a task to delete "bar" and its contents, in a background thread, to the the passed executor.
// 3) Create a "foo" root directory for the provider type and return that TempFileProvider (while at the same time the background task is in progress)
// This ensures that the "foo" root directory for the providerType is empty and the older content is being cleaned up in the background (without affecting the current processing),
// thus simulating a "cleanup existing content"
final File possiblyExistingProviderRoot = new File(TMP_ROOT, providerType);
if (possiblyExistingProviderRoot.exists()) {
// rename it so that it can be deleted as a separate (background) task
final File toBeDeletedProviderRoot = new File(TMP_ROOT, createTempName(providerType + "-to-be-deleted-", ""));
final boolean renamed = possiblyExistingProviderRoot.renameTo(toBeDeletedProviderRoot);
if (!renamed) {
throw new IOException("Failed to rename " + possiblyExistingProviderRoot.getAbsolutePath() + " to " + toBeDeletedProviderRoot.getAbsolutePath());
} else {
// delete in the background
executor.submit(new DeleteTask(toBeDeletedProviderRoot, executor));
}
}
} catch (Throwable t) {
// just log a message if existing contents couldn't be deleted
VFSLogger.ROOT_LOGGER.failedToCleanExistingContentForTempFileProvider(providerType);
// log the cause of the failure
VFSLogger.ROOT_LOGGER.debug("Failed to clean existing content for temp file provider of type " + providerType, t);
}
}
// now create and return the TempFileProvider for the providerType
final File providerRoot = new File(TMP_ROOT, providerType);
return new TempFileProvider(createTempDir(providerType, "", providerRoot), executor);
}
private final File providerRoot;
private final ScheduledExecutorService executor;
File getProviderRoot() {
return providerRoot;
}
private TempFileProvider(File providerRoot, ScheduledExecutorService executor) {
this.providerRoot = providerRoot;
this.executor = executor;
}
/**
* Create a temp directory, into which temporary files may be placed.
*
* @param originalName the original file name
* @return the temp directory
* @throws IOException for any error
*/
public TempDir createTempDir(String originalName) throws IOException {
if (!open.get()) {
throw VFSMessages.MESSAGES.tempFileProviderClosed();
}
final String name = createTempName(originalName + "-", "");
final File f = new File(providerRoot, name);
for (int i = 0; i < RETRIES; i++) {
if (f.mkdirs()) {
return new TempDir(this, f);
}
}
throw VFSMessages.MESSAGES.couldNotCreateDirectory(originalName,RETRIES);
}
private static final Random rng = new Random();
private static File createTempDir(String prefix, String suffix, File root) throws IOException {
for (int i = 0; i < RETRIES; i++) {
final File f = new File(root, createTempName(prefix, suffix));
if (f.mkdirs()) {
if (f.isDirectory()&&f.getParent()!=null){
f.delete();
}
return f;
}
}
throw VFSMessages.MESSAGES.couldNotCreateDirectoryForRoot(
root,
prefix,
suffix,
RETRIES);
}
static String createTempName(String prefix, String suffix) {
return prefix + Long.toHexString(rng.nextLong()) + suffix;
}
/**
* Close this provider and delete any temp files associated with it.
*/
public void close() throws IOException {
if (open.getAndSet(false)) {
delete(this.providerRoot);
}
}
protected void finalize() {
VFSUtils.safeClose(this);
}
/**
* Deletes any temp files associated with this provider
*
* @throws IOException
*/
void delete(final File root) throws IOException {
new DeleteTask(root, executor).run();
}
static final class DeleteTask implements Runnable {
private final File root;
private ScheduledExecutorService retryExecutor;
DeleteTask(final File root, final ScheduledExecutorService retryExecutor) {
this.root = root;
this.retryExecutor = retryExecutor;
}
public void run() {
if (VFSUtils.recursiveDelete(root) == false) {
if (retryExecutor != null) {
VFSLogger.ROOT_LOGGER.tracef("Failed to delete root (%s), retrying in 30sec.", root);
retryExecutor.schedule(this, 30L, TimeUnit.SECONDS);
} else {
VFSLogger.ROOT_LOGGER.tracef("Failed to delete root (%s).", root);
}
}
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VFS.java 0000664 0000000 0000000 00000062616 13562475444 0023241 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.io.Closeable;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.AbstractSet;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.vfs.spi.AssemblyFileSystem;
import org.jboss.vfs.spi.FileSystem;
import org.jboss.vfs.spi.JavaZipFileSystem;
import org.jboss.vfs.spi.MountHandle;
import org.jboss.vfs.spi.RealFileSystem;
import org.jboss.vfs.spi.RootFileSystem;
/**
* Virtual File System
*
* @author Adrian Brock
* @author Scott.Stark@jboss.org
* @author Ales Justin
* @author David M. Lloyd
* @version $Revision: 1.1 $
*/
public class VFS {
private static final ConcurrentMap> mounts = new ConcurrentHashMap>();
private static final VirtualFile rootVirtualFile = createDefaultRoot();
private static VirtualFile createDefaultRoot() {
return isWindows() ? getChild("/") : new VirtualFile("/", null);
}
// Note that rootVirtualFile is ignored by RootFS
private static final Mount rootMount = new Mount(RootFileSystem.ROOT_INSTANCE, rootVirtualFile);
static {
init();
}
/**
* Do not allow construction
*/
private VFS() {
}
/**
* Initialize VFS protocol handlers package property.
*/
private static void init() {
String pkgs = System.getProperty("java.protocol.handler.pkgs");
if (pkgs == null || pkgs.trim().length() == 0) {
pkgs = "org.jboss.net.protocol|org.jboss.vfs.protocol";
System.setProperty("java.protocol.handler.pkgs", pkgs);
} else if (pkgs.contains("org.jboss.vfs.protocol") == false) {
if (pkgs.contains("org.jboss.net.protocol") == false) { pkgs += "|org.jboss.net.protocol"; }
pkgs += "|org.jboss.vfs.protocol";
System.setProperty("java.protocol.handler.pkgs", pkgs);
}
}
/**
* Mount a filesystem on a mount point in the VFS. The mount point is any valid file name, existent or non-existent.
* If a relative path is given, it will be treated as relative to the VFS root.
*
* @param mountPoint the mount point
* @param fileSystem the file system to mount
* @return a handle which can be used to unmount the filesystem
* @throws IOException if an I/O error occurs, such as a filesystem already being mounted at the given mount point
*/
public static Closeable mount(VirtualFile mountPoint, FileSystem fileSystem) throws IOException {
final VirtualFile parent = mountPoint.getParent();
if (parent == null) {
throw VFSMessages.MESSAGES.rootFileSystemAlreadyMounted();
}
final String name = mountPoint.getName();
final Mount mount = new Mount(fileSystem, mountPoint);
final ConcurrentMap> mounts = VFS.mounts;
for (; ; ) {
Map childMountMap = mounts.get(parent);
Map newMap;
if (childMountMap == null) {
childMountMap = mounts.putIfAbsent(parent, Collections.singletonMap(name, mount));
if (childMountMap == null) {
return mount;
}
}
newMap = new HashMap(childMountMap);
if (newMap.put(name, mount) != null) {
throw VFSMessages.MESSAGES.fileSystemAlreadyMountedAtMountPoint(mountPoint);
}
if (mounts.replace(parent, childMountMap, newMap)) {
VFSLogger.ROOT_LOGGER.tracef("Mounted filesystem %s on mount point %s", fileSystem, mountPoint);
return mount;
}
}
}
/**
* Find a virtual file.
*
* @param url the URL whose path component is the child path
* @return the child
* @throws IllegalArgumentException if the path is null
* @throws java.net.URISyntaxException for any uri error
* @deprecated use getChild(URI) instead
*/
@Deprecated
public static VirtualFile getChild(URL url) throws URISyntaxException {
return getChild(url.toURI());
}
private static boolean isWindows() {
// Not completely accurate, but good enough
return File.separatorChar == '\\';
}
/**
* Find a virtual file.
*
* @param uri the URI whose path component is the child path
* @return the child
* @throws IllegalArgumentException if the path is null
*/
public static VirtualFile getChild(URI uri) {
String path = uri.getPath();
if(path == null) {
path = uri.getSchemeSpecificPart();
}
return getChild(path);
}
/**
* Find a virtual file.
*
* @param path the child path
* @return the child
* @throws IllegalArgumentException if the path is null
*/
public static VirtualFile getChild(String path) {
if (path == null) {
throw VFSMessages.MESSAGES.nullArgument("path");
}
VirtualFile root = null;
if (isWindows()) {
// Normalize the path using java.io.File
// TODO Consider creating our own normalization routine, which would
// allow for testing on non-Windows
String absolute = new File(path).getAbsolutePath();
if (absolute.length() > 2) {
if (absolute.charAt(1) == ':') {
// Drive form
root = new VirtualFile("/" + absolute.charAt(0) + ":/", null);
path = absolute.substring(2).replace('\\', '/');
} else if (absolute.charAt(0) == '\\' && absolute.charAt(1) == '\\') {
// UNC form
for (int i = 2; i < absolute.length(); i++) {
if (absolute.charAt(i) == '\\') {
// Switch \\ to // just like java file URLs.
// Note, it turns out that File.toURL puts this portion
// in the path portion of the URL, which is actually not
// correct, since // is supposed to signify the authority.
root = new VirtualFile("//" + absolute.substring(0, i) + "/", null);
path = absolute.substring(i).replace('\\', '/');
break;
}
}
}
}
if (root == null) {
throw MESSAGES.invalidWin32Path(path);
}
} else {
root = rootVirtualFile;
}
return root.getChild(path);
}
/**
* Get the root virtual file for this VFS instance.
*
* @return the root virtual file
*/
public static VirtualFile getRootVirtualFile() {
return rootVirtualFile;
}
/**
* Get the children
*
* @return the children
* @throws IOException for any problem accessing the virtual file system
*/
public static List getChildren() throws IOException {
return getRootVirtualFile().getChildren(null);
}
/**
* Get the children
*
* @param filter to filter the children
* @return the children
* @throws IOException for any problem accessing the virtual file system
*/
public static List getChildren(VirtualFileFilter filter) throws IOException {
return getRootVirtualFile().getChildren(filter);
}
/**
* Get all the children recursively
*
* This always uses {@link VisitorAttributes#RECURSE}
*
* @return the children
* @throws IOException for any problem accessing the virtual file system
*/
public static List getChildrenRecursively() throws IOException {
return getRootVirtualFile().getChildrenRecursively(null);
}
/**
* Get all the children recursively
*
* This always uses {@link VisitorAttributes#RECURSE}
*
* @param filter to filter the children
* @return the children
* @throws IOException for any problem accessing the virtual file system
*/
public static List getChildrenRecursively(VirtualFileFilter filter) throws IOException {
return getRootVirtualFile().getChildrenRecursively(filter);
}
/**
* Visit the virtual file system from the root
*
* @param visitor the visitor
* @throws IOException for any problem accessing the VFS
* @throws IllegalArgumentException if the visitor is null
*/
public static void visit(VirtualFileVisitor visitor) throws IOException {
visitor.visit(getRootVirtualFile());
}
/**
* Visit the virtual file system
*
* @param file the file
* @param visitor the visitor
* @throws IOException for any problem accessing the VFS
* @throws IllegalArgumentException if the file or visitor is null
*/
protected static void visit(VirtualFile file, VirtualFileVisitor visitor) throws IOException {
if (file == null) {
throw VFSMessages.MESSAGES.nullArgument("file");
}
visitor.visit(file);
}
static Mount getMount(VirtualFile virtualFile) {
final ConcurrentMap> mounts = VFS.mounts;
for (; ; ) {
final VirtualFile parent = virtualFile.getParent();
if (parent == null) {
return rootMount;
}
final Map parentMounts = mounts.get(parent);
if (parentMounts == null) {
virtualFile = parent;
} else {
final Mount mount = parentMounts.get(virtualFile.getName());
if (mount == null) {
virtualFile = parent;
} else {
return mount;
}
}
}
}
/**
* Get all immediate submounts for a path.
*
* @param virtualFile the path
* @return the collection of present mount (simple) names
*/
static Set getSubmounts(VirtualFile virtualFile) {
final ConcurrentMap> mounts = VFS.mounts;
final Map mountMap = mounts.get(virtualFile);
if (mountMap == null) {
return emptyRemovableSet();
}
return new HashSet(mountMap.keySet());
}
private static MountHandle doMount(final FileSystem fileSystem, final VirtualFile mountPoint, Closeable... additionalCloseables) throws IOException {
boolean ok = false;
try {
final Closeable mountHandle = mount(mountPoint, fileSystem);
ok = true;
return new BasicMountHandle(fileSystem, mountHandle, additionalCloseables);
} finally {
if (!ok) {
VFSUtils.safeClose(fileSystem);
}
}
}
/**
* Create and mount a zip file into the filesystem, returning a single handle which will unmount and close the file
* system when closed.
*
* @param zipFile the zip file to mount
* @param mountPoint the point at which the filesystem should be mounted
* @param tempFileProvider the temporary file provider
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountZip(File zipFile, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException {
boolean ok = false;
final TempDir tempDir = tempFileProvider.createTempDir(zipFile.getName());
try {
final MountHandle handle = doMount(new JavaZipFileSystem(zipFile, tempDir), mountPoint);
ok = true;
return handle;
} finally {
if (!ok) {
VFSUtils.safeClose(tempDir);
}
}
}
/**
* Create and mount a zip file into the filesystem, returning a single handle which will unmount and close the file
* system when closed.
*
* @param zipData an input stream containing the zip data
* @param zipName the name of the archive
* @param mountPoint the point at which the filesystem should be mounted
* @param tempFileProvider the temporary file provider
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountZip(InputStream zipData, String zipName, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException {
boolean ok = false;
try {
final TempDir tempDir = tempFileProvider.createTempDir(zipName);
try {
final MountHandle handle = doMount(new JavaZipFileSystem(zipName, zipData, tempDir), mountPoint);
ok = true;
return handle;
} finally {
if (!ok) {
VFSUtils.safeClose(tempDir);
}
}
} finally {
VFSUtils.safeClose(zipData);
}
}
/**
* Create and mount a zip file into the filesystem, returning a single handle which will unmount and close the file
* system when closed.
*
* @param zipFile a zip file in the VFS
* @param mountPoint the point at which the filesystem should be mounted
* @param tempFileProvider the temporary file provider
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountZip(VirtualFile zipFile, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException {
return mountZip(zipFile.openStream(), zipFile.getName(), mountPoint, tempFileProvider);
}
/**
* Create and mount a real file system, returning a single handle which will unmount and close the filesystem when
* closed.
*
* @param realRoot the real filesystem root
* @param mountPoint the point at which the filesystem should be mounted
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountReal(File realRoot, VirtualFile mountPoint) throws IOException {
return doMount(new RealFileSystem(realRoot), mountPoint);
}
/**
* Create and mount a temporary file system, returning a single handle which will unmount and close the filesystem
* when closed.
*
* @param mountPoint the point at which the filesystem should be mounted
* @param tempFileProvider the temporary file provider
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountTemp(VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException {
boolean ok = false;
final TempDir tempDir = tempFileProvider.createTempDir("tmpfs");
try {
final MountHandle handle = doMount(new RealFileSystem(tempDir.getRoot()), mountPoint, tempDir);
ok = true;
return handle;
} finally {
if (!ok) {
VFSUtils.safeClose(tempDir);
}
}
}
/**
* Create and mount an expanded zip file in a temporary file system, returning a single handle which will unmount and
* close the filesystem when closed.
*
* @param zipFile the zip file to mount
* @param mountPoint the point at which the filesystem should be mounted
* @param tempFileProvider the temporary file provider
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountZipExpanded(File zipFile, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException {
boolean ok = false;
final TempDir tempDir = tempFileProvider.createTempDir(zipFile.getName());
try {
final File rootFile = tempDir.getRoot();
VFSUtils.unzip(zipFile, rootFile);
final MountHandle handle = doMount(new RealFileSystem(rootFile), mountPoint, tempDir);
ok = true;
return handle;
} finally {
if (!ok) {
VFSUtils.safeClose(tempDir);
}
}
}
/**
* Create and mount an expanded zip file in a temporary file system, returning a single handle which will unmount and
* close the filesystem when closed. The given zip data stream is closed.
*
* @param zipData an input stream containing the zip data
* @param zipName the name of the archive
* @param mountPoint the point at which the filesystem should be mounted
* @param tempFileProvider the temporary file provider
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountZipExpanded(InputStream zipData, String zipName, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException {
try {
boolean ok = false;
final TempDir tempDir = tempFileProvider.createTempDir(zipName);
try {
final File zipFile = File.createTempFile(zipName + "-", ".tmp", tempDir.getRoot());
try {
final FileOutputStream os = new FileOutputStream(zipFile);
try {
// allow an error on close to terminate the unzip
VFSUtils.copyStream(zipData, os);
zipData.close();
os.close();
} finally {
VFSUtils.safeClose(zipData);
VFSUtils.safeClose(os);
}
final File rootFile = tempDir.getRoot();
VFSUtils.unzip(zipFile, rootFile);
final MountHandle handle = doMount(new RealFileSystem(rootFile), mountPoint, tempDir);
ok = true;
return handle;
} finally {
//noinspection ResultOfMethodCallIgnored
zipFile.delete();
}
} finally {
if (!ok) {
VFSUtils.safeClose(tempDir);
}
}
} finally {
VFSUtils.safeClose(zipData);
}
}
/**
* Create and mount an expanded zip file in a temporary file system, returning a single handle which will unmount and
* close the filesystem when closed. The given zip data stream is closed.
*
* @param zipFile a zip file in the VFS
* @param mountPoint the point at which the filesystem should be mounted
* @param tempFileProvider the temporary file provider
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountZipExpanded(VirtualFile zipFile, VirtualFile mountPoint, TempFileProvider tempFileProvider) throws IOException {
return mountZipExpanded(zipFile.openStream(), zipFile.getName(), mountPoint, tempFileProvider);
}
/**
* Create and mount an assembly file system, returning a single handle which will unmount and
* close the filesystem when closed.
*
* @param assembly an {@link VirtualFileAssembly} to mount in the VFS
* @param mountPoint the point at which the filesystem should be mounted
* @return a handle
* @throws IOException if an error occurs
*/
public static Closeable mountAssembly(VirtualFileAssembly assembly, VirtualFile mountPoint) throws IOException {
return doMount(new AssemblyFileSystem(assembly), mountPoint);
}
@SuppressWarnings({"unchecked"})
private static Set emptyRemovableSet() {
return EMPTY_REMOVABLE_SET;
}
@SuppressWarnings("unchecked")
private static final Set EMPTY_REMOVABLE_SET = new EmptyRemovableSet();
private static final class EmptyRemovableSet extends AbstractSet {
public boolean remove(Object o) {
return false;
}
public boolean retainAll(Collection> c) {
return false;
}
public void clear() {
}
public Iterator iterator() {
return Collections.emptySet().iterator();
}
public int size() {
return 0;
}
}
/**
* The mount representation. This instance represents a binding between a position in the virtual filesystem and the
* backing filesystem implementation; the same {@code FileSystem} may be mounted in more than one place, however only
* one {@code FileSystem} may be bound to a specific path at a time.
*/
static final class Mount implements Closeable {
private final FileSystem fileSystem;
private final VirtualFile mountPoint;
private final StackTraceElement[] allocationPoint;
private final AtomicBoolean closed = new AtomicBoolean(false);
Mount(FileSystem fileSystem, VirtualFile mountPoint) {
this.fileSystem = fileSystem;
this.mountPoint = mountPoint;
allocationPoint = Thread.currentThread().getStackTrace();
}
public void close() throws IOException {
if (closed.getAndSet(true)) {
return;
}
final String name = mountPoint.getName();
final VirtualFile parent = mountPoint.getParent();
final ConcurrentMap> mounts = VFS.mounts;
for (; ; ) {
final Map parentMounts = mounts.get(parent);
if (parentMounts == null) {
return;
}
final VFS.Mount mount = parentMounts.get(name);
if (mount != this) {
return;
}
final Map newParentMounts;
if (parentMounts.size() == 2) {
final Iterator> ei = parentMounts.entrySet().iterator();
final Map.Entry e1 = ei.next();
if (e1.getKey().equals(name)) {
final Map.Entry e2 = ei.next();
newParentMounts = Collections.singletonMap(e2.getKey(), e2.getValue());
} else {
newParentMounts = Collections.singletonMap(e1.getKey(), e1.getValue());
}
if (mounts.replace(parent, parentMounts, newParentMounts)) {
VFSLogger.ROOT_LOGGER.tracef("Unmounted filesystem %s on mount point %s", fileSystem, mountPoint);
return;
}
} else if (parentMounts.size() == 1) {
if (mounts.remove(parent, parentMounts)) {
VFSLogger.ROOT_LOGGER.tracef("Unmounted filesystem %s on mount point %s", fileSystem, mountPoint);
return;
}
} else {
newParentMounts = new HashMap(parentMounts);
newParentMounts.remove(name);
if (mounts.replace(parent, parentMounts, newParentMounts)) {
VFSLogger.ROOT_LOGGER.tracef("Unmounted filesystem %s on mount point %s", fileSystem, mountPoint);
return;
}
}
}
}
FileSystem getFileSystem() {
return fileSystem;
}
VirtualFile getMountPoint() {
return mountPoint;
}
@SuppressWarnings({"FinalizeDoesntCallSuperFinalize"})
protected void finalize() throws IOException {
if (!closed.get()) {
final StackTraceElement[] allocationPoint = this.allocationPoint;
if (allocationPoint != null) {
final LeakDescriptor t = new LeakDescriptor();
t.setStackTrace(allocationPoint);
VFSLogger.ROOT_LOGGER.vfsMountLeaked(mountPoint, t);
} else {
VFSLogger.ROOT_LOGGER.vfsMountLeaked(mountPoint, null);
}
close();
}
}
}
private static final class LeakDescriptor extends Throwable {
private static final long serialVersionUID = 6034058126740270584L;
public String toString() {
return "Allocation stack trace:";
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VFSInputSource.java 0000664 0000000 0000000 00000003360 13562475444 0025431 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs;
import java.io.InputStream;
import org.jboss.vfs.util.LazyInputStream;
import org.xml.sax.InputSource;
/**
* VFS based impl of InputSource.
*
* @author Ales Justin
*/
public class VFSInputSource extends InputSource {
private VirtualFile file;
public VFSInputSource(VirtualFile file) {
if (file == null) {
throw VFSMessages.MESSAGES.nullArgument("file");
}
this.file = file;
}
@Override
public String getSystemId() {
try {
return VFSUtils.getVirtualURI(file).toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
@Override
public InputStream getByteStream() {
return new LazyInputStream(file);
}
@Override
public String toString() {
return file.getPathName();
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VFSLogger.java 0000664 0000000 0000000 00000002157 13562475444 0024373 0 ustar 00root root 0000000 0000000 package org.jboss.vfs;
import org.jboss.logging.BasicLogger;
import org.jboss.logging.Logger;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.LogMessage;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageLogger;
import static org.jboss.logging.Logger.Level.WARN;
import static org.jboss.logging.Logger.Level.INFO;
/**
* @author Tomaz Cerar (c) 2013 Red Hat Inc.
*/
@MessageLogger(projectCode = "VFS")
public interface VFSLogger extends BasicLogger {
/**
* A logger with a category of the package name.
*/
VFSLogger ROOT_LOGGER = Logger.getMessageLogger(VFSLogger.class, VFSLogger.class.getPackage().getName());
@LogMessage(level = WARN)
@Message(id = 1, value = "A VFS mount (%s) was leaked!")
void vfsMountLeaked(VirtualFile mountPoint, @Cause Throwable cause);
@LogMessage(level = INFO)
@Message(id = 2, value = "Failed to clean existing content for temp file provider of type %s. Enable DEBUG level log to find what caused this")
void failedToCleanExistingContentForTempFileProvider(String providerType);
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VFSMessages.java 0000664 0000000 0000000 00000007057 13562475444 0024727 0 ustar 00root root 0000000 0000000 package org.jboss.vfs;
import java.io.File;
import java.io.IOException;
import org.jboss.logging.Messages;
import org.jboss.logging.annotations.Cause;
import org.jboss.logging.annotations.Message;
import org.jboss.logging.annotations.MessageBundle;
/**
* @author Tomaz Cerar (c) 2013 Red Hat Inc.
*/
@MessageBundle(projectCode = "VFS")
public interface VFSMessages {
/**
* The messages
*/
VFSMessages MESSAGES = Messages.getBundle(VFSMessages.class);
@Message(id = 10, value = "Can't set up temp file provider")
RuntimeException cantSetupTempFileProvider(@Cause Throwable cause);
@Message(id = 11, value = "Temp directory closed")
IOException tempDirectoryClosed();
@Message(id = 12, value = "Temp file provider closed")
IOException tempFileProviderClosed();
// Retired
// @Message(id = 13, value = "Failed to clean existing content for temp file provider of type %s")
// IOException failedToCleanExistingContentForTempFileProvider(String providerType);
@Message(id = 14, value = "Could not create directory for root '%s' (prefix '%s', suffix '%s') after %d attempts")
IOException couldNotCreateDirectoryForRoot(File root, String prefix, String suffix, int retries);
@Message(id = 15, value = "Could not create directory for original name '%s' after %d attempts")
IOException couldNotCreateDirectory(String originalName, int retries);
@Message(id = 16, value = "Root filesystem already mounted")
IOException rootFileSystemAlreadyMounted();
@Message(id = 17, value = "Filesystem already mounted at mount point \"%s\"")
IOException fileSystemAlreadyMountedAtMountPoint(VirtualFile mountPoint);
@Message(id = 18, value = "Stream is closed")
IOException streamIsClosed();
@Message(id = 19, value = "Not a file: '%s'")
IOException notAFile(String path);
@Message(id = 20, value = "Remote host access not supported for URLs of type '%s'")
IOException remoteHostAccessNotSupportedForUrls(String protocol);
@Message(id = 21, value = "%s must not be null")
IllegalArgumentException nullArgument(String name);
@Message(id = 22, value = "Null or empty %s")
IllegalArgumentException nullOrEmpty(String name);
@Message(id = 23, value = "Given parent (%s) is not an ancestor of this virtual file")
IllegalArgumentException parentIsNotAncestor(VirtualFile parent);
@Message(id = 24, value = "Problems creating new directory: %s")
IllegalArgumentException problemCreatingNewDirectory(VirtualFile targetChild);
@Message(id = 25, value = "Invalid Win32 path: %s")
IllegalArgumentException invalidWin32Path(String path);
@Message(id = 26, value = "Cannot decode: %s [%s]")
IllegalArgumentException cannotDecode(String path, String encoding, @Cause Exception e);
@Message(id = 27, value = "Invalid jar signature %s should be %s")
IOException invalidJarSignature(String bytes, String expectedHeader);
@Message(id = 28, value = "Invalid actions string: %s")
IllegalArgumentException invalidActionsString(String actions);
@Message(id = 29, value = "The totalBufferLength must be larger than: %s")
IllegalArgumentException bufferMustBeLargerThan(int minimumBufferLength);
@Message(id = 30, value = "Buffer does not have enough capacity")
IllegalArgumentException bufferDoesntHaveEnoughCapacity();
@Message(id = 31, value = "The preconfigured attributes are immutable")
IllegalStateException preconfiguredAttributesAreImmutable();
@Message(id = 32, value = ".. on root path")
IllegalStateException onRootPath();
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VFSUtils.java 0000664 0000000 0000000 00000116277 13562475444 0024265 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.io.Closeable;
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 java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLStreamHandler;
import java.security.AccessController;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collection;
import java.util.Enumeration;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.StringTokenizer;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.Manifest;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.zip.ZipEntry;
import java.util.zip.ZipFile;
import org.jboss.vfs.protocol.FileURLStreamHandler;
import org.jboss.vfs.protocol.VirtualFileURLStreamHandler;
import org.jboss.vfs.spi.MountHandle;
import org.jboss.vfs.util.PaddedManifestStream;
import org.jboss.vfs.util.PathTokenizer;
import org.jboss.vfs.util.automount.Automounter;
/**
* VFS Utilities
*
* @author Adrian Brock
* @author Ales Justin
* @author David M. Lloyd
* @version $Revision: 1.1 $
*/
public class VFSUtils {
/**
* The default encoding
*/
private static final String DEFAULT_ENCODING = "UTF-8";
/**
* Constant representing the URL vfs protocol
*/
public static final String VFS_PROTOCOL = "vfs";
/**
* Constant representing the system property for forcing case sensitive
*/
public static final String FORCE_CASE_SENSITIVE_KEY = "jboss.vfs.forceCaseSensitive";
/**
* The {@link URLStreamHandler} for the 'vfs' protocol
*/
public static final URLStreamHandler VFS_URL_HANDLER = new VirtualFileURLStreamHandler();
/**
* The {@link URLStreamHandler} for the 'file' protocol
*/
public static final URLStreamHandler FILE_URL_HANDLER = new FileURLStreamHandler();
/**
* The default buffer size to use for copies
*/
public static final int DEFAULT_BUFFER_SIZE = 65536;
/**
* This variable indicates if the FileSystem should force case sensitive independently if
* the underlying file system is case sensitive or not
*/
private static boolean forceCaseSensitive;
static {
forceCaseSensitive = AccessController.doPrivileged(new PrivilegedAction () {
public Boolean run() {
String forceString = System.getProperty(VFSUtils.FORCE_CASE_SENSITIVE_KEY, "false");
return Boolean.valueOf(forceString);
}
});
}
private VFSUtils() {
}
/**
* Get the paths string for a collection of virtual files
*
* @param paths the paths
* @return the string
* @throws IllegalArgumentException for null paths
*/
public static String getPathsString(Collection paths) {
if (paths == null) {
throw MESSAGES.nullArgument("paths");
}
StringBuilder buffer = new StringBuilder();
boolean first = true;
for (VirtualFile path : paths) {
if (path == null) { throw new IllegalArgumentException("Null path in " + paths); }
if (first == false) {
buffer.append(':');
} else {
first = false;
}
buffer.append(path.getPathName());
}
if (first == true) {
buffer.append("");
}
return buffer.toString();
}
/**
* Add manifest paths
*
* @param file the file
* @param paths the paths to add to
* @throws IOException if there is an error reading the manifest or the virtual file is closed
* @throws IllegalStateException if the file has no parent
* @throws IllegalArgumentException for a null file or paths
*/
public static void addManifestLocations(VirtualFile file, List paths) throws IOException {
if (file == null) {
throw MESSAGES.nullArgument("file");
}
if (paths == null) {
throw MESSAGES.nullArgument("paths");
}
boolean trace = VFSLogger.ROOT_LOGGER.isTraceEnabled();
Manifest manifest = getManifest(file);
if (manifest == null) { return; }
Attributes mainAttributes = manifest.getMainAttributes();
String classPath = mainAttributes.getValue(Attributes.Name.CLASS_PATH);
if (classPath == null) {
if (trace) {
VFSLogger.ROOT_LOGGER.tracef("Manifest has no Class-Path for %s", file.getPathName());
}
return;
}
VirtualFile parent = file.getParent();
if (parent == null) {
VFSLogger.ROOT_LOGGER.debugf("%s has no parent.", file);
return;
}
if (trace) {
VFSLogger.ROOT_LOGGER.tracef("Parsing Class-Path: %s for %s parent=%s", classPath, file.getName(), parent.getName());
}
StringTokenizer tokenizer = new StringTokenizer(classPath);
while (tokenizer.hasMoreTokens()) {
String path = tokenizer.nextToken();
try {
VirtualFile vf = parent.getChild(path);
if (vf.exists()) {
if (paths.contains(vf) == false) {
paths.add(vf);
// Recursively process the jar
Automounter.mount(file, vf);
addManifestLocations(vf, paths);
} else if (trace) {
VFSLogger.ROOT_LOGGER.tracef("%s from manifest is already in the classpath %s", vf.getName(), paths);
}
} else if (trace) {
VFSLogger.ROOT_LOGGER.trace("Unable to find " + path + " from " + parent.getName());
}
} catch (IOException e) {
VFSLogger.ROOT_LOGGER.debugf("Manifest Class-Path entry %s ignored for %s reason= %s", path, file.getPathName(), e);
}
}
}
/**
* Get a manifest from a virtual file, assuming the virtual file is the root of an archive
*
* @param archive the root the archive
* @return the manifest or null if not found
* @throws IOException if there is an error reading the manifest or the virtual file is closed
* @throws IllegalArgumentException for a null archive
*/
public static Manifest getManifest(VirtualFile archive) throws IOException {
if (archive == null) {
throw MESSAGES.nullArgument("archive");
}
VirtualFile manifest = archive.getChild(JarFile.MANIFEST_NAME);
if (manifest == null || !manifest.exists()) {
if (VFSLogger.ROOT_LOGGER.isTraceEnabled()) {
VFSLogger.ROOT_LOGGER.tracef("Can't find manifest for %s", archive.getPathName());
}
return null;
}
return readManifest(manifest);
}
/**
* Read the manifest from given manifest VirtualFile.
*
* @param manifest the VF to read from
* @return JAR's manifest
* @throws IOException if problems while opening VF stream occur
*/
public static Manifest readManifest(VirtualFile manifest) throws IOException {
if (manifest == null) {
throw MESSAGES.nullArgument("manifest file");
}
InputStream stream = new PaddedManifestStream(manifest.openStream());
try {
return new Manifest(stream);
} finally {
safeClose(stream);
}
}
/**
* Fix a name (removes any trailing slash)
*
* @param name the name to fix
* @return the fixed name
* @throws IllegalArgumentException for a null name
*/
public static String fixName(String name) {
if (name == null) {
throw MESSAGES.nullArgument("name");
}
int length = name.length();
if (length <= 1) { return name; }
if (name.charAt(length - 1) == '/') { return name.substring(0, length - 1); }
return name;
}
/**
* Decode the path with UTF-8 encoding..
*
* @param path the path to decode
* @return decoded path
*/
public static String decode(String path) {
return decode(path, DEFAULT_ENCODING);
}
/**
* Decode the path.
*
* @param path the path to decode
* @param encoding the encoding
* @return decoded path
*/
public static String decode(String path, String encoding) {
try {
return URLDecoder.decode(path, encoding);
} catch (UnsupportedEncodingException e) {
throw MESSAGES.cannotDecode(path,encoding,e);
}
}
/**
* Get the name.
*
* @param uri the uri
* @return name from uri's path
*/
public static String getName(URI uri) {
if (uri == null) {
throw MESSAGES.nullArgument("uri");
}
String name = uri.getPath();
if (name != null) {
// TODO: Not correct for certain uris like jar:...!/
int lastSlash = name.lastIndexOf('/');
if (lastSlash > 0) { name = name.substring(lastSlash + 1); }
}
return name;
}
/**
* Deal with urls that may include spaces.
*
* @param url the url
* @return uri the uri
* @throws URISyntaxException for any error
*/
public static URI toURI(URL url) throws URISyntaxException {
if (url == null) {
throw MESSAGES.nullArgument("url");
}
try {
return url.toURI();
} catch (URISyntaxException e) {
String urispec = url.toExternalForm();
// Escape percent sign and spaces
urispec = urispec.replaceAll("%", "%25");
urispec = urispec.replaceAll(" ", "%20");
return new URI(urispec);
}
}
/**
* Ensure the url is convertible to URI by encoding spaces and percent characters if necessary
*
* @param url to be sanitized
* @return sanitized URL
* @throws URISyntaxException if URI conversion can't be fixed
* @throws MalformedURLException if an error occurs
*/
public static URL sanitizeURL(URL url) throws URISyntaxException, MalformedURLException {
return toURI(url).toURL();
}
/**
* Copy all the children from the original {@link VirtualFile} the target recursively.
*
* @param original the file to copy children from
* @param target the file to copy the children to
* @throws IOException if any problems occur copying the files
*/
public static void copyChildrenRecursive(VirtualFile original, VirtualFile target) throws IOException {
if (original == null) {
throw MESSAGES.nullArgument("Original VirtualFile");
}
if (target == null) {
throw MESSAGES.nullArgument("Target VirtualFile");
}
List children = original.getChildren();
for (VirtualFile child : children) {
VirtualFile targetChild = target.getChild(child.getName());
File childFile = child.getPhysicalFile();
if (childFile.isDirectory()) {
if (!targetChild.getPhysicalFile().mkdir()) {
throw MESSAGES.problemCreatingNewDirectory(targetChild);
}
copyChildrenRecursive(child, targetChild);
} else {
FileInputStream is = new FileInputStream(childFile);
writeFile(targetChild, is);
}
}
}
/**
* Copy input stream to output stream and close them both
*
* @param is input stream
* @param os output stream
* @throws IOException for any error
*/
public static void copyStreamAndClose(InputStream is, OutputStream os) throws IOException {
copyStreamAndClose(is, os, DEFAULT_BUFFER_SIZE);
}
/**
* Copy input stream to output stream and close them both
*
* @param is input stream
* @param os output stream
* @param bufferSize the buffer size to use
* @throws IOException for any error
*/
public static void copyStreamAndClose(InputStream is, OutputStream os, int bufferSize)
throws IOException {
try {
copyStream(is, os, bufferSize);
// throw an exception if the close fails since some data might be lost
is.close();
os.close();
} finally {
// ...but still guarantee that they're both closed
safeClose(is);
safeClose(os);
}
}
/**
* Copy input stream to output stream without closing streams. Flushes output stream when done.
*
* @param is input stream
* @param os output stream
* @throws IOException for any error
*/
public static void copyStream(InputStream is, OutputStream os) throws IOException {
copyStream(is, os, DEFAULT_BUFFER_SIZE);
}
/**
* Copy input stream to output stream without closing streams. Flushes output stream when done.
*
* @param is input stream
* @param os output stream
* @param bufferSize the buffer size to use
* @throws IOException for any error
*/
public static void copyStream(InputStream is, OutputStream os, int bufferSize)
throws IOException {
if (is == null) {
throw MESSAGES.nullArgument("input stream");
}
if (os == null) {
throw MESSAGES.nullArgument("output stream");
}
byte[] buff = new byte[bufferSize];
int rc;
while ((rc = is.read(buff)) != -1) { os.write(buff, 0, rc); }
os.flush();
}
/**
* Write the given bytes to the given virtual file, replacing its current contents (if any) or creating a new file if
* one does not exist.
*
* @param virtualFile the virtual file to write
* @param bytes the bytes
* @throws IOException if an error occurs
*/
public static void writeFile(VirtualFile virtualFile, byte[] bytes) throws IOException {
final File file = virtualFile.getPhysicalFile();
file.getParentFile().mkdirs();
final FileOutputStream fos = new FileOutputStream(file);
try {
fos.write(bytes);
fos.close();
} finally {
safeClose(fos);
}
}
/**
* Write the content from the given {@link InputStream} to the given virtual file, replacing its current contents (if any) or creating a new file if
* one does not exist.
*
* @param virtualFile the virtual file to write
* @param is the input stream
* @throws IOException if an error occurs
*/
public static void writeFile(VirtualFile virtualFile, InputStream is) throws IOException {
final File file = virtualFile.getPhysicalFile();
file.getParentFile().mkdirs();
final FileOutputStream fos = new FileOutputStream(file);
copyStreamAndClose(is, fos);
}
/**
* Get the virtual URL for a virtual file. This URL can be used to access the virtual file; however, taking the file
* part of the URL and attempting to use it with the {@link java.io.File} class may fail if the file is not present
* on the physical filesystem, and in general should not be attempted.
* Note: if the given VirtualFile refers to a directory at the time of this
* method invocation, a trailing slash will be appended to the URL; this means that invoking
* this method may require a filesystem access, and in addition, may not produce consistent results
* over time.
*
* @param file the virtual file
* @return the URL
* @throws MalformedURLException if the file cannot be coerced into a URL for some reason
* @see VirtualFile#asDirectoryURL()
* @see VirtualFile#asFileURL()
*/
public static URL getVirtualURL(VirtualFile file) throws MalformedURLException {
try {
final URI uri = getVirtualURI(file);
final String scheme = uri.getScheme();
return AccessController.doPrivileged(new PrivilegedExceptionAction() {
@Override
public URL run() throws MalformedURLException{
if (VFS_PROTOCOL.equals(scheme)) {
return new URL(null, uri.toString(), VFS_URL_HANDLER);
} else if ("file".equals(scheme)) {
return new URL(null, uri.toString(), FILE_URL_HANDLER);
} else {
return uri.toURL();
}
}
});
} catch (URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
} catch (PrivilegedActionException e) {
throw (MalformedURLException) e.getException();
}
}
/**
* Get the virtual URI for a virtual file.
* Note: if the given VirtualFile refers to a directory at the time of this
* method invocation, a trailing slash will be appended to the URI; this means that invoking
* this method may require a filesystem access, and in addition, may not produce consistent results
* over time.
*
* @param file the virtual file
* @return the URI
* @throws URISyntaxException if the file cannot be coerced into a URI for some reason
* @see VirtualFile#asDirectoryURI()
* @see VirtualFile#asFileURI()
*/
public static URI getVirtualURI(VirtualFile file) throws URISyntaxException {
return new URI(VFS_PROTOCOL, "", file.getPathName(true), null);
}
/**
* Get a physical URL for a virtual file. See the warnings on the {@link VirtualFile#getPhysicalFile()} method
* before using this method.
*
* @param file the virtual file
* @return the physical file URL
* @throws IOException if an I/O error occurs getting the physical file
*/
public static URL getPhysicalURL(VirtualFile file) throws IOException {
return getPhysicalURI(file).toURL();
}
/**
* Get a physical URI for a virtual file. See the warnings on the {@link VirtualFile#getPhysicalFile()} method
* before using this method.
*
* @param file the virtual file
* @return the physical file URL
* @throws IOException if an I/O error occurs getting the physical file
*/
public static URI getPhysicalURI(VirtualFile file) throws IOException {
return file.getPhysicalFile().toURI();
}
/**
* Get the physical root URL of the filesystem of a virtual file. This URL is suitable for use as a class loader's
* code source or in similar situations where only standard URL types ({@code jar} and {@code file}) are supported.
*
* @param file the virtual file
* @return the root URL
* @throws MalformedURLException if the URL is not valid
*/
public static URL getRootURL(VirtualFile file) throws MalformedURLException {
final URI uri;
try {
uri = getRootURI(file);
} catch (URISyntaxException e) {
throw new MalformedURLException(e.getMessage());
}
return uri.toURL();
}
/**
* Get the physical root URL of the filesystem of a virtual file. This URI is suitable for conversion to a class loader's
* code source URL or in similar situations where only standard URL types ({@code jar} and {@code file}) are supported.
*
* @param file the virtual file
* @return the root URI
* @throws URISyntaxException if the URI is not valid
*/
public static URI getRootURI(final VirtualFile file) throws URISyntaxException {
return VFS.getMount(file).getFileSystem().getRootURI();
}
/**
* Safely close some resource without throwing an exception. Any exception will be logged at TRACE level.
*
* @param c the resource
*/
public static void safeClose(final Closeable c) {
if (c != null) {
try {
c.close();
} catch (Exception e) {
VFSLogger.ROOT_LOGGER.trace("Failed to close resource", e);
}
}
}
/**
* Safely close some resource without throwing an exception. Any exception will be logged at TRACE level.
*
* @param closeables the resources
*/
public static void safeClose(final Closeable... closeables) {
safeClose(Arrays.asList(closeables));
}
/**
* Safely close some resources without throwing an exception. Any exception will be logged at TRACE level.
*
* @param ci the resources
*/
public static void safeClose(final Iterable extends Closeable> ci) {
if (ci != null) {
for (Closeable closeable : ci) {
safeClose(closeable);
}
}
}
/**
* Safely close some resource without throwing an exception. Any exception will be logged at TRACE level.
*
* @param zipFile the resource
*/
public static void safeClose(final ZipFile zipFile) {
if (zipFile != null) {
try {
zipFile.close();
} catch (Exception e) {
VFSLogger.ROOT_LOGGER.trace("Failed to close resource", e);
}
}
}
public static boolean isForceCaseSensitive() {
return forceCaseSensitive;
}
/**
* In case the file system is not case sensitive we compare the canonical path with
* the absolute path of the file after normalized.
* @param file
* @return
*/
public static boolean exists(File file) {
try {
boolean fileExists = file.exists();
if(!forceCaseSensitive || !fileExists) {
return fileExists;
}
String absPath = canonicalize(file.getAbsolutePath());
String canPath = canonicalize(file.getCanonicalPath());
return fileExists && absPath.equals(canPath);
} catch(IOException io) {
return false;
}
}
/**
* Attempt to recursively delete a real file.
*
* @param root the real file to delete
* @return {@code true} if the file was deleted
*/
public static boolean recursiveDelete(File root) {
boolean ok = true;
if (root.isDirectory()) {
final File[] files = root.listFiles();
if (files != null) {
for (File file : files) {
ok &= recursiveDelete(file);
}
}
return ok && (root.delete() || !root.exists());
} else {
ok &= root.delete() || !root.exists();
}
return ok;
}
/**
* Attempt to recursively delete a virtual file.
*
* @param root the virtual file to delete
* @return {@code true} if the file was deleted
*/
public static boolean recursiveDelete(VirtualFile root) {
boolean ok = true;
if (root.isDirectory()) {
final List files = root.getChildren();
for (VirtualFile file : files) {
ok &= recursiveDelete(file);
}
return ok && (root.delete() || !root.exists());
} else {
ok &= root.delete() || !root.exists();
}
return ok;
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original file or directory
* @param destDir the destination directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(File original, File destDir) throws IOException {
final String name = original.getName();
final File destFile = new File(destDir, name);
if (original.isDirectory()) {
destFile.mkdir();
for (File file : original.listFiles()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = new FileInputStream(original);
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original file or directory
* @param destDir the destination directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(File original, VirtualFile destDir) throws IOException {
final String name = original.getName();
final File destFile = destDir.getChild(name).getPhysicalFile();
if (original.isDirectory()) {
destFile.mkdir();
for (File file : original.listFiles()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = new FileInputStream(original);
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original virtual file or directory
* @param destDir the destination directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(VirtualFile original, File destDir) throws IOException {
final String name = original.getName();
final File destFile = new File(destDir, name);
if (original.isDirectory()) {
destFile.mkdir();
for (VirtualFile file : original.getChildren()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = original.openStream();
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
/**
* Recursively copy a file or directory from one location to another.
*
* @param original the original virtual file or directory
* @param destDir the destination virtual directory
* @throws IOException if an I/O error occurs before the copy is complete
*/
public static void recursiveCopy(VirtualFile original, VirtualFile destDir) throws IOException {
final String name = original.getName();
final File destFile = destDir.getChild(name).getPhysicalFile();
if (original.isDirectory()) {
destFile.mkdir();
for (VirtualFile file : original.getChildren()) {
recursiveCopy(file, destFile);
}
} else {
final OutputStream os = new FileOutputStream(destFile);
try {
final InputStream is = original.openStream();
copyStreamAndClose(is, os);
} finally {
// in case the input stream open fails
safeClose(os);
}
}
}
private static final InputStream EMPTY_STREAM = new InputStream() {
public int read() throws IOException {
return -1;
}
};
/**
* Get the empty input stream. This stream always reports an immediate EOF.
*
* @return the empty input stream
*/
public static InputStream emptyStream() {
return EMPTY_STREAM;
}
/**
* Get an input stream that will always be consumable as a Zip/Jar file. The input stream will not be an instance
* of a JarInputStream, but will stream bytes according to the Zip specification. Using this method, a VFS file
* or directory can be written to disk as a normal jar/zip file.
*
* @param virtualFile The virtual to get a jar file input stream for
* @return An input stream returning bytes according to the zip spec
* @throws IOException if any problems occur
*/
public static InputStream createJarFileInputStream(final VirtualFile virtualFile) throws IOException {
if (virtualFile.isDirectory()) {
final VirtualJarInputStream jarInputStream = new VirtualJarInputStream(virtualFile);
return new VirtualJarFileInputStream(jarInputStream);
}
InputStream inputStream = null;
try {
final byte[] expectedHeader = new byte[4];
expectedHeader[0] = (byte) (JarEntry.LOCSIG & 0xff);
expectedHeader[1] = (byte) ((JarEntry.LOCSIG >>> 8) & 0xff);
expectedHeader[2] = (byte) ((JarEntry.LOCSIG >>> 16) & 0xff);
expectedHeader[3] = (byte) ((JarEntry.LOCSIG >>> 24) & 0xff);
inputStream = virtualFile.openStream();
final byte[] bytes = new byte[4];
final int read = inputStream.read(bytes, 0, 4);
if (read < 4 || !Arrays.equals(expectedHeader, bytes)) {
throw MESSAGES.invalidJarSignature(Arrays.toString(bytes), Arrays.toString(expectedHeader));
}
} finally {
safeClose(inputStream);
}
return virtualFile.openStream();
}
/**
* Expand a zip file to a destination directory. The directory must exist. If an error occurs, the destination
* directory may contain a partially-extracted archive, so cleanup is up to the caller.
*
* @param zipFile the zip file
* @param destDir the destination directory
* @throws IOException if an error occurs
*/
public static void unzip(File zipFile, File destDir) throws IOException {
final ZipFile zip = new ZipFile(zipFile);
try {
final Set createdDirs = new HashSet();
final Enumeration extends ZipEntry> entries = zip.entries();
FILES_LOOP:
while (entries.hasMoreElements()) {
final ZipEntry zipEntry = entries.nextElement();
final String name = zipEntry.getName();
final List tokens = PathTokenizer.getTokens(name);
final Iterator it = tokens.iterator();
File current = destDir;
while (it.hasNext()) {
String token = it.next();
if (PathTokenizer.isCurrentToken(token) || PathTokenizer.isReverseToken(token)) {
// invalid file; skip it!
continue FILES_LOOP;
}
current = new File(current, token);
if ((it.hasNext() || zipEntry.isDirectory()) && createdDirs.add(current)) {
current.mkdir();
}
}
if (!zipEntry.isDirectory()) {
final InputStream is = zip.getInputStream(zipEntry);
try {
final FileOutputStream os = new FileOutputStream(current);
try {
VFSUtils.copyStream(is, os);
// allow an error on close to terminate the unzip
is.close();
os.close();
} finally {
VFSUtils.safeClose(os);
}
} finally {
VFSUtils.safeClose(is);
}
// exclude jsp files last modified time change. jasper jsp compiler Compiler.java depends on last modified time-stamp to re-compile jsp files
if (!current.getName().endsWith(".jsp"))
current.setLastModified(zipEntry.getTime());
}
}
} finally {
VFSUtils.safeClose(zip);
}
}
/**
* Return the mount source File for a given mount handle.
*
* @param handle The handle to get the source for
* @return The mount source file or null if the handle does not have a source, or is not a MountHandle
*/
public static File getMountSource(Closeable handle) {
if (handle instanceof MountHandle) { return MountHandle.class.cast(handle).getMountSource(); }
return null;
}
private static final Pattern GLOB_PATTERN = Pattern.compile("(\\*\\*?)|(\\?)|(\\\\.)|(/+)|([^*?]+)");
/**
* Get a regular expression pattern which matches any path names which match the given glob. The glob patterns
* function similarly to {@code ant} file patterns. Valid meta-characters in the glob pattern include:
*
*
"\" - escape the next character (treat it literally, even if it is itself a recognized meta-character)
*
"?" - match any non-slash character
*
"*" - match zero or more non-slash characters
*
"**" - match zero or more characters, including slashes
*
"/" - match one or more slash characters. Consecutive {@code /} characters are collapsed down into one.
*
* In addition, like {@code ant}, if the pattern ends with a {@code /}, then an implicit "**" will be appended.
*
* See also:"Patterns" in the Ant Manual
*
* @param glob the glob to match
* @return the pattern
*/
public static Pattern getGlobPattern(final String glob) {
StringBuilder patternBuilder = new StringBuilder();
patternBuilder.append("^");
final Matcher m = GLOB_PATTERN.matcher(glob);
boolean lastWasSlash = false;
while (m.find()) {
lastWasSlash = false;
String grp;
if ((grp = m.group(1)) != null) {
// match a * or **
if (grp.length() == 2) {
// it's a **
patternBuilder.append(".*");
} else {
// it's a *
patternBuilder.append("[^/]*");
}
} else if ((grp = m.group(2)) != null) {
// match a '?' glob pattern; any non-slash character
patternBuilder.append("[^/]");
} else if ((grp = m.group(3)) != null) {
// backslash-escaped value
patternBuilder.append(grp.charAt(1));
} else if ((grp = m.group(4)) != null) {
// match any number of / chars
patternBuilder.append("/+");
lastWasSlash = true;
} else {
// some other string
patternBuilder.append(Pattern.quote(m.group()));
}
}
if (lastWasSlash) {
// ends in /, append **
patternBuilder.append(".*");
}
patternBuilder.append("$");
return Pattern.compile(patternBuilder.toString());
}
/**
* Canonicalize the given path. Removes all {@code .} and {@code ..} segments from the path.
*
* @param path the relative or absolute possibly non-canonical path
* @return the canonical path
*/
@SuppressWarnings("UnusedLabel") // for documentation
public static String canonicalize(final String path) {
final int length = path.length();
// 0 - start
// 1 - got one .
// 2 - got two .
// 3 - got /
int state = 0;
if (length == 0) {
return path;
}
final char[] targetBuf = new char[length];
// string segment end exclusive
int e = length;
// string cursor position
int i = length;
// buffer cursor position
int a = length - 1;
// number of segments to skip
int skip = 0;
loop:
while (--i >= 0) {
char c = path.charAt(i);
outer:
switch (c) {
case '/': {
inner:
switch (state) {
case 0:
state = 3;
e = i;
break outer;
case 1:
state = 3;
e = i;
break outer;
case 2:
state = 3;
e = i;
skip++;
break outer;
case 3:
e = i;
break outer;
default:
throw new IllegalStateException();
}
// not reached!
}
case '.': {
inner:
switch (state) {
case 0:
state = 1;
break outer;
case 1:
state = 2;
break outer;
case 2:
break inner; // emit!
case 3:
state = 1;
break outer;
default:
throw new IllegalStateException();
}
// fall thru
}
default: {
final int newE = e > 0 ? path.lastIndexOf('/', e - 1) : -1;
final int segmentLength = e - newE - 1;
if (skip > 0) {
skip--;
} else {
if (state == 3) {
targetBuf[a--] = '/';
}
path.getChars(newE + 1, e, targetBuf, (a -= segmentLength) + 1);
}
state = 0;
i = newE + 1;
e = newE;
break;
}
}
}
if (state == 3) {
targetBuf[a--] = '/';
}
return new String(targetBuf, a + 1, length - a - 1);
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualFile.java 0000664 0000000 0000000 00000062451 13562475444 0025026 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.Serializable;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.MalformedURLException;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.security.AccessController;
import java.security.CodeSigner;
import java.security.PrivilegedAction;
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.Set;
import org.jboss.vfs.util.FilterVirtualFileVisitor;
import org.jboss.vfs.util.MatchAllVirtualFileFilter;
import org.jboss.vfs.util.PathTokenizer;
/**
* A virtual file. This is a symbolic reference to a location in the virtual file system hierarchy. Holding a {@code
* VirtualFile} instance gives no guarantees as to the presence or immutability of the referenced file or any of its
* parent path elements.
*
* @author Scott.Stark@jboss.org
* @author adrian@jboss.org
* @author Ales.Justin@jboss.org
* @author David M. Lloyd
* @version $Revision: 44334 $
*/
public final class VirtualFile implements Serializable {
private static final long serialVersionUID = 1L;
private final String name;
private final String lcname;
private final VirtualFile parent;
private final int hashCode;
private String pathName;
VirtualFile(String name, VirtualFile parent) {
this.name = name;
lcname = name.toLowerCase();
this.parent = parent;
int result = parent == null ? 1 : parent.hashCode();
result = 31 * result + name.hashCode();
hashCode = result;
}
/**
* Get the simple VF name (X.java)
*
* @return the simple file name
*/
public String getName() {
return name;
}
/**
* Get the simple VF name mapped to lowercase (x.java) (used by case-insensitive filesystems like ZIP).
*
* @return the lowercase simple file name
* @deprecated should not be used anymore, as the code is case-sensitive from JBVFS-170
*/
public String getLowerCaseName() {
return lcname;
}
/**
* Get the absolute VFS full path name (/xxx/yyy/foo.ear/baz.jar/org/jboss/X.java)
*
* @return the VFS full path name
*/
public String getPathName() {
return getPathName(false);
}
/**
* Get the path name relative to a parent virtual file. If the given virtual file is not a parent of
* this virtual file, then an {@code IllegalArgumentException} is thrown.
*
* @param parent the parent virtual file
* @return the relative path name as a string
* @throws IllegalArgumentException if the given virtual file is not a parent of this virtual file
*/
public String getPathNameRelativeTo(VirtualFile parent) throws IllegalArgumentException {
final StringBuilder builder = new StringBuilder(160);
getPathNameRelativeTo(parent, builder);
return builder.toString();
}
private void getPathNameRelativeTo(VirtualFile parent, StringBuilder builder) {
if (this.parent == null) {
throw VFSMessages.MESSAGES.parentIsNotAncestor(parent);
}
if (this.equals(parent)) {
return;
}
if (!this.parent.equals(parent)) {
this.parent.getPathNameRelativeTo(parent, builder);
builder.append('/');
}
builder.append(name);
}
/**
* Get the absolute VFS full path name. If this is a URL then directory entries will have a trailing slash.
*
* @param url whether or not this path is being used for a URL
* @return the VFS full path name
*/
String getPathName(boolean url) {
if (pathName ==null || pathName.isEmpty()) {
VirtualFile[] path = getParentFiles();
final StringBuilder builder = new StringBuilder(path.length*30+50);
for (int i=path.length-1;i>-1;i--) {
final VirtualFile parent = path[i].parent;
if (parent == null){
builder.append(path[i].name);
}else{
if (parent.parent != null) {
builder.append('/');
}
builder.append(path[i].name);
}
}
pathName = builder.toString();
}
// Perhaps this should be cached to avoid the fs stat call?
return (url && isDirectory())? pathName.concat("/"): pathName;
}
/**
* When the file was last modified
*
* @return the last modified time
*/
public long getLastModified() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Long run() {
return mount.getFileSystem().getLastModified(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().getLastModified(mount.getMountPoint(), this);
}
/**
* Get the size
*
* @return the size
*/
public long getSize() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Long run() {
return mount.getFileSystem().getSize(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().getSize(mount.getMountPoint(), this);
}
/**
* Tests whether the underlying implementation file still exists.
*
* @return true if the file exists, false otherwise.
*/
public boolean exists() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Boolean run() {
return mount.getFileSystem().exists(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().exists(mount.getMountPoint(), this);
}
/**
* Determines whether this virtual file represents a true root of a file system.
* On UNIX, there is only one root "/". Howevever, on Windows there are an infinite
* number of roots that correspond to drives, or UNC paths.
*
* @return {@code true} if this represents a root.
*/
public boolean isRoot() {
return parent == null;
}
/**
* Whether it is a simple leaf of the VFS, i.e. whether it can contain other files
*
* @return {@code true} if a simple file
* @deprecated use {@link #isDirectory()} or {@link #isFile()} instead
*/
@Deprecated
public boolean isLeaf() {
return isFile();
}
/**
* Determine whether the named virtual file is a plain file.
*
* @return {@code true} if it is a plain file, {@code false} otherwise
*/
public boolean isFile() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Boolean run() {
return mount.getFileSystem().isFile(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().isFile(mount.getMountPoint(), this);
}
/**
* Determine whether the named virtual file is a directory.
*
* @return {@code true} if it is a directory, {@code false} otherwise
*/
public boolean isDirectory() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Boolean run() {
return mount.getFileSystem().isDirectory(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().isDirectory(mount.getMountPoint(), this);
}
/**
* Access the file contents.
*
* @return an InputStream for the file contents.
* @throws IOException for any error accessing the file system
*/
public InputStream openStream() throws IOException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
if (isDirectory()) {
return new VirtualJarInputStream(this);
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return doIoPrivileged(new PrivilegedExceptionAction() {
@Override
public InputStream run() throws Exception {
return mount.getFileSystem().openInputStream(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().openInputStream(mount.getMountPoint(), this);
}
/**
* Delete this virtual file
*
* @return {@code true} if file was deleted
*/
public boolean delete() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "delete"));
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return AccessController.doPrivileged(new PrivilegedAction() {
@Override
public Boolean run() {
return mount.getFileSystem().delete(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().delete(mount.getMountPoint(), this);
}
/**
* Get a physical file for this virtual file. Depending on the underlying file system type, this may simply return
* an already-existing file; it may create a copy of a file; or it may reuse a preexisting copy of the file.
* Furthermore, the returned file may or may not have any relationship to other files from the same or any other
* virtual directory.
*
* @return the physical file
* @throws IOException if an I/O error occurs while producing the physical file
*/
public File getPhysicalFile() throws IOException {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "getfile"));
}
final VFS.Mount mount = VFS.getMount(this);
if (sm != null) {
final VirtualFile target = this;
return doIoPrivileged(new PrivilegedExceptionAction() {
@Override
public File run() throws Exception {
return mount.getFileSystem().getFile(mount.getMountPoint(), target);
}
});
}
return mount.getFileSystem().getFile(mount.getMountPoint(), this);
}
private static T doIoPrivileged(PrivilegedExceptionAction action) throws IOException {
try {
return AccessController.doPrivileged(action);
} catch (PrivilegedActionException pe) {
try {
throw pe.getException();
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new UndeclaredThrowableException(e);
}
}
}
/**
* Get a {@code VirtualFile} which represents the parent of this instance.
*
* @return the parent or {@code null} if there is no parent
*/
public VirtualFile getParent() {
return parent;
}
/**
* Get the all the parent files of this virtual file from this file to the root. The leafmost file will be at the
* start of the array, and the rootmost will be at the end.
*
* @return the array of parent files
*/
public VirtualFile[] getParentFiles() {
return getParentFiles(0);
}
/**
* Get the all the parent files of this virtual file from this file to the root as a list. The leafmost file will be
* at the start of the list, and the rootmost will be at the end.
*
* @return the list of parent files
*/
public List getParentFileList() {
return Arrays.asList(getParentFiles());
}
private VirtualFile[] getParentFiles(int idx) {
final VirtualFile[] array;
if (parent == null) {
array = new VirtualFile[idx + 1];
} else {
array = parent.getParentFiles(idx + 1);
}
array[idx] = this;
return array;
}
/**
* Get the children. This is the combined list of real children within this directory, as well as virtual children
* created by submounts.
*
* @return the children
*/
public List getChildren() {
// isDirectory does the read security check
if (!isDirectory()) { return Collections.emptyList(); }
final VFS.Mount mount = VFS.getMount(this);
final Set submounts = VFS.getSubmounts(this);
final List names = mount.getFileSystem().getDirectoryEntries(mount.getMountPoint(), this);
final List virtualFiles = new ArrayList(names.size() + submounts.size());
for (String name : names) {
final VirtualFile child = new VirtualFile(name, this);
virtualFiles.add(child);
submounts.remove(name);
}
for (String name : submounts) {
final VirtualFile child = new VirtualFile(name, this);
virtualFiles.add(child);
}
return virtualFiles;
}
/**
* Get the children
*
* @param filter to filter the children
* @return the children
* @throws IOException for any problem accessing the virtual file system
* @throws IllegalStateException if the file is closed or it is a leaf node
*/
public List getChildren(VirtualFileFilter filter) throws IOException {
// isDirectory does the read security check
if (!isDirectory()) { return Collections.emptyList(); }
if (filter == null) { filter = MatchAllVirtualFileFilter.INSTANCE; }
FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor(filter, null);
visit(visitor);
return visitor.getMatched();
}
/**
* Get all the children recursively
*
* This always uses {@link VisitorAttributes#RECURSE}
*
* @return the children
* @throws IOException for any problem accessing the virtual file system
* @throws IllegalStateException if the file is closed
*/
public List getChildrenRecursively() throws IOException {
return getChildrenRecursively(null);
}
/**
* Get all the children recursively
*
* This always uses {@link VisitorAttributes#RECURSE}
*
* @param filter to filter the children
* @return the children
* @throws IOException for any problem accessing the virtual file system
* @throws IllegalStateException if the file is closed or it is a leaf node
*/
public List getChildrenRecursively(VirtualFileFilter filter) throws IOException {
// isDirectory does the read security check
if (!isDirectory()) { return Collections.emptyList(); }
if (filter == null) { filter = MatchAllVirtualFileFilter.INSTANCE; }
FilterVirtualFileVisitor visitor = new FilterVirtualFileVisitor(filter, VisitorAttributes.RECURSE);
visit(visitor);
return visitor.getMatched();
}
/**
* Visit the virtual file system
*
* @param visitor the visitor
* @throws IOException for any problem accessing the virtual file system
* @throws IllegalArgumentException if the visitor is null
* @throws IllegalStateException if the file is closed
*/
public void visit(VirtualFileVisitor visitor) throws IOException {
visit(visitor, true);
}
private void visit(VirtualFileVisitor visitor, boolean root) throws IOException {
final VisitorAttributes visitorAttributes = visitor.getAttributes();
if (root && visitorAttributes.isIncludeRoot()) { visitor.visit(this); }
// isDirectory does the read security check
if (!isDirectory()) { return; }
for (VirtualFile child : getChildren()) {
// Always visit a leaf, and visit directories when leaves only is false
if (!child.isDirectory() || !visitorAttributes.isLeavesOnly()) { visitor.visit(child); }
if (child.isDirectory() && visitorAttributes.isRecurse(child)) { child.visit(visitor, false); }
}
}
/**
* Get a child virtual file. The child may or may not exist in the virtual filesystem.
*
* @param path the path
* @return the child
* @throws IllegalArgumentException if the path is null
*/
public VirtualFile getChild(String path) {
if (path == null) {
throw VFSMessages.MESSAGES.nullArgument("path");
}
final List pathParts = PathTokenizer.getTokens(path);
VirtualFile current = this;
for (String part : pathParts) {
if (PathTokenizer.isReverseToken(part)) {
final VirtualFile parent = current.parent;
current = parent == null ? current : parent;
} else if (PathTokenizer.isCurrentToken(part) == false) {
current = new VirtualFile(part, current);
}
}
return current;
}
/**
* Get file's current URL. Note: if this VirtualFile refers to a directory at the time of this
* method invocation, a trailing slash will be appended to the URL; this means that invoking
* this method may require a filesystem access, and in addition, may not produce consistent results
* over time.
*
* @return the current url
* @throws MalformedURLException if the URL is somehow malformed
* @see VirtualFile#asDirectoryURL()
* @see VirtualFile#asFileURL()
*/
public URL toURL() throws MalformedURLException {
return VFSUtils.getVirtualURL(this);
}
/**
* Get file's current URI. Note: if this VirtualFile refers to a directory at the time of this
* method invocation, a trailing slash will be appended to the URI; this means that invoking
* this method may require a filesystem access, and in addition, may not produce consistent results
* over time.
*
* @return the current uri
* @throws URISyntaxException if the URI is somehow malformed
* @see VirtualFile#asDirectoryURI()
* @see VirtualFile#asFileURI()
*/
public URI toURI() throws URISyntaxException {
return VFSUtils.getVirtualURI(this);
}
/**
* Get file's URL as a directory. There will always be a trailing {@code "/"} character.
*
* @return the url
* @throws MalformedURLException if the URL is somehow malformed
*/
public URL asDirectoryURL() throws MalformedURLException {
final String pathName = getPathName(false);
return new URL(VFSUtils.VFS_PROTOCOL, "", -1, parent == null ? pathName : pathName + "/", VFSUtils.VFS_URL_HANDLER);
}
/**
* Get file's URI as a directory. There will always be a trailing {@code "/"} character.
*
* @return the uri
* @throws URISyntaxException if the URI is somehow malformed
*/
public URI asDirectoryURI() throws URISyntaxException {
final String pathName = getPathName(false);
return new URI(VFSUtils.VFS_PROTOCOL, "", parent == null ? pathName : pathName + "/", null);
}
/**
* Get file's URL as a file. There will be no trailing {@code "/"} character unless this {@code VirtualFile}
* represents a root.
*
* @return the url
* @throws MalformedURLException if the URL is somehow malformed
*/
public URL asFileURL() throws MalformedURLException {
return new URL(VFSUtils.VFS_PROTOCOL, "", -1, getPathName(false), VFSUtils.VFS_URL_HANDLER);
}
/**
* Get file's URI as a file. There will be no trailing {@code "/"} character unless this {@code VirtualFile}
* represents a root.
*
* @return the url
* @throws URISyntaxException if the URI is somehow malformed
*/
public URI asFileURI() throws URISyntaxException {
return new URI(VFSUtils.VFS_PROTOCOL, "", getPathName(false), null);
}
/**
* Get the {@link CodeSigner}s for a the virtual file.
*
* @return the {@link CodeSigner}s for the virtual file, or {@code null} if not signed
*/
public CodeSigner[] getCodeSigners() {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new VirtualFilePermission(getPathName(), "read"));
}
final VFS.Mount mount = VFS.getMount(this);
return mount.getFileSystem().getCodeSigners(mount.getMountPoint(), this);
}
/**
* Get the {@link Certificate}s for the virtual file. Simply extracts the certificate entries from
* the code signers array.
*
* @return the certificates for the virtual file, or {@code null} if not signed
*/
public Certificate[] getCertificates() {
// getCodeSigners() does the sec check
final CodeSigner[] codeSigners = getCodeSigners();
if (codeSigners == null) {
return null;
}
final List certList = new ArrayList(codeSigners.length * 3);
for (CodeSigner signer : codeSigners) {
certList.addAll(signer.getSignerCertPath().getCertificates());
}
return certList.toArray(new Certificate[certList.size()]);
}
/**
* Get a human-readable (but non-canonical) representation of this virtual file.
*
* @return the string
*/
public String toString() {
return '"' + getPathName() + '"';
}
/**
* Determine whether the given object is equal to this one. Returns true if the argument is a {@code VirtualFile}
* from the same {@code VFS} instance with the same name.
*
* @param o the other object
* @return {@code true} if they are equal
*/
public boolean equals(Object o) {
return o instanceof VirtualFile && equals((VirtualFile) o);
}
/**
* Determine whether the given object is equal to this one. Returns true if the argument is a {@code VirtualFile}
* from the same {@code VFS} instance with the same name.
*
* @param o the other virtual file
* @return {@code true} if they are equal
*/
public boolean equals(VirtualFile o) {
if (o == this) {
return true;
}
if (o == null || hashCode != o.hashCode || !name.equals(o.name)) {
return false;
}
final VirtualFile parent = this.parent;
final VirtualFile oparent = o.parent;
return parent != null && parent.equals(oparent) || oparent == null;
}
/**
* Get a hashcode for this virtual file.
*
* @return the hash code
*/
public int hashCode() {
return hashCode;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualFileAssembly.java 0000664 0000000 0000000 00000020631 13562475444 0026520 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.security.SecureRandom;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Queue;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import org.jboss.vfs.util.PathTokenizer;
/**
* Assembly of VirtualFiles that can be mounted into the VFS in a structure
* that is not required to match a real filesystem structure.
*
* @author John Bailey
*/
public class VirtualFileAssembly implements Closeable {
private static final Random RANDOM_NUM_GEN = new SecureRandom();
private final AssemblyNode rootNode = new AssemblyNode("");
private final List mountHandles = new CopyOnWriteArrayList();
private final VirtualFile mountRoot = VFS.getChild("assembly-mounts").getChild(getAssemblyId());
private TempFileProvider tempFileProvider;
/**
* Add a {@link VirtualFile} to the assembly.
*
* @param virtualFile
*/
public void add(VirtualFile virtualFile) {
String path = virtualFile.getName();
AssemblyNode assemblyNode = rootNode.findOrBuild(path);
assemblyNode.setTarget(virtualFile);
}
/**
* Add a {@link VirtualFile} to the assembly in a given path.
*
* @param path
* @param virtualFile
*/
public void add(String path, VirtualFile virtualFile) {
AssemblyNode assemblyNode = rootNode.findOrBuild(path);
assemblyNode.setTarget(virtualFile);
}
public void add(final String path, final File root) throws IOException {
VirtualFile mountPoint = mountRoot.getChild(path);
Closeable handle = VFS.mountReal(root, mountPoint);
mountHandles.add(handle);
add(path, mountPoint);
}
public void addZip(final String path, final File zipFile) throws IOException {
VirtualFile mountPoint = mountRoot.getChild(path);
Closeable handle = VFS.mountZip(zipFile, mountPoint, getTempFileProvider());
mountHandles.add(handle);
add(path, mountPoint);
}
/**
* Get the VirtualFile from the assembly. This will traverse VirtualFiles in assembly
* to find children if needed.
*
* @param mountPoint
* @param target
* @return
* @throws IOException
*/
public VirtualFile getFile(VirtualFile mountPoint, VirtualFile target) {
final String path = target.getPathNameRelativeTo(mountPoint);
return rootNode.getFile(new Path(path), mountPoint);
}
/**
* Returns a list of all the names of the children in the assembly.
*
* @return
*/
public List getChildNames(VirtualFile mountPoint, VirtualFile target) {
List names = new LinkedList();
AssemblyNode targetNode = null;
if (mountPoint.equals(target)) {
targetNode = rootNode;
} else {
targetNode = rootNode.find(target.getPathNameRelativeTo(mountPoint));
}
if (targetNode != null) {
for (AssemblyNode childNode : targetNode.children.values()) {
names.add(childNode.realName);
}
}
return names;
}
public boolean contains(VirtualFile mountPoint, VirtualFile target) {
final String path = target.getPathNameRelativeTo(mountPoint);
return rootNode.find(path) != null;
}
/**
* Close the assembly and nested resources.
*/
public void close() {
VFSUtils.safeClose(mountHandles);
}
/**
* @return
* @throws IOException
*/
private TempFileProvider getTempFileProvider() throws IOException {
if (tempFileProvider == null) {
tempFileProvider = TempFileProvider.create("temp", Executors.newSingleThreadScheduledExecutor());
}
return tempFileProvider;
}
private String getAssemblyId() {
return Long.toHexString(RANDOM_NUM_GEN.nextLong());
}
/**
* Path representation to hold onto the elements of the path.
*/
private static class Path {
private final Queue parts;
private Path(String path) {
parts = new LinkedList();
List tokens = PathTokenizer.getTokens(path);
parts.addAll(tokens);
}
private boolean isEndOfPath() {
return parts.isEmpty();
}
private String getCurrent() {
return parts.poll();
}
}
/**
* Node located within the assembly.
*/
private static class AssemblyNode {
private final Map children = new ConcurrentHashMap();
private final String realName;
private VirtualFile target;
AssemblyNode(String realName) {
this.realName = realName;
}
/**
* Find an AssemblyNode staring with this node and return null if not found.
*
* @param path
* @return
*/
public AssemblyNode find(String path) {
return find(new Path(path), false);
}
/**
* Find an AssemblyNode starting with this node and build the required nodes if not found.
*
* @param path
* @return
*/
public AssemblyNode findOrBuild(String path) {
return find(new Path(path), true);
}
/**
* Find an AssemblyNode starting with this node.
*
* @param path
* @param createIfMissing
* @return
*/
public AssemblyNode find(Path path, boolean createIfMissing) {
if (path.isEndOfPath()) {
return this;
}
String current = path.getCurrent();
AssemblyNode childNode = getChild(current);
if (childNode == null) {
if (!createIfMissing) {
return null;
}
childNode = new AssemblyNode(current);
addChild(current, childNode);
}
return childNode.find(path, createIfMissing);
}
/**
* Get the VirtualFile for a given path. Will traverse VirtualFile links if not
* found in the assembly.
*
* @param path
* @return
* @throws IOException
*/
public VirtualFile getFile(Path path, VirtualFile assemblyMountPoint) {
if (path.isEndOfPath()) {
return target;
}
String current = path.getCurrent();
AssemblyNode childNode = getChild(current);
if (childNode != null) {
return childNode.getFile(path, assemblyMountPoint);
}
if (target != null) {
VirtualFile currentFile = target != null ? target.getChild(current) : null;
if (currentFile != null) {
while (!path.isEndOfPath()) {
current = path.getCurrent();
currentFile = currentFile.getChild(current);
if (currentFile == null) {
return null;
}
}
return currentFile;
}
}
return null;
}
private void addChild(String name, AssemblyNode child) {
children.put(name.toLowerCase(), child);
}
private AssemblyNode getChild(String name) {
return children.get(name.toLowerCase());
}
private void setTarget(VirtualFile target) {
this.target = target;
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualFileFilter.java 0000664 0000000 0000000 00000002071 13562475444 0026164 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
/**
* A filter for virtual files
*
* @author Bill Burke
* @author adrian@jboss.org
* @version $Revision: 44334 $
*/
public interface VirtualFileFilter {
/**
* Match the virtual file
*
* @param file the virtual file
* @return true when it matches
*/
boolean accepts(VirtualFile file);
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualFileFilterWithAttributes.java 0000664 0000000 0000000 00000002031 13562475444 0031063 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
/**
* A filter for virtual files with attributes
*
* @author adrian@jboss.org
* @version $Revision: 44334 $
*/
public interface VirtualFileFilterWithAttributes extends VirtualFileFilter {
/**
* Get the attributes for this filter
*
* @return the attributes
*/
VisitorAttributes getAttributes();
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualFilePermission.java 0000664 0000000 0000000 00000020561 13562475444 0027073 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs;
import java.io.Serializable;
import java.security.Permission;
import java.security.PermissionCollection;
/**
* A permission to a file on the virtual file system.
*
* @author David M. Lloyd
* @see java.io.FilePermission
*/
public final class VirtualFilePermission extends Permission implements Serializable {
private static final long serialVersionUID = 1L;
/**
* @serial the action flags (must be within {@link #VALID_FLAGS})
*/
private final int actionFlags;
/**
* The flag value for the "read" action.
*/
public static final int FLAG_READ = Integer.parseInt("0000000000000001",2); //0b0000_0000_0000_0001
/**
* The flag value for the "delete" action.
*/
public static final int FLAG_DELETE = Integer.parseInt("0000000000000010",2); //0b0000_0000_0000_0010;
/**
* The flag value for the "getfile" action.
*/
public static final int FLAG_GET_FILE = Integer.parseInt("0000000000000100",2); //0b0000_0000_0000_0100;
/**
* The set of valid action flags for this permission.
*/
public static final int VALID_FLAGS = Integer.parseInt("0000000000000111",2); //0b0000_0000_0000_0111;
VirtualFilePermission(final String path, final int actionFlags, final boolean canonicalize) {
super(canonicalize ? VFSUtils.canonicalize(path) : path);
this.actionFlags = actionFlags & VALID_FLAGS;
}
/**
* Construct a new instance.
*
* @param path the path
* @param actions the actions to grant
*/
public VirtualFilePermission(final String path, final String actions) {
this(path, parseActions(actions), true);
}
/**
* Construct a new instance. Any flags outside of {@link #VALID_FLAGS} are ignored.
*
* @param path the path
* @param actionFlags the action flags to set
*/
public VirtualFilePermission(final String path, final int actionFlags) {
this(path, actionFlags, true);
}
private static boolean in(char c, char t1, char t2) {
return c == t1 || c == t2;
}
private static boolean lenIs(String s, int idx, int len, int wlen) {
return idx == len - wlen || idx < len - wlen && s.charAt(idx + wlen) == ',';
}
static int parseActions(String actions) {
final int len = actions.length();
int res = 0;
for (int i = 0; i < len; i++) {
if (lenIs(actions, i, len, 4)
&& in(actions.charAt(i), 'r', 'R')
&& in(actions.charAt(i + 1), 'e', 'E')
&& in(actions.charAt(i + 2), 'a', 'A')
&& in(actions.charAt(i + 3), 'd', 'D')) {
res |= FLAG_READ;
i += 4;
} else if (lenIs(actions, i, len, 6)
&& in(actions.charAt(i), 'd', 'D')
&& in(actions.charAt(i + 1), 'e', 'E')
&& in(actions.charAt(i + 2), 'l', 'L')
&& in(actions.charAt(i + 3), 'e', 'E')
&& in(actions.charAt(i + 4), 't', 'T')
&& in(actions.charAt(i + 5), 'e', 'E')) {
res |= FLAG_DELETE;
i += 6;
} else if (lenIs(actions, i, len, 7)
&& in(actions.charAt(i), 'g', 'G')
&& in(actions.charAt(i + 1), 'e', 'E')
&& in(actions.charAt(i + 2), 't', 'T')
&& in(actions.charAt(i + 3), 'f', 'F')
&& in(actions.charAt(i + 4), 'i', 'I')
&& in(actions.charAt(i + 5), 'l', 'L')
&& in(actions.charAt(i + 6), 'e', 'E')) {
res |= FLAG_GET_FILE;
i += 7;
} else if (lenIs(actions, i, len, 1) && actions.charAt(i) == '*') {
res |= FLAG_READ | FLAG_DELETE | FLAG_GET_FILE;
} else {
throw VFSMessages.MESSAGES.invalidActionsString(actions);
}
}
return res;
}
public boolean implies(final Permission permission) {
return permission instanceof VirtualFilePermission && implies((VirtualFilePermission) permission);
}
public boolean implies(final VirtualFilePermission permission) {
return permission != null && impliesUnchecked(permission);
}
private boolean impliesUnchecked(final VirtualFilePermission permission) {
final int theirFlags = permission.actionFlags;
return (actionFlags & theirFlags) == theirFlags && impliesPath(getName(), permission.getName());
}
private static int ourIndexOf(String str, char ch, int start) {
final int idx = str.indexOf(ch, start);
return idx == -1 ? str.length() : idx;
}
static boolean impliesPath(String ourName, String theirName) {
if ("<>".equals(ourName)) {
return true;
}
return impliesPath(ourName, theirName, 0);
}
private static boolean impliesPath(String ourName, String theirName, int idx) {
final int ourLen = ourName.length();
final int theirLen = theirName.length();
final int ei1 = ourIndexOf(ourName, '/', idx);
final int ei2 = ourIndexOf(theirName, '/', idx);
if (ei1 == idx + 1) {
final char ch = ourName.charAt(idx);
if (ch == '-') {
// recursive wildcard...
// if they are non-empty, match
return theirLen > idx; // otherwise their segment is empty (no match)
} else if (ch == '*') {
// non-recursive wildcard...
// if they are non-empty, and this is their last segment, match, unless they are '-'
return theirLen > idx && ei2 == theirLen && (ei2 != ei1 || theirName.charAt(idx) != '-');
}
}
if (ei1 == ei2) {
if (ei1 == ourLen && ei2 == theirLen) {
// exact match
return true;
} else {
// leading sequence matches, check next segment
return impliesPath(ourName, theirName, ei1 + 1);
}
} else {
return false;
}
}
public String getActions() {
final StringBuilder builder = new StringBuilder();
if ((actionFlags & FLAG_READ) != 0) {
builder.append("read");
}
if ((actionFlags & FLAG_DELETE) != 0) {
if (builder.length() > 0) { builder.append(','); }
builder.append("delete");
}
if ((actionFlags & FLAG_GET_FILE) != 0) {
if (builder.length() > 0) { builder.append(','); }
builder.append("getfile");
}
return builder.toString();
}
/**
* Get the action flags for this permission.
*
* @return the action flags for this permission
*/
public int getActionFlags() {
return actionFlags;
}
public PermissionCollection newPermissionCollection() {
return new VirtualFilePermissionCollection();
}
public boolean equals(final Object permission) {
return permission instanceof VirtualFilePermission && equals((VirtualFilePermission) permission);
}
public boolean equals(final Permission permission) {
return permission instanceof VirtualFilePermission && equals((VirtualFilePermission) permission);
}
public boolean equals(final VirtualFilePermission permission) {
return permission != null && permission.actionFlags == actionFlags && permission.getName().equals(permission.getName());
}
public int hashCode() {
return getName().hashCode() * 11 + actionFlags;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualFilePermissionCollection.java 0000664 0000000 0000000 00000011045 13562475444 0031104 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2013, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectStreamField;
import java.lang.reflect.Field;
import java.security.AccessController;
import java.security.Permission;
import java.security.PermissionCollection;
import java.security.PrivilegedAction;
import java.util.Arrays;
import java.util.Enumeration;
final class VirtualFilePermissionCollection extends PermissionCollection {
private static final ObjectStreamField[] serialPersistentFields = {
new ObjectStreamField("list", VirtualFilePermission[].class)
};
private static final VirtualFilePermission[] NO_PERMISSIONS = new VirtualFilePermission[0];
private volatile VirtualFilePermission[] permissions = NO_PERMISSIONS;
private static final Field listField;
static {
listField = AccessController.doPrivileged(new PrivilegedAction() {
public Field run() {
final Field field;
try {
field = VirtualFilePermissionCollection.class.getDeclaredField("permissions");
} catch (NoSuchFieldException e) {
throw new NoSuchFieldError(e.getMessage());
}
field.setAccessible(true);
return field;
}
});
}
VirtualFilePermissionCollection() {
}
public void add(final Permission permission) {
if (permission instanceof VirtualFilePermission) {
add((VirtualFilePermission) permission);
} else {
throw new IllegalArgumentException();
}
}
public synchronized void add(final VirtualFilePermission permission) {
if (permission != null) {
final VirtualFilePermission[] permissions = this.permissions;
final int length = permissions.length;
final VirtualFilePermission[] newPermissions = Arrays.copyOf(permissions, length + 1);
newPermissions[length] = permission;
this.permissions = newPermissions;
} else {
throw new IllegalArgumentException();
}
}
public boolean implies(final Permission permission) {
return permission instanceof VirtualFilePermission && implies((VirtualFilePermission) permission);
}
private boolean implies(final VirtualFilePermission permission) {
assert permission != null; // else the above check would have failed
int remainingFlags = permission.getActionFlags();
if (remainingFlags == 0) { return true; }
// snapshot
final VirtualFilePermission[] permissions = this.permissions;
final String theirName = permission.getName();
for (VirtualFilePermission ourPermission : permissions) {
if (VirtualFilePermission.impliesPath(ourPermission.getName(), theirName)) {
remainingFlags &= ~ourPermission.getActionFlags();
if (remainingFlags == 0) {
return true;
}
}
}
return false;
}
@SuppressWarnings("unchecked")
public Enumeration elements() {
final VirtualFilePermission[] permissions = this.permissions;
return new Enumeration() {
private int idx = 0;
public boolean hasMoreElements() {
return idx < permissions.length;
}
public Permission nextElement() {
return permissions[idx++];
}
};
}
private void readObject(ObjectInputStream ois) throws IOException, ClassNotFoundException {
try {
listField.set(this, ois.readFields().get("list", null));
} catch (IllegalAccessException e) {
throw new IllegalAccessError(e.getMessage());
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualFileVisitor.java 0000664 0000000 0000000 00000002244 13562475444 0026400 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
/**
* Visits a virtual file and its children
*
* @author Adrian Brock
* @version $Revision: 1.1 $
*/
public interface VirtualFileVisitor {
/**
* Get the search attribues for this visitor
*
* @return the attributes
*/
VisitorAttributes getAttributes();
/**
* Visit a virtual file
*
* @param virtualFile the virtual file being visited
*/
void visit(VirtualFile virtualFile);
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualJarFileInputStream.java 0000664 0000000 0000000 00000036001 13562475444 0027647 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.List;
import java.util.jar.JarEntry;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
/**
* An input stream that can be used to wrap an VirtualJarInputStream (so any VFS dir)
* and produce a byte stream following the Zip standard.
*
* @author John Bailey
*/
public class VirtualJarFileInputStream extends InputStream {
// Needs to be sufficiently sized to allow local and central file headers with a single entry name
private static final int MINIMUM_BUFFER_LENGTH = 1024;
private final VirtualJarInputStream virtualJarInputStream;
private State currentState = State.NOT_STARTED;
private final List processedEntries = new LinkedList();
private ProcessedEntry currentEntry;
private final ByteBuffer buffer;
private final CRC32 crc = new CRC32();
private int currentCentralEntryIdx;
private long centralOffset;
private long totalRead;
/**
* Create with the minimum put length
*
* @param virtualJarInputStream The virtual jar input stream to base the stream off of
*/
public VirtualJarFileInputStream(final VirtualJarInputStream virtualJarInputStream) {
this(virtualJarInputStream, MINIMUM_BUFFER_LENGTH);
}
/**
* Create with the a specified put size
*
* @param virtualJarInputStream The virtual jar input stream to base the stream off of
* @param bufferLength The length of put to use
*/
public VirtualJarFileInputStream(final VirtualJarInputStream virtualJarInputStream, int bufferLength) {
if (virtualJarInputStream == null) {
throw VFSMessages.MESSAGES.nullArgument("virtualJarInputStream");
}
if (bufferLength < MINIMUM_BUFFER_LENGTH) {
throw VFSMessages.MESSAGES.bufferMustBeLargerThan(MINIMUM_BUFFER_LENGTH);
}
this.virtualJarInputStream = virtualJarInputStream;
buffer = new ByteBuffer(bufferLength);
}
/**
* {@inheritDoc}
*/
@Override
public int read() throws IOException {
int readByte = -1;
while (currentState != null && (readByte = currentState.read(this)) == -1) {
currentState = currentState.getNextState(this);
}
totalRead++;
return readByte;
}
/**
* {@inheritDoc}
*/
@Override
public void close() throws IOException {
VFSUtils.safeClose(virtualJarInputStream);
super.close();
}
/**
* Close the current entry, and calculate the crc value.
*
* @throws IOException if any problems occur
*/
private void closeCurrent() throws IOException {
virtualJarInputStream.closeEntry();
currentEntry.crc = crc.getValue();
crc.reset();
}
/**
* Buffer the content of the local file header for a single entry.
*
* @return true if the next local file header was buffered
* @throws IOException if any problems occur
*/
private boolean bufferLocalFileHeader() throws IOException {
buffer.reset();
JarEntry jarEntry = virtualJarInputStream.getNextJarEntry();
if (jarEntry == null) { return false; }
currentEntry = new ProcessedEntry(jarEntry, totalRead);
processedEntries.add(currentEntry);
bufferInt(ZipEntry.LOCSIG); // Local file header signature
bufferShort(10); // Extraction version
bufferShort(0); // Flags
bufferShort(ZipEntry.STORED); // Compression type
bufferInt(jarEntry.getTime()); // Entry time
bufferInt(0); // CRC
bufferInt(0); // Compressed size
bufferInt(0); // Uncompressed size
byte[] nameBytes = jarEntry.getName().getBytes("UTF8");
bufferShort(nameBytes.length); // Entry name length
bufferShort(0); // Extra length
buffer(nameBytes);
return true;
}
/**
* Buffer the central file header record for a single entry.
*
* @return true if the next central file header was buffered
* @throws IOException if any problems occur
*/
private boolean bufferNextCentralFileHeader() throws IOException {
buffer.reset();
if (currentCentralEntryIdx == processedEntries.size()) { return false; }
ProcessedEntry entry = processedEntries.get(currentCentralEntryIdx++);
JarEntry jarEntry = entry.jarEntry;
bufferInt(ZipEntry.CENSIG); // Central file header signature
bufferShort(10); // Version made by
bufferShort(10); // Extraction version
bufferShort(0); // Flags
bufferShort(ZipEntry.STORED); // Compression type
bufferInt(jarEntry.getTime()); // Entry time
bufferInt(entry.crc); // CRC
bufferInt(jarEntry.getSize()); // Compressed size
bufferInt(jarEntry.getSize()); // Uncompressed size
byte[] nameBytes = jarEntry.getName().getBytes("UTF8");
bufferShort(nameBytes.length); // Entry name length
bufferShort(0); // Extra field length
bufferShort(0); // File comment length
bufferShort(0); // Disk number start
bufferShort(0); // Internal file attributes
bufferInt(0); // External file attributes
bufferInt(entry.offset); // Relative offset of local header
buffer(nameBytes);
return true;
}
/**
* Write the central file header records. This is repeated
* until all entries have been added to the central file header.
*
* @throws IOException if any problem occur
*/
private void bufferCentralDirectoryEnd() throws IOException {
buffer.reset();
long lengthOfCentral = totalRead - centralOffset;
int count = processedEntries.size();
bufferInt(JarEntry.ENDSIG); // End of central directory signature
bufferShort(0); // Number of this disk
bufferShort(0); // Start of central directory disk
bufferShort(count); // Number of processedEntries on disk
bufferShort(count); // Total number of processedEntries
bufferInt(lengthOfCentral); // Size of central directory
bufferInt(centralOffset); // Offset of start of central directory
bufferShort(0); // Comment Length
}
/**
* Buffer a 32-bit integer in little-endian
*
* @param i A long representation of a 32 bit int
*/
private void bufferInt(long i) {
buffer((byte) (i & 0xff));
buffer((byte) ((i >>> 8) & 0xff));
buffer((byte) ((i >>> 16) & 0xff));
buffer((byte) ((i >>> 24) & 0xff));
}
/**
* Buffer a 16-bit short in little-endian
*
* @param i An int representation of a 16 bit short
*/
private void bufferShort(int i) {
buffer((byte) (i & 0xff));
buffer((byte) ((i >>> 8) & 0xff));
}
/**
* Buffer a single byte
*
* @param b The byte
*/
private void buffer(byte b) {
if (buffer.hasCapacity()) {
buffer.put(b);
} else {
throw VFSMessages.MESSAGES.bufferDoesntHaveEnoughCapacity();
}
}
/**
* Buffer a byte array
*
* @param bytes The bytes
*/
private void buffer(byte[] bytes) {
for (byte b : bytes) { buffer(b); }
}
private class ProcessedEntry {
private final JarEntry jarEntry;
private final long offset;
private long crc;
private ProcessedEntry(final JarEntry jarEntry, final long offset) {
this.jarEntry = jarEntry;
this.offset = offset;
}
}
/**
* Basic state machine that will allow the process to transition between the different process states.
*
* The following describes the process flow:
* [NOT_STARTED] - Initial state
* - Does not provide content
* - Transitions [LOCAL_ENTRY_HEADER]
* [LOCAL_ENTRY_HEADER] - The phase for reading the Local Directory Header
* - Provides content of the local directory header by populating and feeding off a buffer
* - Transitions to [ENTRY_CONTENT] if the header was written
* - Transitions to [START_CENTRAL_DIRECTORY] if this is the last local entry header
* [ENTRY_CONTENT] - The phase for reading the content of an entry
* - Provides content of the entry using the VirtualJarInputStream
* - Transitions to [LOCAL_ENTRY_HEADER]
* [START_CENTRAL_DIRECTORY] - Phased used to transition into the central directory
* - Does not provide content
* - Transitions to [CENTRAL_ENTRY_HEADER]
* [CENTRAL_ENTRY_HEADER] - The phase for reading the content of a single central directory header
* - Provides content for the central directory header by feeding off a buffer
* - Transitions to [CENTRAL_ENTRY_HEADER]
* - Transitions to [CENTRAL_END] if there are no more entries
* [CENTRAL_END] - The phase for reading the contents of the central directory end
* - Provides content for central directory end by feeing off a buffer
* - Transitions to NULL to terminate the processing
*/
private enum State {
NOT_STARTED {
@Override
State transition(VirtualJarFileInputStream jarFileInputStream) throws IOException {
return LOCAL_ENTRY_HEADER;
}
},
LOCAL_ENTRY_HEADER {
boolean buffered;
@Override
void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
buffered = jarFileInputStream.bufferLocalFileHeader();
}
@Override
int read(VirtualJarFileInputStream jarFileInputStream) throws IOException {
final ByteBuffer buffer = jarFileInputStream.buffer;
if (buffered && buffer.hasRemaining()) { return buffer.get(); }
return -1;
}
@Override
State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
if (buffered) { return ENTRY_CONTENT; }
return START_CENTRAL_DIRECTORY;
}
},
ENTRY_CONTENT {
@Override
int read(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
final VirtualJarInputStream virtualJarInputStream = jarFileInputStream.virtualJarInputStream;
return virtualJarInputStream.read();
}
@Override
State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
virtualJarFileInputStream.closeCurrent();
return LOCAL_ENTRY_HEADER;
}
},
START_CENTRAL_DIRECTORY {
@Override
void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
jarFileInputStream.centralOffset = jarFileInputStream.totalRead;
}
@Override
State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
return CENTRAL_ENTRY_HEADER;
}
},
CENTRAL_ENTRY_HEADER {
boolean buffered;
@Override
void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
buffered = jarFileInputStream.bufferNextCentralFileHeader();
}
@Override
int read(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
final ByteBuffer buffer = jarFileInputStream.buffer;
if (buffered && buffer.hasRemaining()) { return buffer.get(); }
return -1;
}
@Override
State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
if (buffered) { return CENTRAL_ENTRY_HEADER; }
return CENTRAL_END;
}
},
CENTRAL_END {
@Override
void init(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
jarFileInputStream.bufferCentralDirectoryEnd();
}
@Override
int read(final VirtualJarFileInputStream jarFileInputStream) throws IOException {
final ByteBuffer buffer = jarFileInputStream.buffer;
if (buffer.hasRemaining()) { return buffer.get(); }
return -1;
}
@Override
State transition(final VirtualJarFileInputStream virtualJarFileInputStream) throws IOException {
return null;
}
};
void init(VirtualJarFileInputStream jarFileInputStream) throws IOException {
}
abstract State transition(VirtualJarFileInputStream virtualJarFileInputStream) throws IOException;
int read(VirtualJarFileInputStream jarFileInputStream) throws IOException {
return -1;
}
State getNextState(VirtualJarFileInputStream jarFileInputStream) throws IOException {
State nextState = transition(jarFileInputStream);
if (nextState != null) { nextState.init(jarFileInputStream); }
return nextState;
}
}
private static class ByteBuffer {
private final int bufferLength;
private final byte[] buffer;
private int bufferPosition;
private int bufferDepth;
private ByteBuffer(final int bufferLength) {
this.buffer = new byte[bufferLength];
this.bufferLength = bufferLength;
}
private boolean hasRemaining() {
return bufferPosition < bufferDepth;
}
private boolean hasCapacity() {
return bufferDepth < bufferLength;
}
private byte get() {
return buffer[bufferPosition++];
}
private void put(byte b) {
buffer[bufferDepth++] = b;
}
private void reset() {
bufferPosition = 0;
bufferDepth = 0;
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VirtualJarInputStream.java 0000664 0000000 0000000 00000021360 13562475444 0027051 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import java.io.IOException;
import java.io.InputStream;
import java.security.CodeSigner;
import java.security.cert.Certificate;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Deque;
import java.util.Iterator;
import java.util.List;
import java.util.jar.Attributes;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.jar.JarInputStream;
import java.util.jar.Manifest;
import java.util.zip.ZipEntry;
/**
* Virtual JarInputStream used for representing any VFS directory as a JarInputStream.
*
* @author John Bailey
*/
public class VirtualJarInputStream extends JarInputStream {
private static final String MANIFEST_NAME = "MANIFEST.MF";
private static final String META_INF_DIR = "META-INF";
private static final VirtualFileFilter MANIFEST_FILTER = new VirtualFileFilter() {
public boolean accepts(VirtualFile file) {
return !MANIFEST_NAME.equalsIgnoreCase(file.getName());
}
};
private final Deque> entryItr = new ArrayDeque>();
private final VirtualFile root;
private final Manifest manifest;
private InputStream currentEntryStream = VFSUtils.emptyStream();
private boolean closed;
/**
* Construct a {@link VirtualJarInputStream} from a {@link VirtualFile} root
*
* @param root VirtualFile directory to use as the base of the virtual Jar.
* @throws IOException
*/
public VirtualJarInputStream(VirtualFile root) throws IOException {
super(VFSUtils.emptyStream());
this.root = root;
final VirtualFile manifest = root.getChild(JarFile.MANIFEST_NAME);
if (manifest.exists()) {
entryItr.add(Collections.singleton(manifest).iterator());
this.manifest = VFSUtils.readManifest(manifest);
} else {
this.manifest = null;
}
entryItr.add(root.getChildren().iterator());
}
/**
* {@inheritDoc} *
*/
@Override
public ZipEntry getNextEntry() throws IOException {
return getNextJarEntry();
}
/**
* {@inheritDoc} *
*/
@Override
public JarEntry getNextJarEntry() throws IOException {
closeEntry();
final Iterator topItr = entryItr.peekFirst();
if (topItr == null) {
return null;
}
if (!topItr.hasNext()) {
entryItr.pop();
return getNextJarEntry();
}
final VirtualFile nextEntry = topItr.next();
String entryName = getEntryName(nextEntry);
if (nextEntry.isDirectory()) {
List children = nextEntry.getChildren();
if (entryName.equalsIgnoreCase(META_INF_DIR)) {
children = nextEntry.getChildren(MANIFEST_FILTER);
}
entryItr.add(children.iterator());
entryName = fixDirectoryName(entryName);
}
openCurrent(nextEntry);
Attributes attributes = null;
final Manifest manifest = getManifest();
if (manifest != null) {
attributes = manifest.getAttributes(entryName);
}
return new VirtualJarEntry(entryName, nextEntry, attributes);
}
/**
* {@inheritDoc} *
*/
@Override
public Manifest getManifest() {
return manifest;
}
/**
* {@inheritDoc} *
*/
@Override
public int read() throws IOException {
ensureOpen();
return checkForEoSAndReturn(currentEntryStream.read());
}
/**
* {@inheritDoc} *
*/
@Override
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* {@inheritDoc} *
*/
@Override
public int read(byte[] b, int off, int len) throws IOException {
ensureOpen();
return checkForEoSAndReturn(currentEntryStream.read(b, off, len));
}
/**
* {@inheritDoc} *
*/
@Override
public int available() throws IOException {
ensureOpen();
return currentEntryStream.available() > 0 ? 1 : 0;
}
/**
* {@inheritDoc} *
*/
@Override
public void close() throws IOException {
closed = true;
}
/**
* {@inheritDoc} *
*/
@Override
public void closeEntry() throws IOException {
if (currentEntryStream != null) {
currentEntryStream.close();
}
}
/**
* {@inheritDoc} *
*/
@Override
public long skip(long n) throws IOException {
ensureOpen();
return currentEntryStream.skip(n);
}
/**
* {@inheritDoc} *
*/
private void ensureOpen() throws IOException {
if (closed) {
throw VFSMessages.MESSAGES.streamIsClosed();
}
}
/**
* Check to see if the result is the EOF and if so exchange the current entry stream with the empty stream.
*
* @param result
* @return int result
* @throws IOException
*/
private int checkForEoSAndReturn(int result) throws IOException {
if (result == -1) {
closeEntry();
currentEntryStream = VFSUtils.emptyStream();
}
return result;
}
/**
* Open the current virtual file as the current JarEntry stream.
*
* @param current
* @throws IOException
*/
private void openCurrent(VirtualFile current) throws IOException {
if (current.isDirectory()) {
currentEntryStream = VFSUtils.emptyStream();
} else {
currentEntryStream = current.openStream();
}
}
/**
* Get the entry name from a VirtualFile.
*
* @param entry
* @return
*/
private String getEntryName(VirtualFile entry) {
return entry.getPathNameRelativeTo(root);
}
/**
* Make sure directory names end with a trailing slash
*
* @param name
* @return
*/
private String fixDirectoryName(String name) {
if (!name.endsWith("/")) {
return name + "/";
}
return name;
}
/**
* Virtual JarEntry used for representing a child VirtualFile as a JarEntry.
*
* @author John Bailey
* @version $Revision: 1.1 $
*/
public static class VirtualJarEntry extends JarEntry {
private final VirtualFile virtualFile;
private final Attributes attributes;
/**
* Construct a new
*
* @param name
* @param virtualFile
* @param attributes
*/
public VirtualJarEntry(String name, VirtualFile virtualFile, Attributes attributes) {
super(name);
this.virtualFile = virtualFile;
this.attributes = attributes;
}
/**
* {@inheritDoc} *
*/
@Override
public Attributes getAttributes() throws IOException {
return attributes;
}
/**
* {@inheritDoc} *
*/
@Override
public long getSize() {
return virtualFile.getSize();
}
@Override
public long getTime() {
return virtualFile.getLastModified();
}
/**
* {@inheritDoc} *
*/
@Override
public boolean isDirectory() {
return virtualFile.isDirectory();
}
/**
* {@inheritDoc} *
*/
@Override
public Certificate[] getCertificates() {
final CodeSigner[] signers = getCodeSigners();
if (signers == null) {
return null;
}
final List certs = new ArrayList();
for (CodeSigner signer : signers) {
certs.addAll(signer.getSignerCertPath().getCertificates());
}
return certs.toArray(new Certificate[certs.size()]);
}
/**
* {@inheritDoc} *
*/
@Override
public CodeSigner[] getCodeSigners() {
return virtualFile.getCodeSigners();
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/VisitorAttributes.java 0000664 0000000 0000000 00000015607 13562475444 0026307 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs;
import static org.jboss.vfs.VFSMessages.MESSAGES;
/**
* Attributes used when visiting a virtual file system
*
* @author Adrian Brock
* @author Scott.Stark@jboss.org
* @version $Revision: 1.1 $
*/
public class VisitorAttributes {
/**
* A VirtualFileFilter than accepts any file
*/
public static final AcceptAnyFilter RECURSE_ALL = new AcceptAnyFilter();
/**
* The default attributes - visit leaves and non-leaves, no recursion, no root
*/
public static final VisitorAttributes DEFAULT = new ImmutableVisitorAttributes();
/**
* Visit leaves only and do not recurse non-leaf files
*/
public static final VisitorAttributes LEAVES_ONLY = new ImmutableVisitorAttributes(true, null);
/**
* Recurse and visit all non-leaf files
*/
public static final VisitorAttributes RECURSE = new ImmutableVisitorAttributes(false, RECURSE_ALL);
/**
* Recurse all non-leaf files but only visit leaves
*/
public static final VisitorAttributes RECURSE_LEAVES_ONLY = new ImmutableVisitorAttributes(true, RECURSE_ALL);
/**
* Whether to include the root
*/
private boolean includeRoot;
/**
* Whether to only visit leaves
*/
private boolean leavesOnly;
/**
* Whether to ignore individual file errors
*/
private boolean ignoreErrors;
/**
* Whether to include hidden files
*/
private boolean includeHidden;
/**
* A filter used to control whether a non-leaf is recursive visited
*/
private VirtualFileFilter recurseFilter;
/**
* Whether to visit leaves only
*
* Default: false
*
* @return the visit leaves only.
*/
public boolean isLeavesOnly() {
return leavesOnly;
}
/**
* Set the leaves only.
*
* @param leavesOnly the leaves only
* @throws IllegalStateException if you attempt to modify one of the preconfigured static values of this class
*/
public void setLeavesOnly(boolean leavesOnly) {
this.leavesOnly = leavesOnly;
}
/**
* Whether to recurse into the non-leaf file
. If there is a recurse filter then the result will by its
* accepts(file) value.
*
* Default: false
*
* @param file the file
* @return the recurse flag.
*/
public boolean isRecurse(VirtualFile file) {
boolean recurse = false;
if (recurseFilter != null) { recurse = recurseFilter.accepts(file); }
return recurse;
}
/**
* Get the recurse filter.
*
* @return the current recurse filter.
*/
public VirtualFileFilter getRecurseFilter() {
return recurseFilter;
}
/**
* Set the recurse filter.
*
* @param filter - the recurse filter.
* @throws IllegalStateException if you attempt to modify one of the preconfigured static values of this class
*/
public void setRecurseFilter(VirtualFileFilter filter) {
recurseFilter = filter;
}
/**
* Whether to include the root of the visit
*
* Default: false
*
* @return the includeRoot.
*/
public boolean isIncludeRoot() {
return includeRoot;
}
/**
* Set the includeRoot.
*
* @param includeRoot the includeRoot.
* @throws IllegalStateException if you attempt to modify one of the preconfigured static values of this class
*/
public void setIncludeRoot(boolean includeRoot) {
this.includeRoot = includeRoot;
}
/**
* Whether to ignore individual errors
*
* Default: false
*
* @return the ignoreErrors.
*/
public boolean isIgnoreErrors() {
return ignoreErrors;
}
/**
* Set the ignoreErrors.
*
* @param ignoreErrors the ignoreErrors.
* @throws IllegalStateException if you attempt to modify one of the preconfigured static values of this class
*/
public void setIgnoreErrors(boolean ignoreErrors) {
this.ignoreErrors = ignoreErrors;
}
/**
* Whether to include hidden files
*
* Default: false
*
* @return the includeHidden.
*/
public boolean isIncludeHidden() {
return includeHidden;
}
/**
* Set the includeHidden.
*
* @param includeHidden the includeHidden.
* @throws IllegalStateException if you attempt to modify one of the preconfigured static values of this class
*/
public void setIncludeHidden(boolean includeHidden) {
this.includeHidden = includeHidden;
}
private static class AcceptAnyFilter implements VirtualFileFilter {
public boolean accepts(VirtualFile file) {
return true;
}
}
/**
* Immutable version of the attribues
*/
private static class ImmutableVisitorAttributes extends VisitorAttributes {
/**
* Create a new ImmutableVirtualFileVisitorAttributes with default values
*/
ImmutableVisitorAttributes() {
}
/**
* Create a new ImmutableVirtualFileVisitorAttributes.
*
* @param leavesOnly whether to visit leaves only
* @param recurseFilter - filter which controls whether to recurse
*/
ImmutableVisitorAttributes(boolean leavesOnly, VirtualFileFilter recurseFilter) {
super.setLeavesOnly(leavesOnly);
super.setRecurseFilter(recurseFilter);
}
@Override
public void setLeavesOnly(boolean leavesOnly) {
throw MESSAGES.preconfiguredAttributesAreImmutable();
}
@Override
public void setIncludeRoot(boolean includeRoot) {
throw MESSAGES.preconfiguredAttributesAreImmutable();
}
@Override
public void setRecurseFilter(VirtualFileFilter filter) {
throw MESSAGES.preconfiguredAttributesAreImmutable();
}
@Override
public void setIgnoreErrors(boolean ignoreErrors) {
throw MESSAGES.preconfiguredAttributesAreImmutable();
}
@Override
public void setIncludeHidden(boolean includeHidden) {
throw MESSAGES.preconfiguredAttributesAreImmutable();
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/ 0000775 0000000 0000000 00000000000 13562475444 0023566 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/AbstractLocalURLStreamHandler.java 0000664 0000000 0000000 00000004171 13562475444 0032207 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2010, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol;
import java.io.IOException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import java.util.HashSet;
import java.util.Set;
import org.jboss.vfs.VFSMessages;
/**
* Abstract URLStreamHandler that can be used as a base for other URLStreamHandlers that
* require the URL to be local.
*
* @author John Bailey
* @version $Revision$
*/
public abstract class AbstractLocalURLStreamHandler extends URLStreamHandler {
private static final Set locals;
static {
Set set = new HashSet();
set.add(null);
set.add("");
set.add("~");
set.add("localhost");
locals = set;
}
private static String toLower(String str) {
return str == null ? null : str.toLowerCase();
}
@Override
protected URLConnection openConnection(URL u, Proxy p) throws IOException {
return openConnection(u);
}
@Override
protected boolean hostsEqual(URL url1, URL url2) {
return locals.contains(toLower(url1.getHost())) && locals.contains(toLower(url2.getHost())) || super.hostsEqual(url1, url2);
}
protected void ensureLocal(URL url) throws IOException {
if (!locals.contains(toLower(url.getHost()))) {
throw VFSMessages.MESSAGES.remoteHostAccessNotSupportedForUrls(url.getProtocol());
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/AbstractURLConnection.java 0000664 0000000 0000000 00000006172 13562475444 0030605 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2010, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol;
import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.net.URLConnection;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;
import org.jboss.vfs.VFSUtils;
/**
* Abstract base class for VFS URLConection impls.
*
* @author John Bailey
* @version $Revision$
*/
public abstract class AbstractURLConnection extends URLConnection {
private String contentType;
protected AbstractURLConnection(final URL url) {
super(url);
}
public String getHeaderField(String name) {
String headerField = null;
if (name.equals("content-type")) {
headerField = getContentType();
} else if (name.equals("content-length")) {
headerField = String.valueOf(getContentLength());
} else if (name.equals("last-modified")) {
long lastModified = getLastModified();
if (lastModified != 0) {
// return the last modified date formatted according to RFC 1123
Date modifiedDate = new Date(lastModified);
SimpleDateFormat sdf = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss 'GMT'", Locale.US);
sdf.setTimeZone(TimeZone.getTimeZone("GMT"));
headerField = sdf.format(modifiedDate);
}
} else {
headerField = super.getHeaderField(name);
}
return headerField;
}
public String getContentType() {
if (contentType != null) { return contentType; }
contentType = getFileNameMap().getContentTypeFor(getName());
if (contentType == null) {
try {
InputStream is = getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
contentType = java.net.URLConnection.guessContentTypeFromStream(bis);
bis.close();
} catch (IOException e) { /* ignore */ }
}
return contentType;
}
protected static URI toURI(URL url) throws IOException {
try {
return VFSUtils.toURI(url);
} catch (URISyntaxException e) {
IOException ioe = new IOException();
ioe.initCause(e);
throw ioe;
}
}
protected abstract String getName();
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/FileURLConnection.java 0000664 0000000 0000000 00000004476 13562475444 0027726 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2010, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Permission;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.spi.RootFileSystem;
/**
* Implementation URLConnection that will delegate to the VFS RootFileSystem.
*
* @author John Bailey
* @version $Revision$
*/
public class FileURLConnection extends AbstractURLConnection {
private final RootFileSystem rootFileSystem = RootFileSystem.ROOT_INSTANCE;
private final VirtualFile mountPoint = VFS.getRootVirtualFile();
private final VirtualFile file;
public FileURLConnection(URL url) throws IOException {
super(url);
file = VFS.getChild(toURI(url));
}
public File getContent() throws IOException {
return rootFileSystem.getFile(mountPoint, file);
}
public int getContentLength() {
final long size = rootFileSystem.getSize(mountPoint, file);
return size > (long) Integer.MAX_VALUE ? -1 : (int) size;
}
public long getLastModified() {
return rootFileSystem.getLastModified(mountPoint, file);
}
public InputStream getInputStream() throws IOException {
return rootFileSystem.openInputStream(mountPoint, file);
}
@Override
public Permission getPermission() throws IOException {
return new FilePermission(file.getPathName(), "read");
}
public void connect() throws IOException {
}
@Override
protected String getName() {
return file.getName();
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/FileURLStreamHandler.java 0000664 0000000 0000000 00000002243 13562475444 0030346 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2010, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
/**
* A File based URLStreamHandler
*
* @author John Bailey
* @version $Revision$
*/
public class FileURLStreamHandler extends AbstractLocalURLStreamHandler {
@Override
protected URLConnection openConnection(final URL url) throws IOException {
ensureLocal(url);
return new FileURLConnection(url);
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/VfsUrlStreamHandlerFactory.java 0000664 0000000 0000000 00000002635 13562475444 0031662 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2010, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol;
import java.net.URLStreamHandler;
import java.net.URLStreamHandlerFactory;
import java.util.HashMap;
import java.util.Map;
/**
* URLStreamHandlerFactory providing URLStreamHandlers for VFS based URLS.
*
* @author John Bailey
*/
public class VfsUrlStreamHandlerFactory implements URLStreamHandlerFactory {
private static Map handlerMap = new HashMap(2);
static {
handlerMap.put("file", new FileURLStreamHandler());
handlerMap.put("vfs", new VirtualFileURLStreamHandler());
}
@Override
public URLStreamHandler createURLStreamHandler(final String protocol) {
return handlerMap.get(protocol);
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/VirtualFileURLConnection.java 0000664 0000000 0000000 00000005344 13562475444 0031270 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol;
import java.io.File;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.security.Permission;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VirtualFile;
/**
* Implements basic URLConnection for a VirtualFile
*
* @author Bill Burke
* @author Ales Justin
* @version $Revision: 1.1 $
*/
class VirtualFileURLConnection extends AbstractURLConnection {
private final VirtualFile file;
VirtualFileURLConnection(URL url) throws IOException {
super(url);
file = VFS.getChild(toURI(url));
}
public void connect() throws IOException {
}
public Object getContent() throws IOException {
if (getContentType() != null) {
return super.getContent();
}
return file;
}
public int getContentLength() {
final long size = file.getSize();
return size > (long) Integer.MAX_VALUE ? -1 : (int) size;
}
public long getLastModified() {
return file.getLastModified();
}
public InputStream getInputStream() throws IOException {
return file.openStream();
}
public Permission getPermission() throws IOException {
String decodedPath = toURI(url).getPath();
if (File.separatorChar != '/') { decodedPath = decodedPath.replace('/', File.separatorChar); }
return new FilePermission(decodedPath, "read");
}
@Override
protected String getName() {
return file.getName();
}
@Override
public Object getContent(Class[] classes) throws IOException {
Object obj = super.getContent(classes);
for (int i = 0; i < classes.length; i++) {
if (classes[i] == VirtualFile.class) {
return file;
} else if (classes[i].isInstance(obj)) {
return obj;
}
}
return obj;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/VirtualFileURLStreamHandler.java 0000664 0000000 0000000 00000002123 13562475444 0031712 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
/**
* The VFS URL stream handler.
*/
public class VirtualFileURLStreamHandler extends AbstractLocalURLStreamHandler {
@Override
protected URLConnection openConnection(URL url) throws IOException {
ensureLocal(url);
return new VirtualFileURLConnection(url);
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/file/ 0000775 0000000 0000000 00000000000 13562475444 0024505 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/file/Handler.java 0000664 0000000 0000000 00000001563 13562475444 0026732 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol.file;
import org.jboss.vfs.protocol.FileURLStreamHandler;
/**
* Stub handler class.
*/
public final class Handler extends FileURLStreamHandler {
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/vfs/ 0000775 0000000 0000000 00000000000 13562475444 0024364 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/protocol/vfs/Handler.java 0000664 0000000 0000000 00000001600 13562475444 0026601 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.protocol.vfs;
import org.jboss.vfs.protocol.VirtualFileURLStreamHandler;
/**
* Stub handler class.
*/
public final class Handler extends VirtualFileURLStreamHandler {
} jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/ 0000775 0000000 0000000 00000000000 13562475444 0022520 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/AssemblyFileSystem.java 0000664 0000000 0000000 00000012730 13562475444 0027152 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.CodeSigner;
import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;
import org.jboss.vfs.VFSLogger;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileAssembly;
/**
* FileSystem used to mount an Assembly into the VFS.
*
* @author John Bailey
*/
public class AssemblyFileSystem implements FileSystem {
private final VirtualFileAssembly assembly;
public AssemblyFileSystem(VirtualFileAssembly assembly) {
this.assembly = assembly;
VFSLogger.ROOT_LOGGER.tracef("Constructed a new assembly filesystem for %s", assembly);
}
/**
* {@inheritDoc}
*/
public File getFile(VirtualFile mountPoint, VirtualFile target) throws IOException {
return getExistingFile(mountPoint, target).getPhysicalFile();
}
/**
* {@inheritDoc}
*/
public boolean delete(VirtualFile mountPoint, VirtualFile target) {
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile != null && assemblyFile.delete();
}
/**
* {@inheritDoc}
*/
public boolean exists(VirtualFile mountPoint, VirtualFile target) {
if (mountPoint.equals(target)) {
return true;
}
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
if (assemblyFile != null) {
return assemblyFile.exists();
}
return assembly.contains(mountPoint, target);
}
/**
* {@inheritDoc}
*/
public boolean isFile(final VirtualFile mountPoint, final VirtualFile target) {
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile != null && assemblyFile.isFile();
}
/**
* {@inheritDoc}
*/
public List getDirectoryEntries(VirtualFile mountPoint, VirtualFile target) {
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
if (assemblyFile == null) {
return new ArrayList(assembly.getChildNames(mountPoint, target));
}
final List directoryEntries = new LinkedList();
for (VirtualFile child : assemblyFile.getChildren()) {
directoryEntries.add(child.getName());
}
return directoryEntries;
}
/**
* {@inheritDoc}
*/
public long getLastModified(VirtualFile mountPoint, VirtualFile target) {
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile == null ? 0L : assemblyFile.getLastModified();
}
/**
* {@inheritDoc}
*/
public long getSize(VirtualFile mountPoint, VirtualFile target) {
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
return assemblyFile == null ? 0L : assemblyFile.getSize();
}
/**
* {@inheritDoc}
*/
public boolean isDirectory(VirtualFile mountPoint, VirtualFile target) {
if (mountPoint.equals(target)) { return true; }
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
if (assemblyFile != null) { return assemblyFile.isDirectory(); }
return assembly.contains(mountPoint, target);
}
/**
* {@inheritDoc}
*/
public boolean isReadOnly() {
return false;
}
/**
* {@inheritDoc}
*/
public InputStream openInputStream(VirtualFile mountPoint, VirtualFile target) throws IOException {
return getExistingFile(mountPoint, target).openStream();
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
VFSLogger.ROOT_LOGGER.tracef("Closing assembly filesystem %s", this);
assembly.close();
}
/**
* {@inheritDoc}
*/
public CodeSigner[] getCodeSigners(VirtualFile mountPoint, VirtualFile target) {
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
if (assemblyFile == null) {
return null;
}
return assemblyFile.getCodeSigners();
}
/**
* {@inheritDoc}
*/
public File getMountSource() {
return null;
}
/**
* {@inheritDoc}
*/
public URI getRootURI() throws URISyntaxException {
return null;
}
private VirtualFile getExistingFile(final VirtualFile mountPoint, final VirtualFile target) throws FileNotFoundException {
final VirtualFile assemblyFile = assembly.getFile(mountPoint, target);
if (assemblyFile == null) {
throw new FileNotFoundException(target.getPathName());
}
return assemblyFile;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/EnumerationIterable.java 0000664 0000000 0000000 00000002302 13562475444 0027316 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import java.util.Enumeration;
import java.util.Iterator;
/**
* An iterable enumeration wrapper.
*
* @param the element type
* @author David M. Lloyd
*/
class EnumerationIterable implements Iterable {
private final Enumeration entries;
EnumerationIterable(Enumeration entries) {
this.entries = entries;
}
public Iterator iterator() {
return new EnumerationIterator(entries);
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/EnumerationIterator.java 0000664 0000000 0000000 00000002503 13562475444 0027363 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import java.util.Enumeration;
import java.util.Iterator;
/**
* An enumeration iterator.
*
* @param the element type
* @author David M. Lloyd
*/
class EnumerationIterator implements Iterator {
private final Enumeration entries;
EnumerationIterator(Enumeration entries) {
this.entries = entries;
}
public boolean hasNext() {
return entries.hasMoreElements();
}
public T next() {
return entries.nextElement();
}
public void remove() {
throw new UnsupportedOperationException();
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/FileSystem.java 0000664 0000000 0000000 00000016446 13562475444 0025462 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.CodeSigner;
import java.util.List;
import org.jboss.vfs.VirtualFile;
/**
* A file system which is mounted in to the VFS. This is the driver class for a given virtual file system type. An
* instance of {@code FileSystem} will be mounted at some point on a VFS. The specific instance is only called when a
* file from this filesystem is called upon. The path components passed in to the operations are canonical, with no "."
* or ".." components.
*
* @author David M. Lloyd
*/
public interface FileSystem extends Closeable {
/**
* Get a real {@code File} for the given path within this filesystem. Some filesystem types will need to make a copy
* in order to return this file; such copies should be cached and retained until the filesystem is closed. Depending
* on the file type, the real path of the returned {@code File} may or may not bear a relationship to the virtual
* path provided; if such a relationship is required, it must be negotiated at the time the filesystem is mounted.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return the file instance
* @throws IOException if an I/O error occurs
*/
File getFile(VirtualFile mountPoint, VirtualFile target) throws IOException;
/**
* Open an input stream for the file at the given relative path.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return the input stream
* @throws IOException if an I/O error occurs
*/
InputStream openInputStream(VirtualFile mountPoint, VirtualFile target) throws IOException;
/**
* Determine whether this filesystem is read-only. A read-only filesystem prohibits file modification or deletion.
* It is not an error to mount a read-write filesystem within a read-only filesystem however (this operation does not
* take place within the {@code FileSystem} implementation).
*
* @return {@code true} if the filesystem is read-only
*/
boolean isReadOnly();
/**
* Attempt to delete a virtual file within this filesystem.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return {@code true} if the file was deleted, {@code false} if it failed for any reason
*/
boolean delete(VirtualFile mountPoint, VirtualFile target);
/**
* Get the size of a virtual file within this filesystem.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return the size, in bytes, or 0L if the file does not exist or is a directory
*/
long getSize(VirtualFile mountPoint, VirtualFile target);
/**
* Get the last modification time of a virtual file within this filesystem.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return the modification time in milliseconds, or 0L if the file does not exist or if an error occurs
*/
long getLastModified(VirtualFile mountPoint, VirtualFile target);
/**
* Ascertain the existance of a virtual file within this filesystem.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return {@code true} if the file exists, {@code false} otherwise
* @throws IOException if an I/O error occurs
*/
boolean exists(VirtualFile mountPoint, VirtualFile target);
/**
* Ascertain whether a virtual file within this filesystem is a plain file.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return {@code true} if the file exists and is a plain file, {@code false} otherwise
*/
boolean isFile(VirtualFile mountPoint, VirtualFile target);
/**
* Ascertain whether a virtual file within this filesystem is a directory.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return {@code true} if the file exists and is a directory, {@code false} otherwise
*/
boolean isDirectory(VirtualFile mountPoint, VirtualFile target);
/**
* Read a directory. Returns all the simple path names (excluding "." and ".."). The returned list will be empty if
* the node is not a directory.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return the collection of children names
*/
List getDirectoryEntries(VirtualFile mountPoint, VirtualFile target);
/**
* Get the {@link CodeSigner}s for a the virtual file.
*
* @param mountPoint the mount point of the filesystem instance (guaranteed to be a parent of {@code target})
* @param target the virtual file to act upon
* @return {@link CodeSigner} for the virtual file or null if not signed.
*/
CodeSigner[] getCodeSigners(VirtualFile mountPoint, VirtualFile target);
/**
* Destroy this filesystem instance. After this method is called, the filesystem may not be used in any way. This
* method should be called only after all mounts of this filesystem have been cleared; otherwise, VFS accesses may
* result in {@code IOException}s.
*
* @throws IOException if an I/O error occurs during close
*/
void close() throws IOException;
/**
* Get the {@link java.io.File} source provided at mount time.
*
* @return the source used for mounting
*/
File getMountSource();
/**
* Get the root URI for this file system, or {@code null} if there is no valid root URI.
*
* @return the root URI
* @throws URISyntaxException if the URI isn't valid
*/
URI getRootURI() throws URISyntaxException;
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/JavaZipFileSystem.java 0000664 0000000 0000000 00000030271 13562475444 0026737 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import java.io.BufferedOutputStream;
import java.io.Closeable;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.CodeSigner;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import org.jboss.vfs.TempDir;
import org.jboss.vfs.VFSLogger;
import org.jboss.vfs.VFSMessages;
import org.jboss.vfs.VFSUtils;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.util.PathTokenizer;
/**
* {@inheritDoc}
*
* This implementation is backed by a zip file. The provided file must be owned by this instance; otherwise, if the
* file disappears unexpectedly, the filesystem will malfunction.
*
* @author David M. Lloyd
* @author Ales Justin
*/
public final class JavaZipFileSystem implements FileSystem {
private final JarFile zipFile;
private final File archiveFile;
private final long zipTime;
private final ZipNode rootNode;
private final TempDir tempDir;
private final File contentsDir;
/**
* Create a new instance.
*
* @param name the name of the source archive
* @param inputStream an input stream from the source archive
* @param tempDir the temp dir into which zip information is stored
* @throws java.io.IOException if an I/O error occurs
*/
public JavaZipFileSystem(String name, InputStream inputStream, TempDir tempDir) throws IOException {
this(tempDir.createFile(name, inputStream), tempDir);
}
/**
* Create a new instance.
*
* @param archiveFile the original archive file
* @param tempDir the temp dir into which zip information is stored
* @throws java.io.IOException if an I/O error occurs
*/
public JavaZipFileSystem(File archiveFile, TempDir tempDir) throws IOException {
zipTime = archiveFile.lastModified();
final JarFile zipFile;
this.zipFile = zipFile = new JarFile(archiveFile);
this.archiveFile = archiveFile;
this.tempDir = tempDir;
final Enumeration extends JarEntry> entries = zipFile.entries();
final ZipNode rootNode = new ZipNode(new HashMap(), "", null);
FILES:
for (JarEntry entry : iter(entries)) {
final String name = entry.getName();
final boolean isDirectory = entry.isDirectory();
final List tokens = PathTokenizer.getTokens(name);
ZipNode node = rootNode;
final Iterator it = tokens.iterator();
while (it.hasNext()) {
String token = it.next();
if (PathTokenizer.isCurrentToken(token) || PathTokenizer.isReverseToken(token)) {
// invalid file name
continue FILES;
}
final Map children = node.children;
if (children == null) {
// todo - log bad zip entry
continue FILES;
}
ZipNode child = children.get(token);
if (child == null) {
child = it.hasNext() || isDirectory ? new ZipNode(new HashMap(), token, null) : new ZipNode(null, token, entry);
children.put(token, child);
}
node = child;
}
}
this.rootNode = rootNode;
contentsDir = tempDir.getFile("contents");
contentsDir.mkdir();
VFSLogger.ROOT_LOGGER.tracef("Created zip filesystem for file %s in temp dir %s", archiveFile, tempDir);
}
/**
* {@inheritDoc}
*/
private static Iterable iter(final Enumeration entries) {
return new EnumerationIterable(entries);
}
/**
* {@inheritDoc}
*/
public File getFile(VirtualFile mountPoint, VirtualFile target) throws IOException {
final ZipNode zipNode = getExistingZipNode(mountPoint, target);
// check if we have cached one already
File cachedFile = zipNode.cachedFile;
if (cachedFile != null) {
return cachedFile;
}
synchronized (zipNode) {
// double-check
cachedFile = zipNode.cachedFile;
if (cachedFile != null) {
return cachedFile;
}
// nope, create a cached temp
final JarEntry zipEntry = zipNode.entry;
String name = target.getPathNameRelativeTo(mountPoint);
cachedFile = buildFile(contentsDir, name);
if (zipEntry == null) {
cachedFile.mkdir();
} else {
VFSUtils.copyStreamAndClose(zipFile.getInputStream(zipEntry), new BufferedOutputStream(new FileOutputStream(cachedFile)));
}
zipNode.cachedFile = cachedFile;
return cachedFile;
}
}
/**
* {@inheritDoc}
*/
public InputStream openInputStream(VirtualFile mountPoint, VirtualFile target) throws IOException {
final ZipNode zipNode = getExistingZipNode(mountPoint, target);
final File cachedFile = zipNode.cachedFile;
if (cachedFile != null) {
return new FileInputStream(cachedFile);
}
if (rootNode == zipNode) {
return new FileInputStream(archiveFile);
}
final JarEntry entry = zipNode.entry;
if (entry == null) {
throw VFSMessages.MESSAGES.notAFile(target.getPathName());
}
return zipFile.getInputStream(entry);
}
/**
* {@inheritDoc}
*/
public boolean delete(VirtualFile mountPoint, VirtualFile target) {
final ZipNode zipNode = getZipNode(mountPoint, target);
if (zipNode == null) {
return false;
}
final File cachedFile = zipNode.cachedFile;
return cachedFile != null && cachedFile.delete();
}
/**
* {@inheritDoc}
*/
public long getSize(VirtualFile mountPoint, VirtualFile target) {
final ZipNode zipNode = getZipNode(mountPoint, target);
if (zipNode == null) {
return 0L;
}
final File cachedFile = zipNode.cachedFile;
final JarEntry entry = zipNode.entry;
if (zipNode == rootNode) {
return archiveFile.length();
}
return cachedFile != null ? cachedFile.length() : entry == null ? 0L : entry.getSize();
}
/**
* {@inheritDoc}
*/
public long getLastModified(VirtualFile mountPoint, VirtualFile target) {
final ZipNode zipNode = getZipNode(mountPoint, target);
if (zipNode == null) {
return 0L;
}
final File cachedFile = zipNode.cachedFile;
final JarEntry entry = zipNode.entry;
return cachedFile != null ? cachedFile.lastModified() : entry == null ? zipTime : entry.getTime();
}
/**
* {@inheritDoc}
*/
public boolean exists(VirtualFile mountPoint, VirtualFile target) {
final ZipNode zipNode = rootNode.find(mountPoint, target);
if (zipNode == null) {
return false;
} else {
final File cachedFile = zipNode.cachedFile;
return cachedFile == null || cachedFile.exists();
}
}
/**
* {@inheritDoc}
*/
public boolean isFile(final VirtualFile mountPoint, final VirtualFile target) {
final ZipNode zipNode = rootNode.find(mountPoint, target);
return zipNode != null && zipNode.entry != null;
}
/**
* {@inheritDoc}
*/
public boolean isDirectory(VirtualFile mountPoint, VirtualFile target) {
final ZipNode zipNode = rootNode.find(mountPoint, target);
return zipNode != null && zipNode.entry == null;
}
/**
* {@inheritDoc}
*/
public List getDirectoryEntries(VirtualFile mountPoint, VirtualFile target) {
final ZipNode zipNode = getZipNode(mountPoint, target);
if (zipNode == null) {
return Collections.emptyList();
}
final Map children = zipNode.children;
if (children == null) {
return Collections.emptyList();
}
final Collection values = children.values();
final List names = new ArrayList(values.size());
for (ZipNode node : values) {
names.add(node.name);
}
return names;
}
/**
* {@inheritDoc}
*/
public CodeSigner[] getCodeSigners(VirtualFile mountPoint, VirtualFile target) {
final ZipNode zipNode = getZipNode(mountPoint, target);
if (zipNode == null) {
return null;
}
JarEntry jarEntry = zipNode.entry;
return jarEntry.getCodeSigners();
}
private ZipNode getZipNode(VirtualFile mountPoint, VirtualFile target) {
return rootNode.find(mountPoint, target);
}
private ZipNode getExistingZipNode(VirtualFile mountPoint, VirtualFile target)
throws FileNotFoundException {
final ZipNode zipNode = rootNode.find(mountPoint, target);
if (zipNode == null) {
throw new FileNotFoundException(target.getPathName());
}
return zipNode;
}
/**
* {@inheritDoc}
*/
public boolean isReadOnly() {
return true;
}
/**
* {@inheritDoc}
*/
public File getMountSource() {
return archiveFile;
}
public URI getRootURI() throws URISyntaxException {
return new URI("jar", archiveFile.toURI().toString() + "!/", null);
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
VFSLogger.ROOT_LOGGER.tracef("Closing zip filesystem %s", this);
VFSUtils.safeClose(new Closeable() {
public void close() throws IOException {
zipFile.close();
}
});
tempDir.close();
}
private File buildFile(File contentsDir, String name) {
List tokens = PathTokenizer.getTokens(name);
File currentFile = contentsDir;
for (String token : tokens) {
currentFile = new File(currentFile, token);
}
currentFile.getParentFile().mkdirs();
return currentFile;
}
private static final class ZipNode {
// immutable child map
private final Map children;
private final String name;
private final JarEntry entry;
private volatile File cachedFile;
private ZipNode(Map children, String name, JarEntry entry) {
this.children = children;
this.name = name;
this.entry = entry;
}
private ZipNode find(VirtualFile mountPoint, VirtualFile target) {
if (mountPoint.equals(target)) {
return this;
} else {
final ZipNode parent = find(mountPoint, target.getParent());
if (parent == null) {
return null;
}
final Map children = parent.children;
if (children == null) {
return null;
}
return children.get(target.getName());
}
}
}
} jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/MountHandle.java 0000664 0000000 0000000 00000002236 13562475444 0025604 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import java.io.Closeable;
import java.io.File;
/**
* This class represents a handle to a mounted FileSystem. This can
* be used to close/cleanup the FileSystem as well as to access the
* mount source.
*
* @author John Bailey
*/
public interface MountHandle extends Closeable {
/**
* Get the source file used for the mount.
*
* @return the source file
*/
File getMountSource();
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/RealFileSystem.java 0000664 0000000 0000000 00000017567 13562475444 0026273 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import static java.security.AccessController.doPrivileged;
import java.io.File;
import java.io.FileInputStream;
import java.io.FilePermission;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.UndeclaredThrowableException;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.CodeSigner;
import java.security.PrivilegedAction;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.jboss.vfs.VFSLogger;
import org.jboss.vfs.VFSUtils;
import org.jboss.vfs.VirtualFile;
/**
* A real filesystem.
*
* @author David M. Lloyd
*/
public final class RealFileSystem implements FileSystem {
private static final boolean NEEDS_CONVERSION = File.separatorChar != '/';
private final File realRoot;
private final boolean privileged;
/**
* Construct a real filesystem with the given real root.
*
* @param realRoot the real root
*/
public RealFileSystem(File realRoot) {
this(realRoot, true);
}
/**
* Construct a real filesystem with the given real root.
*
* @param realRoot the real root
* @param privileged {@code true} to check permissions once up front, {@code false} to check at access time
*/
public RealFileSystem(File realRoot, boolean privileged) {
if (privileged) {
final SecurityManager sm = System.getSecurityManager();
if (sm != null) {
sm.checkPermission(new FilePermission(new File(realRoot, "-").getPath(), "read,delete"));
}
}
// the transformation is for case insensitive file systems. This helps to ensure that the rest of the path matches exactly the canonical form
File canonicalRoot = realRoot;
try {
canonicalRoot = realRoot.getCanonicalFile();
} catch(IOException e) {
VFSLogger.ROOT_LOGGER.warnf(e, "Cannot get the canonical form of the real root. This could lead to potential problems if the %s flag is set.", VFSUtils.FORCE_CASE_SENSITIVE_KEY);
}
this.realRoot = canonicalRoot;
this.privileged = privileged;
VFSLogger.ROOT_LOGGER.tracef("Constructed real %s filesystem at root %s", privileged ? "privileged" : "unprivileged", realRoot);
}
private static T doIoPrivileged(PrivilegedExceptionAction action) throws IOException {
try {
return doPrivileged(action);
} catch (PrivilegedActionException pe) {
try {
throw pe.getException();
} catch (IOException e) {
throw e;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new UndeclaredThrowableException(e);
}
}
}
/**
* {@inheritDoc}
*/
public InputStream openInputStream(final VirtualFile mountPoint, final VirtualFile target) throws IOException {
return privileged ? doIoPrivileged(new PrivilegedExceptionAction() {
public InputStream run() throws Exception {
return new FileInputStream(getFile(mountPoint, target));
}
}) : new FileInputStream(getFile(mountPoint, target));
}
/**
* {@inheritDoc}
*/
public boolean isReadOnly() {
return false;
}
/**
* {@inheritDoc}
*/
public File getFile(VirtualFile mountPoint, VirtualFile target) {
if (mountPoint.equals(target)) {
return realRoot;
} else if (NEEDS_CONVERSION) {
return new File(realRoot, target.getPathNameRelativeTo(mountPoint).replace('/', File.separatorChar));
} else {
return new File(realRoot, target.getPathNameRelativeTo(mountPoint));
}
}
/**
* {@inheritDoc}
*/
public boolean delete(VirtualFile mountPoint, VirtualFile target) {
final File file = getFile(mountPoint, target);
return privileged ? doPrivileged(new PrivilegedAction() {
public Boolean run() {
return Boolean.valueOf(file.delete());
}
}).booleanValue() : file.delete();
}
/**
* {@inheritDoc}
*/
public long getSize(VirtualFile mountPoint, VirtualFile target) {
final File file = getFile(mountPoint, target);
return privileged ? doPrivileged(new PrivilegedAction() {
public Long run() {
return Long.valueOf(file.length());
}
}).longValue() : file.length();
}
/**
* {@inheritDoc}
*/
public long getLastModified(VirtualFile mountPoint, VirtualFile target) {
final File file = getFile(mountPoint, target);
return privileged ? doPrivileged(new PrivilegedAction() {
public Long run() {
return Long.valueOf(file.lastModified());
}
}).longValue() : file.lastModified();
}
/**
* {@inheritDoc}
*/
public boolean exists(VirtualFile mountPoint, VirtualFile target) {
final File file = getFile(mountPoint, target);
return privileged ? doPrivileged(new PrivilegedAction() {
public Boolean run() {
return Boolean.valueOf(VFSUtils.exists(file));
}
}).booleanValue() : VFSUtils.exists(file);
}
/**
* {@inheritDoc}
*/
public boolean isFile(final VirtualFile mountPoint, final VirtualFile target) {
final File file = getFile(mountPoint, target);
return privileged ? doPrivileged(new PrivilegedAction() {
public Boolean run() {
return Boolean.valueOf(file.isFile());
}
}).booleanValue() : file.isFile();
}
/**
* {@inheritDoc}
*/
public boolean isDirectory(VirtualFile mountPoint, VirtualFile target) {
final File file = getFile(mountPoint, target);
return privileged ? doPrivileged(new PrivilegedAction() {
public Boolean run() {
return Boolean.valueOf(file.isDirectory());
}
}).booleanValue() : file.isDirectory();
}
/**
* {@inheritDoc}
*/
public List getDirectoryEntries(VirtualFile mountPoint, VirtualFile target) {
final File file = getFile(mountPoint, target);
final String[] names = privileged ? doPrivileged(new PrivilegedAction() {
public String[] run() {
return file.list();
}
}) : file.list();
return names == null ? Collections.emptyList() : Arrays.asList(names);
}
/**
* {@inheritDoc}
*/
public CodeSigner[] getCodeSigners(VirtualFile mountPoint, VirtualFile target) {
return null;
}
/**
* {@inheritDoc}
*/
public File getMountSource() {
return realRoot;
}
public URI getRootURI() throws URISyntaxException {
return realRoot.toURI();
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
// no operation - the real FS can't be closed
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/spi/RootFileSystem.java 0000775 0000000 0000000 00000007205 13562475444 0026322 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.spi;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URISyntaxException;
import java.security.CodeSigner;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import org.jboss.vfs.VirtualFile;
/**
* A special FileSystem which supports multiple roots.
*
* This is currently accomplished by requiring that VirtualFile.getPathName()
* produce output that is consumable by java.io.File as a path.
*/
public final class RootFileSystem implements FileSystem {
public static final RootFileSystem ROOT_INSTANCE = new RootFileSystem();
private RootFileSystem() {
}
/**
* {@inheritDoc}
*/
public InputStream openInputStream(VirtualFile mountPoint, VirtualFile target) throws IOException {
return new FileInputStream(getFile(mountPoint, target));
}
/**
* {@inheritDoc}
*/
public boolean isReadOnly() {
return false;
}
/**
* {@inheritDoc}
*/
public File getFile(VirtualFile mountPoint, VirtualFile target) {
return new File(target.getPathName());
}
/**
* {@inheritDoc}
*/
public boolean delete(VirtualFile mountPoint, VirtualFile target) {
return getFile(mountPoint, target).delete();
}
/**
* {@inheritDoc}
*/
public long getSize(VirtualFile mountPoint, VirtualFile target) {
return getFile(mountPoint, target).length();
}
/**
* {@inheritDoc}
*/
public long getLastModified(VirtualFile mountPoint, VirtualFile target) {
return getFile(mountPoint, target).lastModified();
}
/**
* {@inheritDoc}
*/
public boolean exists(VirtualFile mountPoint, VirtualFile target) {
return getFile(mountPoint, target).exists();
}
/**
* {@inheritDoc}
*/
public boolean isFile(final VirtualFile mountPoint, final VirtualFile target) {
return getFile(mountPoint, target).isFile();
}
/**
* {@inheritDoc}
*/
public boolean isDirectory(VirtualFile mountPoint, VirtualFile target) {
return getFile(mountPoint, target).isDirectory();
}
/**
* {@inheritDoc}
*/
public List getDirectoryEntries(VirtualFile mountPoint, VirtualFile target) {
final String[] names = getFile(mountPoint, target).list();
return names == null ? Collections.emptyList() : Arrays.asList(names);
}
/**
* {@inheritDoc}
*/
public CodeSigner[] getCodeSigners(VirtualFile mountPoint, VirtualFile target) {
return null;
}
/**
* {@inheritDoc}
*/
public File getMountSource() {
return null;
}
public URI getRootURI() throws URISyntaxException {
return null;
}
/**
* {@inheritDoc}
*/
public void close() throws IOException {
// no operation - the root FS can't be closed
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/ 0000775 0000000 0000000 00000000000 13562475444 0022702 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/AbstractPatternVirtualFileFilter.java 0000664 0000000 0000000 00000003663 13562475444 0032173 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs.util;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.util.regex.Pattern;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileFilter;
/**
* Regexp patter filter.
*
* @author Ales Justin
*/
public abstract class AbstractPatternVirtualFileFilter implements VirtualFileFilter {
private Pattern pattern;
public AbstractPatternVirtualFileFilter(String regexp) {
if (regexp == null) {
throw MESSAGES.nullArgument("regexp");
}
pattern = Pattern.compile(regexp);
}
/**
* Extract match string from file.
*
* @param file the file
* @return extracted match string
*/
protected abstract String getMatchString(VirtualFile file);
/**
* Should we match the pattern.
*
* @return the match flag
*/
protected abstract boolean doMatch();
public boolean accepts(VirtualFile file) {
String string = getMatchString(file);
return pattern.matcher(string).matches() == doMatch();
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/AbstractVirtualFileFilterWithAttributes.java0000664 0000000 0000000 00000003402 13562475444 0033527 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import org.jboss.vfs.VirtualFileFilterWithAttributes;
import org.jboss.vfs.VisitorAttributes;
/**
* AbstractVirtualFileFilterWithAttributes
*
* @author adrian@jboss.org
* @version $Revision: 44223 $
*/
public abstract class AbstractVirtualFileFilterWithAttributes implements VirtualFileFilterWithAttributes {
/**
* The attributes
*/
private VisitorAttributes attributes;
/**
* Create a new AbstractVirtualFileFilterWithAttributes, using {@link VisitorAttributes#DEFAULT}
*/
protected AbstractVirtualFileFilterWithAttributes() {
this(null);
}
/**
* Create a new AbstractVirtualFileFilterWithAttributes.
*
* @param attributes the attributes, pass null to use {@link VisitorAttributes#DEFAULT}
*/
protected AbstractVirtualFileFilterWithAttributes(VisitorAttributes attributes) {
if (attributes == null) { attributes = VisitorAttributes.DEFAULT; }
this.attributes = attributes;
}
public VisitorAttributes getAttributes() {
return attributes;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/AbstractVirtualFileVisitor.java 0000664 0000000 0000000 00000003272 13562475444 0031043 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import org.jboss.vfs.VirtualFileVisitor;
import org.jboss.vfs.VisitorAttributes;
/**
* AbstractVirtualFileVisitor.
*
* @author Adrian Brock
* @version $Revision: 1.1 $
*/
public abstract class AbstractVirtualFileVisitor implements VirtualFileVisitor {
/**
* The attributes
*/
private final VisitorAttributes attributes;
/**
* Create a new AbstractVirtualFileVisitor using the default visitor attributes
*/
protected AbstractVirtualFileVisitor() {
this(null);
}
/**
* Create a new AbstractVirtualFileVisitor using the default visitor attributes
*
* @param attributes the attributes, uses the default if null
*/
protected AbstractVirtualFileVisitor(VisitorAttributes attributes) {
if (attributes == null) { attributes = VisitorAttributes.DEFAULT; }
this.attributes = attributes;
}
public VisitorAttributes getAttributes() {
return attributes;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/ExtensibleFilter.java 0000664 0000000 0000000 00000017226 13562475444 0027025 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileFilter;
/**
* An extensible filter for VFS files. Three arrays are maintained for checking: a prefix, suffix, and match array. If
* the filename starts with any of the prefixes, ends with any of the suffixes, or exactly matches any of the matches,
* then the accepts method will return false.
*
* NOTE: the arrays *must* be sorted for the string matching to work, and suffixes use the 'reverseComparator'
*
* @author somebody@jboss.org
* @author Scott.Stark@jboss.org
* @version $Revision: 57108 $
*/
public class ExtensibleFilter implements VirtualFileFilter {
/**
* Compare the strings backwards. This assists in suffix comparisons.
*/
private static final Comparator reverseComparator = new Comparator() {
public int compare(String o1, String o2) {
int idx1 = o1.length();
int idx2 = o2.length();
int comp = 0;
while (comp == 0 && idx1 > 0 && idx2 > 0) { comp = o1.charAt(--idx1) - o2.charAt(--idx2); }
return (comp == 0) ? (idx1 - idx2) : comp;
}
};
/**
* the default prefix list
*/
private static final String[] DEFAULT_PREFIXES =
{"#", "%", ",", ".", "_$"};
/**
* the default suffix list
*/
private static final String[] DEFAULT_SUFFIXES =
{"#", "$", "%", "~", ",v", ".BAK", ".bak", ".old", ".orig", ".tmp", ".rej", ".sh"};
/**
* the default matches list
*/
private static final String[] DEFAULT_MATCHES =
{".make.state", ".nse_depinfo", "CVS", "CVS.admin", "RCS", "RCSLOG",
"SCCS", "TAGS", "core", "tags"};
/**
* The list of disallowed suffixes, sorted using reverse values
*/
private List suffixes;
/**
* The sorted list of disallowed prefixes
*/
private List prefixes;
/**
* The sorted list of disallowed values
*/
private List matches;
/**
* Use the default values for suffixes, prefixes, and matches
*/
public ExtensibleFilter() {
this(DEFAULT_MATCHES, DEFAULT_PREFIXES, DEFAULT_SUFFIXES);
}
/**
* Create using a custom set of matches, prefixes, and suffixes. If any of these arrays are null, then the
* corresponding default will be substituted.
*
* @param matches the matches
* @param prefixes the prefixes
* @param suffixes the suffixes
*/
public ExtensibleFilter(String[] matches, String[] prefixes, String[] suffixes) {
if (matches == null) { matches = DEFAULT_MATCHES; }
Arrays.sort(matches);
this.matches = new ArrayList(Arrays.asList(matches));
if (prefixes == null) { prefixes = DEFAULT_PREFIXES; }
Arrays.sort(prefixes);
this.prefixes = new ArrayList(Arrays.asList(prefixes));
if (suffixes == null) { suffixes = DEFAULT_SUFFIXES; }
Arrays.sort(suffixes, reverseComparator);
this.suffixes = new ArrayList(Arrays.asList(suffixes));
}
public void addPrefix(String prefix) {
prefixes.add(prefix);
Collections.sort(prefixes);
}
public void addPrefixes(String[] prefixes) {
this.prefixes.addAll(Arrays.asList(prefixes));
Collections.sort(this.prefixes);
}
public void delPrefix(String prefix) {
prefixes.remove(prefix);
}
public void delPrefixes(String[] prefixes) {
this.prefixes.removeAll(Arrays.asList(prefixes));
Collections.sort(this.prefixes);
}
public void addSuffix(String suffix) {
suffixes.add(suffix);
Collections.sort(suffixes, reverseComparator);
}
public void addSuffixes(String[] suffixes) {
this.suffixes.addAll(Arrays.asList(suffixes));
Collections.sort(this.suffixes, reverseComparator);
}
public void delSuffix(String suffix) {
suffixes.remove(suffix);
}
public void delSuffixes(String[] suffixes) {
this.suffixes.removeAll(Arrays.asList(suffixes));
Collections.sort(this.suffixes, reverseComparator);
}
public String[] getSuffixes() {
String[] tmp = new String[suffixes.size()];
suffixes.toArray(tmp);
return tmp;
}
public void setSuffixes(String[] suffixes) {
Arrays.sort(suffixes, reverseComparator);
this.suffixes.clear();
this.suffixes.addAll(Arrays.asList(suffixes));
}
public String[] getPrefixes() {
String[] tmp = new String[prefixes.size()];
prefixes.toArray(tmp);
return tmp;
}
public void setPrefixes(String[] prefixes) {
Arrays.sort(prefixes);
this.prefixes.clear();
this.prefixes.addAll(Arrays.asList(prefixes));
}
public String[] getMatches() {
String[] tmp = new String[matches.size()];
matches.toArray(tmp);
return tmp;
}
public void setMatches(String[] matches) {
Arrays.sort(matches);
this.matches.clear();
this.matches.addAll(Arrays.asList(matches));
}
/**
* If the filename matches any string in the prefix, suffix, or matches array, return false. Perhaps a bit of
* overkill, but this method operates in log(n) time, where n is the size of the arrays.
*
* @param file The file to be tested
* @return false if the filename matches any of the prefixes, suffixes, or matches.
*/
public boolean accepts(VirtualFile file) {
String name = file.getName();
// check exact match
int index = Collections.binarySearch(matches, name);
if (index >= 0) { return false; }
// check prefix
index = Collections.binarySearch(prefixes, name);
if (index >= 0) { return false; }
if (index < -1) {
// The < 0 index gives the first index greater than name
int firstLessIndex = -2 - index;
String prefix = prefixes.get(firstLessIndex);
// If name starts with an ingored prefix ignore name
if (name.startsWith(prefix)) { return false; }
}
// check suffix
index = Collections.binarySearch(suffixes, name, reverseComparator);
if (index >= 0) { return false; }
if (index < -1) {
// The < 0 index gives the first index greater than name
int firstLessIndex = -2 - index;
String suffix = suffixes.get(firstLessIndex);
// If name ends with an ingored suffix ignore name
if (name.endsWith(suffix)) { return false; }
}
// everything checks out.
return true;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/FileNameVirtualFileFilter.java 0000664 0000000 0000000 00000005621 13562475444 0030546 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs.util;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.util.Map;
import java.util.Set;
import org.jboss.vfs.VFSLogger;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileFilter;
/**
* Exclude virtual file by file name and path.
*
* @author ales.justin@jboss.org
*/
public class FileNameVirtualFileFilter implements VirtualFileFilter {
private Map> excludes;
public FileNameVirtualFileFilter(Map> excludes) {
if (excludes == null || excludes.isEmpty()) {
throw MESSAGES.nullOrEmpty("excludes");
}
this.excludes = excludes;
}
/**
* Do we accept file.
*
* If pathName contains any of the keys,
* * if the value is null - then do exclude
* * if value is not null - only exclude if it value contains simple name
*
* @param file the virtual file
* @return false if file is excluded by excludes map, true other wise
*/
public boolean accepts(VirtualFile file) {
String pathName = getPathName(file);
for (Map.Entry> entry : excludes.entrySet()) {
String key = entry.getKey();
if (pathName.contains(key)) {
String simpleName = file.getName();
Set value = entry.getValue();
if (value == null || value.contains(simpleName)) {
VFSLogger.ROOT_LOGGER.tracef("Excluding %s", pathName);
return false;
}
}
}
return true;
}
/**
* Get the path name for the VirtualFile.
*
* @param file the virtual file
* @return the path name
*/
protected String getPathName(VirtualFile file) {
try {
// prefer the URI, as the pathName might
// return an empty string for temp virtual files
return file.toURI().toString();
} catch (Exception e) {
return file.getPathName();
}
}
} jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/FilterVirtualFileVisitor.java 0000664 0000000 0000000 00000006304 13562475444 0030524 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileFilter;
import org.jboss.vfs.VirtualFileFilterWithAttributes;
import org.jboss.vfs.VisitorAttributes;
/**
* A visitor based on a virtual file filter
*
* @author Adrian Brock
* @version $Revision: 1.1 $
*/
public class FilterVirtualFileVisitor extends AbstractVirtualFileVisitor {
/**
* The filter
*/
private final VirtualFileFilter filter;
/**
* What is matched
*/
private List matched;
/**
* Check the attributes
*
* @param filter the filter
* @param attributes the attributes
* @return the attributes
* @throws IllegalArgumentException for a null filter
*/
private static VisitorAttributes checkAttributes(VirtualFileFilter filter, VisitorAttributes attributes) {
if (filter == null) {
throw MESSAGES.nullArgument("filter");
}
// Specified
if (attributes != null) { return attributes; }
// From the filter
if (filter instanceof VirtualFileFilterWithAttributes) { return ((VirtualFileFilterWithAttributes) filter).getAttributes(); }
// It will use the default
return null;
}
/**
* Create a new FilterVirtualFileVisitor with default attributes
*
* @param filter the filter
* @throws IllegalArgumentException if the filter is null
*/
public FilterVirtualFileVisitor(VirtualFileFilter filter) {
this(filter, null);
}
/**
* Create a new FilterVirtualFileVisitor.
*
* @param filter the filter
* @param attributes the attributes, uses the default if null
* @throws IllegalArgumentException if the filter is null
*/
public FilterVirtualFileVisitor(VirtualFileFilter filter, VisitorAttributes attributes) {
super(checkAttributes(filter, attributes));
this.filter = filter;
}
/**
* Get the matched files
*
* @return the matched files
*/
public List getMatched() {
if (matched == null) { return Collections.emptyList(); } else { return matched; }
}
public void visit(VirtualFile virtualFile) {
if (filter.accepts(virtualFile)) {
if (matched == null) { matched = new ArrayList(); }
matched.add(virtualFile);
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/IncludeExcludeVisitorAttributes.java 0000664 0000000 0000000 00000004562 13562475444 0032100 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs.util;
import java.net.URL;
import java.util.Collections;
import java.util.Set;
import org.jboss.vfs.VFSLogger;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileFilter;
import org.jboss.vfs.VisitorAttributes;
/**
* Include/exclude visitor attributes.
*
* @author Ales Justin
*/
public class IncludeExcludeVisitorAttributes extends VisitorAttributes implements VirtualFileFilter {
private Set includes;
private Set excludes;
public IncludeExcludeVisitorAttributes(Set includes, Set excludes) {
if (includes == null) { includes = Collections.emptySet(); }
if (excludes == null) { excludes = Collections.emptySet(); }
this.includes = includes;
this.excludes = excludes;
setIncludeRoot(false);
setLeavesOnly(true);
setRecurseFilter(this);
}
public boolean accepts(VirtualFile file) {
try {
URL url = file.toURL();
String urlString = url.toExternalForm();
for (String include : includes) {
if (urlString.contains(include) == false) { return false; }
}
for (String exclude : excludes) {
if (urlString.contains(exclude)) { return false; }
}
return true;
} catch (Exception e) {
VFSLogger.ROOT_LOGGER.tracef(e,"Exception while filtering file: %s", file);
return false;
}
}
} jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/IncludeFileNameVirtualFileFilter.java 0000664 0000000 0000000 00000002410 13562475444 0032043 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs.util;
import org.jboss.vfs.VirtualFile;
/**
* Include file name filter.
*
* @author Ales Justin
*/
public class IncludeFileNameVirtualFileFilter extends IncludePatternVirtualFileFilter {
public IncludeFileNameVirtualFileFilter(String regexp) {
super(regexp);
}
protected String getMatchString(VirtualFile file) {
return file.getName();
}
} jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/IncludePatternVirtualFileFilter.java 0000664 0000000 0000000 00000002311 13562475444 0032000 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2008, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs.util;
/**
* Include pattern filter.
*
* @author Ales Justin
*/
public abstract class IncludePatternVirtualFileFilter extends AbstractPatternVirtualFileFilter {
public IncludePatternVirtualFileFilter(String regexp) {
super(regexp);
}
protected boolean doMatch() {
return true;
}
} jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/LazyInputStream.java 0000664 0000000 0000000 00000006114 13562475444 0026662 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* Licensed 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.jboss.vfs.util;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.io.IOException;
import java.io.InputStream;
import org.jboss.vfs.VirtualFile;
/**
* Lazy input stream.
*
* Delaying opening stream from underlying virtual file as long as possible.
* Won't be opened if not used at all.
*
* Synchronization is very simplistic, as it's highly unlikely
* there will be a lot of concurrent requests.
*
* @author Ales Justin
*/
public class LazyInputStream extends InputStream {
private VirtualFile file;
private InputStream stream;
public LazyInputStream(VirtualFile file) {
if (file == null) {
throw MESSAGES.nullArgument("file");
}
this.file = file;
}
/**
* Open stream.
*
* @return file's stream
* @throws IOException for any IO error
*/
protected synchronized InputStream openStream() throws IOException {
if (stream == null) { stream = file.openStream(); }
return stream;
}
@Override
public int read() throws IOException {
return openStream().read();
}
@Override
public int read(byte[] b) throws IOException {
return openStream().read(b);
}
@Override
public int read(byte[] b, int off, int len) throws IOException {
return openStream().read(b, off, len);
}
@Override
public long skip(long n) throws IOException {
return openStream().skip(n);
}
@Override
public int available() throws IOException {
return openStream().available();
}
@Override
public synchronized void close() throws IOException {
if (stream == null) { return; }
openStream().close();
stream = null; // reset the stream
}
@Override
public void mark(int readlimit) {
try {
openStream().mark(readlimit);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
@Override
public void reset() throws IOException {
openStream().reset();
}
@Override
public boolean markSupported() {
try {
return openStream().markSupported();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/MatchAllVirtualFileFilter.java 0000664 0000000 0000000 00000002404 13562475444 0030547 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileFilter;
/**
* MatchAllVirtualFileFilter.
*
* @author Adrian Brock
* @version $Revision: 1.1 $
*/
public class MatchAllVirtualFileFilter implements VirtualFileFilter {
/**
* The instance
*/
public static final MatchAllVirtualFileFilter INSTANCE = new MatchAllVirtualFileFilter();
/**
* Singleton
*/
private MatchAllVirtualFileFilter() {
}
public boolean accepts(VirtualFile file) {
return true;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/PaddedManifestStream.java 0000664 0000000 0000000 00000003151 13562475444 0027571 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import java.io.IOException;
import java.io.InputStream;
/**
* Appends a new line char to the stream if it doesn't have one as his last byte.
*
* @author ehsavoie
*/
public class PaddedManifestStream extends InputStream {
private final InputStream realStream;
private int previousChar = -1;
public PaddedManifestStream(InputStream realStream) {
this.realStream = realStream;
}
@Override
public int read() throws IOException {
int value = this.realStream.read();
while(value == '\0') {
value = this.realStream.read();
}
if (value == -1 && previousChar != '\n' && previousChar != -1) {
previousChar = '\n';
return '\n';
}
previousChar = value;
return value;
}
@Override
public void close() throws IOException {
super.close();
realStream.close();
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/PathTokenizer.java 0000664 0000000 0000000 00000022111 13562475444 0026331 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.util.ArrayList;
import java.util.List;
import org.jboss.vfs.VFSMessages;
/**
* PathTokenizer.
*
* @author Adrian Brock
* @author Ales Justin
* @author David M. Lloyd
* @version $Revision: 1.1 $
*/
@SuppressWarnings({"StringEquality"})
public class PathTokenizer {
/**
* The reverse path const
*/
private static final String CURRENT_PATH = ".";
/**
* The reverse path const
*/
private static final String REVERSE_PATH = "..";
/**
* Token states
*/
private static final int STATE_INITIAL = 0;
private static final int STATE_NORMAL = 1;
private static final int STATE_MAYBE_CURRENT_PATH = 2;
private static final int STATE_MAYBE_REVERSE_PATH = 3;
/**
* Utility class
*/
private PathTokenizer() {
}
/**
* Get the remaining path from some tokens
*
* @param tokens the tokens
* @param i the current location
* @param end the end index
* @return the remaining path
* @throws IllegalArgumentException for null tokens or i is out of range
*/
protected static String getRemainingPath(List tokens, int i, int end) {
if (tokens == null) {
throw MESSAGES.nullArgument("tokens");
}
if (i < 0 || i >= end) { throw new IllegalArgumentException("i is not in the range of tokens: 0-" + (end - 1)); }
if (i == end - 1) { return tokens.get(end - 1); }
StringBuilder buffer = new StringBuilder();
for (; i < end - 1; ++i) {
buffer.append(tokens.get(i));
buffer.append("/");
}
buffer.append(tokens.get(end - 1));
return buffer.toString();
}
/**
* Get the tokens that comprise this path.
*
* @param path the path
* @return the tokens or null if the path is empty
* @throws IllegalArgumentException if the path is null
*/
public static List getTokens(String path) {
if (path == null) {
throw MESSAGES.nullArgument("path");
}
List list = new ArrayList();
getTokens(list, path);
return list;
}
/**
* Get the tokens that comprise this path and append them to the list.
*
* @param path the path
* @return the tokens or null if the path is empty
* @throws IllegalArgumentException if the path is null
*/
public static void getTokens(List list, String path) {
int start = -1, length = path.length(), state = STATE_INITIAL;
char ch;
for (int index = 0; index < length; index++) {
ch = path.charAt(index);
switch (ch) {
case '/': {
switch (state) {
case STATE_INITIAL: {
// skip extra leading /
continue;
}
case STATE_MAYBE_CURRENT_PATH: {
// it's '.'
list.add(CURRENT_PATH);
state = STATE_INITIAL;
continue;
}
case STATE_MAYBE_REVERSE_PATH: {
// it's '..'
list.add(REVERSE_PATH);
state = STATE_INITIAL;
continue;
}
case STATE_NORMAL: {
// it's just a normal path segment
list.add(path.substring(start, index));
state = STATE_INITIAL;
continue;
}
}
continue;
}
case '.': {
switch (state) {
case STATE_INITIAL: {
// . is the first char; might be a special token
state = STATE_MAYBE_CURRENT_PATH;
start = index;
continue;
}
case STATE_MAYBE_CURRENT_PATH: {
// the second . in a row...
state = STATE_MAYBE_REVERSE_PATH;
continue;
}
case STATE_MAYBE_REVERSE_PATH: {
// the third . in a row, guess it's just a weird path name
state = STATE_NORMAL;
continue;
}
}
continue;
}
default: {
switch (state) {
case STATE_INITIAL: {
state = STATE_NORMAL;
start = index;
continue;
}
case STATE_MAYBE_CURRENT_PATH:
case STATE_MAYBE_REVERSE_PATH: {
state = STATE_NORMAL;
}
}
}
}
}
// handle the last token
switch (state) {
case STATE_INITIAL: {
// trailing /
break;
}
case STATE_MAYBE_CURRENT_PATH: {
list.add(CURRENT_PATH);
break;
}
case STATE_MAYBE_REVERSE_PATH: {
list.add(REVERSE_PATH);
break;
}
case STATE_NORMAL: {
list.add(path.substring(start));
break;
}
}
return;
}
/**
* Get the remaining path from some tokens
*
* @param tokens the tokens
* @param i the current location
* @return the remaining path
* @throws IllegalArgumentException for null tokens or i is out of range
*/
public static String getRemainingPath(List tokens, int i) {
if (tokens == null) {
throw MESSAGES.nullArgument("tokens");
}
return getRemainingPath(tokens, i, tokens.size());
}
/**
* Apply any . or .. paths in the path param.
*
* @param path the path
* @return simple path, containing no . or .. paths
*/
public static String applySpecialPaths(String path) throws IllegalArgumentException {
List tokens = getTokens(path);
if (tokens == null) { return null; }
int i = 0;
for (int j = 0; j < tokens.size(); j++) {
String token = tokens.get(j);
if (isCurrentToken(token)) { continue; } else if (isReverseToken(token)) { i--; } else { tokens.set(i++, token); }
if (i < 0) {
throw VFSMessages.MESSAGES.onRootPath();
}
}
return getRemainingPath(tokens, 0, i);
}
/**
* Apply any . or .. paths in the pathTokens parameter, returning the minimal token list.
*
* @param pathTokens the path tokens
* @return the simple path tokens
* @throws IllegalArgumentException if reverse path goes over the top path
*/
public static List applySpecialPaths(List pathTokens) throws IllegalArgumentException {
final ArrayList newTokens = new ArrayList();
for (String pathToken : pathTokens) {
if (isCurrentToken(pathToken)) { continue; } else if (isReverseToken(pathToken)) {
final int size = newTokens.size();
if (size == 0) {
throw VFSMessages.MESSAGES.onRootPath();
}
newTokens.remove(size - 1);
} else { newTokens.add(pathToken); }
}
return newTokens;
}
/**
* Is current token.
*
* @param token the token to check
* @return true if token matches current path token
*/
public static boolean isCurrentToken(String token) {
return CURRENT_PATH == token;
}
/**
* Is reverse token.
*
* @param token the token to check
* @return true if token matches reverse path token
*/
public static boolean isReverseToken(String token) {
return REVERSE_PATH == token;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/SuffixMatchFilter.java 0000664 0000000 0000000 00000006715 13562475444 0027145 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2006, Red Hat Middleware LLC, and individual contributors
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.util.Collection;
import java.util.Collections;
import java.util.LinkedHashSet;
import org.jboss.vfs.VFSLogger;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VisitorAttributes;
/**
* Matches a file name against a list of suffixes.
*
* @author Scott.Stark@jboss.org
* @author adrian@jboss.org
* @version $Revision: 44223 $
*/
public class SuffixMatchFilter extends AbstractVirtualFileFilterWithAttributes {
/**
* The suffixes
*/
private Collection suffixes;
private boolean trace;
/**
* Create a new SuffixMatchFilter, using {@link VisitorAttributes#DEFAULT}
*
* @param suffix the suffix
* @throws IllegalArgumentException for a null suffix
*/
public SuffixMatchFilter(String suffix) {
this(suffix, null);
}
/**
* Create a new SuffixMatchFilter.
*
* @param suffix the suffix
* @param attributes the attributes, pass null to use {@link VisitorAttributes#DEFAULT}
* @throws IllegalArgumentException for a null suffix
*/
@SuppressWarnings("unchecked")
public SuffixMatchFilter(String suffix, VisitorAttributes attributes) {
this(Collections.singleton(suffix), attributes);
}
/**
* Create a new SuffixMatchFilter.
*
* @param suffixes - the list of file suffixes to accept.
* @throws IllegalArgumentException for a null suffixes
*/
public SuffixMatchFilter(Collection suffixes) {
this(suffixes, null);
}
/**
* Create a new SuffixMatchFilter.
*
* @param suffixes - the list of file suffixes to accept.
* @param attributes the attributes, pass null to use {@link VisitorAttributes#DEFAULT}
* @throws IllegalArgumentException for a null suffixes
*/
public SuffixMatchFilter(Collection suffixes, VisitorAttributes attributes) {
super(attributes == null ? VisitorAttributes.DEFAULT : attributes);
if (suffixes == null) {
throw MESSAGES.nullArgument("suffixes");
}
this.suffixes = new LinkedHashSet();
this.suffixes.addAll(suffixes);
}
/**
* Accept any file that ends with one of the filter suffixes. This checks that the file.getName() endsWith a suffix.
*
* @return true if the file matches a suffix, false otherwise.
*/
public boolean accepts(VirtualFile file) {
String name = file.getName();
boolean accepts = false;
for (String suffix : suffixes) {
if (name.endsWith(suffix)) {
accepts = true;
break;
}
}
VFSLogger.ROOT_LOGGER.tracef("%s accepted: %s", file, accepts);
return accepts;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/SuffixesExcludeFilter.java 0000664 0000000 0000000 00000003545 13562475444 0030030 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2005, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.util.Collection;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.VirtualFileFilter;
/**
* Filters out a set of suffixes
*
* @author adrian@jboss.org
* @version $Revision: 44223 $
*/
public class SuffixesExcludeFilter implements VirtualFileFilter {
/**
* The suffixes
*/
private Collection suffixes;
/**
* Create a new SuffixMatchFilter,
*
* @param suffixes the suffixes
* @throws IllegalArgumentException for null suffixes
*/
public SuffixesExcludeFilter(Collection suffixes) {
if (suffixes == null) {
throw MESSAGES.nullArgument("suffixes");
}
for (String suffix : suffixes) {
if (suffix == null) {
throw new IllegalArgumentException("Null suffix in " + suffixes);
}
}
this.suffixes = suffixes;
}
public boolean accepts(VirtualFile file) {
String name = file.getName();
for (String suffix : suffixes) {
if (name.endsWith(suffix)) { return false; }
}
return true;
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/automount/ 0000775 0000000 0000000 00000000000 13562475444 0024735 5 ustar 00root root 0000000 0000000 jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/automount/AbstractMountOwner.java 0000664 0000000 0000000 00000003174 13562475444 0031406 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util.automount;
/**
* Abstract MountOwner used to wrap a real object as an owner.
*
* @param the type of the actual owner
* @author John Bailey
*/
public abstract class AbstractMountOwner implements MountOwner {
private final T owner;
/**
* Construct with an object.
*
* @param owner the actual owner
*/
protected AbstractMountOwner(T owner) {
this.owner = owner;
}
/**
* Get the owner object
*
* @return the actual owner
*/
protected T getOwner() {
return owner;
}
@SuppressWarnings("unchecked")
@Override
public boolean equals(Object other) {
if (!(other instanceof AbstractMountOwner)) { return false; }
return getOwner().equals(AbstractMountOwner.class.cast(other).getOwner());
}
@Override
public int hashCode() {
return getOwner().hashCode();
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/automount/Automounter.java 0000664 0000000 0000000 00000025137 13562475444 0030132 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util.automount;
import static org.jboss.vfs.VFSMessages.MESSAGES;
import java.io.Closeable;
import java.io.IOException;
import java.util.Collection;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicBoolean;
import org.jboss.vfs.TempFileProvider;
import org.jboss.vfs.VFS;
import org.jboss.vfs.VFSLogger;
import org.jboss.vfs.VFSUtils;
import org.jboss.vfs.VirtualFile;
import org.jboss.vfs.util.PathTokenizer;
/**
* Utility used to manage mounting Virtual FileSystems.
*
* @author John Bailey
*/
public class Automounter {
/* Root entry in the tree. */
private static final RegistryEntry rootEntry = new RegistryEntry();
/* Map of owners and their references */
private static final ConcurrentMap> ownerReferences = new ConcurrentHashMap>();
/* Provider of temp files/directories*/
private static TempFileProvider tempFileProvider;
/**
* Private constructor
*/
private Automounter() {
}
/**
* Mount provided {@link VirtualFile} (if not mounted) and set the owner to be the provided target. (Self owned mount)
*
* @param target VirtualFile to mount
* @param mountOptions optional configuration to use for mounting
* @throws IOException when the target can not be mounted.
*/
public static void mount(VirtualFile target, MountOption... mountOptions) throws IOException {
mount(new VirtualFileOwner(target), target, mountOptions);
}
/**
* Mount provided {@link VirtualFile} (if not mounted) and add an owner entry. Also creates a back-reference to from the owner to the target.
*
* @param owner Object that owns the reference to the mount
* @param target VirtualFile to mount
* @param mountOptions optional configuration to use for mounting
* @throws IOException when the target can not be mounted.
*/
public static void mount(Object owner, VirtualFile target, MountOption... mountOptions) throws IOException {
mount(new SimpleMountOwner(owner), target, mountOptions);
}
/**
* Mount provided {@link VirtualFile} (if not mounted) and add an owner entry. Also creates a back-reference to from the owner to the target.
*
* @param owner VirtualFile that owns the reference to the mount
* @param target VirtualFile to mount
* @param mountOptions optional configuration to use for mounting
* @throws IOException when the target can not be mounted.
*/
public static void mount(VirtualFile owner, VirtualFile target, MountOption... mountOptions) throws IOException {
mount(new VirtualFileOwner(owner), target, mountOptions);
}
/**
* Mount provided {@link VirtualFile} (if not mounted) and add an owner entry. Also creates a back-reference to from the owner to the target.
*
* @param owner MountOwner that owns the reference to the mount
* @param target VirtualFile to mount
* @param mountOptions optional configuration to use for mounting
* @throws IOException when the target can not be mounted
*/
public static void mount(MountOwner owner, VirtualFile target, MountOption... mountOptions) throws IOException {
final RegistryEntry targetEntry = getEntry(target);
targetEntry.mount(target, getMountConfig(mountOptions));
targetEntry.inboundReferences.add(owner);
ownerReferences.putIfAbsent(owner, new HashSet());
ownerReferences.get(owner).add(targetEntry);
}
/**
* Creates a MountConfig and applies the provided mount options
*
* @param mountOptions options to use for mounting
* @return a MountConfig
*/
private static MountConfig getMountConfig(MountOption[] mountOptions) {
final MountConfig config = new MountConfig();
for (MountOption option : mountOptions) {
option.applyTo(config);
}
return config;
}
/**
* Add handle to owner, to be auto closed.
*
* @param owner the handle owner
* @param handle the handle
* @return add result
*/
public static boolean addHandle(VirtualFile owner, Closeable handle) {
RegistryEntry entry = getEntry(owner);
return entry.handles.add(handle);
}
/**
* Remove handle from owner.
*
* @param owner the handle owner
* @param handle the handle
* @return remove result
*/
public static boolean removeHandle(VirtualFile owner, Closeable handle) {
RegistryEntry entry = getEntry(owner);
return entry.handles.remove(handle);
}
/**
* Cleanup all references from the owner. Cleanup any mounted entries that become un-referenced in the process.
*
* @param owner {@link Object} to cleanup references for
*/
public static void cleanup(Object owner) {
cleanup(new SimpleMountOwner(owner));
}
/**
* Cleanup all references from the owner. Cleanup any mounted entries that become un-referenced in the process.
*
* @param owner {@link Object} to cleanup references for
*/
public static void cleanup(VirtualFile owner) {
cleanup(new VirtualFileOwner(owner));
}
/**
* Cleanup all references from the {@link MountOwner}. Cleanup any mounted entries that become un-referenced in the process.
*
* @param owner {@link MountOwner} to cleanup references for
*/
public static void cleanup(MountOwner owner) {
final Set references = ownerReferences.remove(owner);
if (references != null) {
for (RegistryEntry entry : references) {
entry.removeInboundReference(owner);
}
}
owner.onCleanup();
}
/**
* Determines whether a target {@link VirtualFile} is mounted.
*
* @param target target to check
* @return true if mounted, false otherwise
*/
public static boolean isMounted(VirtualFile target) {
return getEntry(target).isMounted();
}
/**
* Get the entry from the tree creating the entry if not present.
*
* @param virtualFile entry's owner file
* @return registry entry
*/
static RegistryEntry getEntry(VirtualFile virtualFile) {
if (virtualFile == null) {
throw MESSAGES.nullArgument("VirutalFile");
}
return rootEntry.find(virtualFile);
}
private static TempFileProvider getTempFileProvider() throws IOException {
if (tempFileProvider == null) { tempFileProvider = TempFileProvider.create("automount", Executors.newScheduledThreadPool(2)); }
return tempFileProvider;
}
static class RegistryEntry {
private final ConcurrentMap children = new ConcurrentHashMap();
private final Set inboundReferences = new HashSet();
private final List handles = new LinkedList();
private final AtomicBoolean mounted = new AtomicBoolean();
private void mount(VirtualFile target, MountConfig mountConfig) throws IOException {
if (mounted.compareAndSet(false, true)) {
if (target.isFile()) {
VFSLogger.ROOT_LOGGER.debugf("Automounting: %s with options %s", target, mountConfig);
final TempFileProvider provider = getTempFileProvider();
if (mountConfig.mountExpanded()) {
if (mountConfig.copyTarget()) { handles.add(VFS.mountZipExpanded(target, target, provider)); } else {
handles.add(VFS.mountZipExpanded(target.getPhysicalFile(), target, provider));
}
} else {
if (mountConfig.copyTarget()) { handles.add(VFS.mountZip(target, target, provider)); } else {
handles.add(VFS.mountZip(target.getPhysicalFile(), target, provider));
}
}
}
}
}
private void removeInboundReference(MountOwner owner) {
inboundReferences.remove(owner);
if (inboundReferences.isEmpty()) {
cleanup();
}
}
void cleanup() {
if (mounted.compareAndSet(true, false)) {
VFSUtils.safeClose(handles);
handles.clear();
final Collection entries = getEntriesRecursive();
for (RegistryEntry entry : entries) {
entry.cleanup();
}
}
}
private boolean isMounted() {
return mounted.get();
}
private RegistryEntry find(VirtualFile file) {
return find(PathTokenizer.getTokens(file.getPathName()));
}
private RegistryEntry find(List path) {
if (path.isEmpty()) {
return this;
}
final String current = path.remove(0);
children.putIfAbsent(current, new RegistryEntry());
final RegistryEntry childEntry = children.get(current);
return childEntry.find(path);
}
private Collection getEntriesRecursive() {
final List allHandles = new LinkedList();
collectEntries(this, allHandles);
return allHandles;
}
private void collectEntries(RegistryEntry registryEntry, List entries) {
for (RegistryEntry childEntry : registryEntry.children.values()) {
collectEntries(childEntry, entries);
entries.add(childEntry);
}
}
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/automount/MountConfig.java 0000664 0000000 0000000 00000004152 13562475444 0030032 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util.automount;
/**
* Configuration used to control the auto-mount behavior.
*
* @author John Bailey
*/
class MountConfig {
private boolean mountExpanded;
private boolean copyTarget;
/**
* Should the archive be mounted as an expanded zip filesystem. Defaults to false.
*
* @return true if it should be expanded
*/
boolean mountExpanded() {
return mountExpanded;
}
/**
* Set whether the mount should be an expanded zip filesystem.
*
* @param mountExpanded the boolean value to set it to
*/
void setMountExpanded(boolean mountExpanded) {
this.mountExpanded = mountExpanded;
}
/**
* Should the archive be copied to a temporary location before being mounted.
* Defaults to false.
*
* @return true if the archive should be copied before being mounted
*/
boolean copyTarget() {
return copyTarget;
}
/**
* Set whether the archive should be copied before being mounted.
*
* @param copyTarget the boolean value to set it to
*/
void setCopyTarget(boolean copyTarget) {
this.copyTarget = copyTarget;
}
@Override
public String toString() {
return new StringBuilder().append("MountConfig[Expanded: ").append(mountExpanded).append(", Copy: ").append(
copyTarget).append("]").toString();
}
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/automount/MountOption.java 0000664 0000000 0000000 00000002513 13562475444 0030074 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util.automount;
/**
* Custom configurations to use when mounting archives through the {@link Automounter}.
*
* @author John Bailey
*/
public enum MountOption {
EXPANDED {
void applyTo(MountConfig config) {
config.setMountExpanded(true);
}
},
COPY {
void applyTo(MountConfig config) {
config.setCopyTarget(true);
}
};
/**
* Each option must apply its custom settings to teh {@link MountConfig}.
*
* @param config MountConfig to apply settings to
*/
abstract void applyTo(MountConfig config);
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/automount/MountOwner.java 0000664 0000000 0000000 00000002030 13562475444 0027710 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util.automount;
/**
* An owner of a reference to an automounted resource.
*
* @author John Bailey
*/
public interface MountOwner {
/**
* A callback method allowing the mount owner to perform any addition cleanup
* specific to the owner type.
*/
void onCleanup();
}
jboss-vfs-3.2.15.Final/src/main/java/org/jboss/vfs/util/automount/SimpleMountOwner.java 0000664 0000000 0000000 00000002520 13562475444 0031066 0 ustar 00root root 0000000 0000000 /*
* JBoss, Home of Professional Open Source
* Copyright 2009, JBoss Inc., and individual contributors as indicated
* by the @authors tag.
*
* Licensed 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.jboss.vfs.util.automount;
/**
* Simple mount owner wrapper relying on any object type as the owner.
*
* @author John Bailey
*/
public class SimpleMountOwner extends AbstractMountOwner