package org.apache.commons.vfs2.provider;
import java.io.IOException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLStreamHandler;
import org.apache.commons.vfs2.FileObject;
import org.apache.commons.vfs2.FileSystemException;
import org.apache.commons.vfs2.FileSystemOptions;
import org.apache.commons.vfs2.VFS;
public class DefaultURLStreamHandler extends URLStreamHandler {
private final VfsComponentContext context;
private final FileSystemOptions fileSystemOptions;
public DefaultURLStreamHandler(final VfsComponentContext context) {
this(context, null);
}
public DefaultURLStreamHandler(final VfsComponentContext context, final FileSystemOptions fileSystemOptions) {
this.context = context;
this.fileSystemOptions = fileSystemOptions;
}
@Override
protected URLConnection openConnection(final URL url) throws IOException {
final FileObject entry = context.resolveFile(url.toExternalForm(), fileSystemOptions);
return new DefaultURLConnection(url, entry.getContent());
}
@Override
protected void parseURL(final URL u, final String spec, final int start, final int limit) {
try {
final FileObject old = context.resolveFile(u.toExternalForm(), fileSystemOptions);
FileObject newURL;
if (start > 0 && spec.charAt(start - 1) == ':') {
newURL = context.resolveFile(old, spec, fileSystemOptions);
} else {
if (old.isFile() && old.getParent() != null) {
newURL = old.getParent().resolveFile(spec);
} else {
newURL = old.resolveFile(spec);
}
}
final String url = newURL.getName().getURI();
final StringBuilder filePart = new StringBuilder();
final String protocolPart = UriParser.extractScheme(VFS.getManager().getSchemes(), url, filePart);
setURL(u, protocolPart, "", -1, null, null, filePart.toString(), null, null);
} catch (final FileSystemException fse) {
throw new RuntimeException(fse.getMessage());
}
}
@Override
protected String toExternalForm(final URL u) {
return u.getProtocol() + ":" + u.getFile();
}
}