package net.sourceforge.javautil.common;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import net.sourceforge.javautil.common.classloader.ClassLoaderResource;
import net.sourceforge.javautil.common.classloader.ClassLoaderScanner;
import net.sourceforge.javautil.common.io.IVirtualArtifact;
import net.sourceforge.javautil.common.io.IVirtualFile;
import net.sourceforge.javautil.common.io.IVirtualPath;
import net.sourceforge.javautil.common.io.impl.SimplePath;
import net.sourceforge.javautil.common.io.impl.ISystemArtifact;
import net.sourceforge.javautil.common.io.impl.SystemDirectory;
import net.sourceforge.javautil.common.io.impl.SystemFile;
/**
* Common routines related to {@link IVirtualArtifact}'s.
*
* @author elponderador
* @author $Author: ponderator $
* @version $Id: VirtualArtifactUtil.java 2297 2010-06-16 00:13:14Z ponderator $
*/
public class VirtualArtifactUtil {
/**
* This will get the resource relative to the class package path, similar to {@link Class#getResource(String)}.
*
* @see #getResource(String)
*/
public static IVirtualFile getResource (Class clazz, String resource) {
return getResource(ClassNameUtil.toRelativePackagePath(clazz.getPackage().getName()) + "/" + resource);
}
/**
* Get a resource wrapped as a {@link IVirtualFile}.
*
* @param resource The resource to search for
* @return A {@link IVirtualFile} implementation that will wrap the resource, or null if no such resource exists
*/
public static IVirtualFile getResource (String resource) {
ClassLoaderResource rsc = ClassLoaderScanner.getResource(resource);
if (rsc == null && !resource.startsWith("/")) rsc = ClassLoaderScanner.getResource("META-INF/" + resource);
return rsc == null ? null : rsc.getFile();
}
/**
* @param artifact The artifact in question
* @return A virtual path for the artifact
*/
public static IVirtualPath createPath (File artifact) {
List<String> parts = new ArrayList<String>();
parts.add(artifact.getName());
while (artifact.getParent() != null) {
artifact = artifact.getParentFile();
if (artifact.getName().startsWith(":")) break;
if ("".equals(artifact.getName())) {
parts.add(0, artifact.getPath().replaceAll("[\\\\/]", ""));
} else
parts.add(0, artifact.getName());
}
return new SimplePath( parts.toArray(new String[parts.size()]) );
}
/**
* @param artifact The artifact in question
* @return A {@link SystemFile} or a {@link SystemDirectory} wrapper depending on the type of the file
*/
public static ISystemArtifact getSystemArtifact (File artifact) {
return artifact.isFile() ? new SystemFile(artifact) : new SystemDirectory(artifact);
}
}