import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.File;
import java.io.FileInputStream;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ForwardLockServlet extends HttpServlet{
protected static final String ENC = "ISO-8859-1";
protected static final byte[] CRLF = { 0xd, 0xa };
protected static final String BOUNDARY = "-boundary-";
protected static final int BUFSIZE = 1024 * 4;
protected static String FS =
System.getProperty("file.separator");
protected String mountPoint;
protected boolean debug;
public void init() throws ServletException{
mountPoint = getInitParameter("mountPoint");
if (mountPoint == null || mountPoint.length() == 0){
throw new ServletException("mountPoint: invalid init parameter.");
}
if (mountPoint.endsWith(FS) && mountPoint.length() != FS.length()){
mountPoint = mountPoint.substring(0, mountPoint.length() -
FS.length());
}
debug = new Boolean(getInitParameter("debug")).booleanValue();
log("initialized: mountPoint=" + mountPoint +
" debug=" + debug);
}
public void doGet(
HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
String ru = request.getRequestURI();
int n = ru.lastIndexOf("/");
String filename = ru.substring(n+1);
if (debug){
log("request=" + ru + " filename=" + filename);
}
File file = new File(mountPoint + FS + filename);
if (! file.exists()){
log("file does not exists." + file);
sendError(response);
return;
}
String mimeType = getServletContext().getMimeType(filename);
if (mimeType == null){
log("no mime-type defined." + filename);
sendError(response);
return;
}
response.setContentType(
"application/vnd.oma.drm.message; boundary=" +
BOUNDARY);
OutputStream os = response.getOutputStream();
put(os, file, mimeType);
os.close();
}
protected void sendError(HttpServletResponse response) throws IOException{
response.sendError(response.SC_NOT_FOUND);
}
public void put(OutputStream os, File file, String mimeType)
throws IOException{
os.write(("--" + BOUNDARY).getBytes(ENC));
os.write(CRLF);
os.write(("Content-type: " + mimeType).getBytes(ENC));
os.write(CRLF);
os.write("Content-Transfer-Encoding: binary".getBytes(ENC));
os.write(CRLF);
os.write(CRLF);
InputStream is = new FileInputStream(file);
byte[] bytes = new byte[BUFSIZE];
int n;
while (true){
if ((n = is.read(bytes)) == -1){
break;
}
os.write(bytes, 0, n);
}
is.close();
os.write(CRLF);
os.write(("--" + BOUNDARY + "--").getBytes(ENC));
}
}
|