/*
* $Id: PathLoader.java,v 1.4 2002/09/16 08:05:06 jkl Exp $
*
* Copyright (c) 2002 Njet Communications Ltd. All Rights Reserved.
*
* Use is subject to license terms, as defined in
* Anvil Sofware License, Version 1.1. See LICENSE
* file, or http://njet.org/license-1.1.txt
*/
package anvil.server;
import java.io.File;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.IOException;
/**
* class PathLoader
*
* @author: Jani Lehtim�ki
*/
public class PathLoader implements Loader
{
private File _path;
public PathLoader(File path)
{
_path = path;
}
protected byte[] readClassData(File file)
{
FileInputStream input = null;
try {
if (file.exists()) {
input = new FileInputStream(file);
int length = (int)file.length();
int offset = 0;
byte[] data = new byte[length];
while(offset < length) {
int read = input.read(data, offset, length - offset);
if (read == -1) {
return null;
}
offset += read;
}
input.close();
return data;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (input != null) {
try {
input.close();
} catch (IOException e) {
}
}
}
return null;
}
public ClassData load(String name)
{
byte[] bytes = null;
String filename = _path.getPath() + "/" + name;
File dir = new File(filename);
if (dir.exists() && dir.isDirectory()) {
String latest_file = null;
int latest_version = 0;
String[] files = dir.list();
if (files != null) {
int n = files.length;
for(int i=0; i<n; i++) {
String file = files[i];
if (file.startsWith("v_") && file.endsWith(".class")) {
int length = file.length();
try {
int version = Integer.parseInt(file.substring(2, length - 6));
if (version > latest_version) {
latest_file = file;
latest_version = version;
}
} catch (NumberFormatException e) {
}
}
}
}
if (latest_file != null) {
name = name + "/v_" + latest_version;
bytes = readClassData(new File(dir, latest_file));
}
}
if (bytes == null) {
filename = filename + ".class";
bytes = readClassData(new File(filename));
}
if (bytes != null) {
return new ClassData(name, bytes);
} else {
return null;
}
}
}