package apollo.dev;
import java.io.*;
import java.net.*;
import java.util.*;
import apollo.*;
import houston.*;
public class DevPersistenceService implements PersistenceService
{
static Logger T = Logger.getLogger( DevPersistenceService.class );
File _muffinDir;
public DevPersistenceService()
{
File userDir = new File( System.getProperty( "user.home" ) );
File rootDir = new File( userDir, ".apollo" );
_muffinDir = new File( rootDir, "muffins" );
if( !_muffinDir.exists() )
_muffinDir.mkdirs();
}
public void setTag( URL url, int tag )
throws MalformedURLException
{
}
public FileContents get( URL url )
throws MalformedURLException, IOException, FileNotFoundException
{
return new DevFileContents( mapUrlToFile( url ) );
}
public String[] getNames( URL url )
throws MalformedURLException, IOException
{
File file = mapUrlToFile( url );
if( !url.toString().endsWith( "/" ) )
file = file.getParentFile();
File entries[] = file.listFiles();
ArrayList tempNames = new ArrayList();
if( entries != null )
{
for( int i = 0; i < entries.length; i++ )
{
File entry = entries[i];
if( entry.isDirectory() )
continue;
else
tempNames.add( entry.getName() );
}
}
return ( String[] ) tempNames.toArray( new String[0] );
}
public int getTag( URL url )
throws MalformedURLException
{
return CACHED;
}
public long create( URL url, long maxSize )
throws MalformedURLException, IOException
{
File file = mapUrlToFile( url );
file.getParentFile().mkdirs();
file.createNewFile();
return maxSize;
}
public void delete( URL url )
throws MalformedURLException, IOException
{
File file = mapUrlToFile( url );
file.delete();
}
private static String escapeSpecialCharacters( String line )
{
StringBuffer buf = new StringBuffer();
for( int pos = 0; pos < line.length(); )
{
char c = line.charAt( pos );
switch ( c )
{
case ':':
buf.append( "&c" );
++pos;
break;
default:
buf.append( c );
++pos;
break;
}
}
return buf.toString();
}
private File mapUrlToFile( URL url )
{
String protocol = url.getProtocol();
String host = url.getHost();
int port = url.getPort();
String path = url.getPath();
if( port == -1
&& protocol.toLowerCase().equals( "http" ) )
{
port = 80;
}
if( host.equals( "" ) )
host = "localhost";
T.debug( "protcol=" + protocol );
T.debug( "host=" + host );
T.debug( "port=" + port );
T.debug( "path=" + path );
StringBuffer mangledPathBuf = new StringBuffer();
mangledPathBuf.append( protocol
+ "/" + host
+ "/" + port );
if( path.startsWith( "/" ) )
path = path.substring( 1 );
T.debug( "path=" + path );
StringTokenizer tok = new StringTokenizer( path, "/" );
while( tok.hasMoreTokens() )
{
String name = tok.nextToken();
name = escapeSpecialCharacters( name );
mangledPathBuf.append( "/" + name );
}
T.debug( "mangledPath=" + mangledPathBuf.toString() );
File mangledPathFile = new File( _muffinDir, mangledPathBuf.toString() );
return mangledPathFile;
}
}