package org.jboss.net.protocol.file;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.net.URLConnection;
import java.net.URL;
import java.net.MalformedURLException;
import java.net.URLDecoder;
import java.security.Permission;
import java.io.FilePermission;
import java.io.BufferedInputStream;
public class FileURLConnection
extends URLConnection
{
static boolean decodeFilePaths = false;
static
{
decodeFilePaths = Boolean.getBoolean("org.jboss.net.protocol.file.decodeFilePaths");
}
protected File file;
public FileURLConnection(final URL url)
throws MalformedURLException, IOException
{
super(url);
String path = url.getPath();
if( decodeFilePaths )
path = URLDecoder.decode(path, "UTF-8");
file = new File(path.replace('/', File.separatorChar).replace('|', ':'));
doOutput = false;
}
public File getFile()
{
return file;
}
public void connect() throws IOException
{
if (connected)
return;
if (!file.exists())
{
throw new FileNotFoundException(file.getPath());
}
connected = true;
}
public InputStream getInputStream() throws IOException
{
if (!connected)
connect();
return new FileInputStream(file);
}
public OutputStream getOutputStream() throws IOException
{
if (!connected)
connect();
SecurityManager sm = System.getSecurityManager();
if( sm != null )
{
FilePermission p = new FilePermission(file.getPath(), "write");
sm.checkPermission(p);
}
return new FileOutputStream(file);
}
public String getHeaderField(final String name)
{
String headerField = null;
if (name.equalsIgnoreCase("last-modified"))
headerField = String.valueOf(getLastModified());
else if (name.equalsIgnoreCase("content-length"))
headerField = String.valueOf(file.length());
else if (name.equalsIgnoreCase("content-type"))
{
headerField = getFileNameMap().getContentTypeFor(file.getName());
if( headerField == null )
{
try
{
InputStream is = getInputStream();
BufferedInputStream bis = new BufferedInputStream(is);
headerField = URLConnection.guessContentTypeFromStream(bis);
bis.close();
}
catch(IOException e)
{
}
}
}
else if (name.equalsIgnoreCase("date"))
headerField = String.valueOf(file.lastModified());
else
{
headerField = super.getHeaderField(name);
}
return headerField;
}
public Permission getPermission() throws IOException
{
return new FilePermission(file.getPath(), "read");
}
public long getLastModified()
{
return file.lastModified();
}
}