package net.sourceforge.javautil.common.coersion.impl;
import java.net.MalformedURLException;
import java.net.URL;
import net.sourceforge.javautil.common.URLUtil;
import net.sourceforge.javautil.common.coersion.CoersionException;
import net.sourceforge.javautil.common.exception.ThrowableManagerRegistry;
import net.sourceforge.javautil.common.io.IVirtualArtifact;
import net.sourceforge.javautil.common.io.VirtualArtifactNotFoundException;
import net.sourceforge.javautil.common.io.VirtualArtifactSystem;
import net.sourceforge.javautil.common.io.IVirtualDirectory;
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;
/**
* This will translate system artifacts <-> strings.
*
* @author elponderador
* @author $Author: ponderator $
* @version $Id: CoersionVirtualArtifact.java 2462 2010-10-24 11:38:22Z ponderator $
*/
public class CoersionVirtualArtifact extends CoersionAbstract<CharSequence, IVirtualArtifact> {
public CoersionVirtualArtifact() {
super(CharSequence.class, IVirtualArtifact.class);
this.toSuper = true;
}
public Object coerce(Object original, Class target) {
if (original instanceof CharSequence) {
String url = String.valueOf( original );
if (url.startsWith("file:/")) {
return url.endsWith("/") || IVirtualDirectory.class.isAssignableFrom(target) ? new SystemDirectory( url.substring(6) ) : new SystemFile( url.substring(6) );
} else if (url.startsWith(VirtualArtifactSystem.VAS_PROTOCOL + ":")) {
String host = url.split(":")[1];
String path = url.substring((VirtualArtifactSystem.VAS_PROTOCOL + ":" + host + ":").length());
VirtualArtifactSystem vas = VirtualArtifactSystem.get(host, true);
return url.endsWith("/") ? vas.getDirectory(new SimplePath(path), true) : vas.getFile(new SimplePath(path), true);
} else {
return url.endsWith("/") || IVirtualDirectory.class.isAssignableFrom(target) ? new SystemDirectory(url) : new SystemFile(url);
}
} else if (original instanceof IVirtualArtifact) {
String url = ((IVirtualArtifact)original).getURL().toExternalForm();
if (original instanceof IVirtualDirectory && !url.endsWith("/")) url += "/";
return url;
}
throw new CoersionException("Could not convert " + original + " to " + target);
}
}