?? filehttprequesthandler.java
字號:
package webServer;
import HTTP.*;
import java.net.*;
import java.util.*;
import java.io.*;
import org.w3c.dom.*;
/**http://www.codefans.net
* Handles requests for files. This can't dynamicly generate content.
* A short configuration file is in data\fileHandlerConfig.xml.
*/
public class FileHTTPRequestHandler implements HTTPRequestHandler
{
private static final File CONFIG_FILE = new File("data\\fileHandlerConfig.xml");
private static String targetDirectory = loadConfigurationAndGetTargetDirectory();
private static String loadConfigurationAndGetTargetDirectory()
{
String result = "public_html";
try
{
Document doc = XMLParser.getDocumentFor(CONFIG_FILE);
NodeList nl = doc.getElementsByTagName("targetDirectory");
if (nl.getLength() > 0)
{
Element e = (Element)nl.item(0);
String dir = e.getAttribute("value");
if (dir != null)
{
result = dir;
// Be flexible if the user thought he should include a trailing slash.
if (result.endsWith("\\") || result.endsWith("/"))
result = result.substring(0, result.length() - 1);
}
}
}
catch (Throwable t)
{
t.printStackTrace();
System.err.println("Unable to load configuration from "+CONFIG_FILE);
}
return result;
}
public boolean canHandle(HTTPRequest request)
{
return true;
}
/**
* Gets HTML formatted info for the specified file
*/
private String getFileInfoContentFor(File parent,File f,boolean needsDirectoryNameInRelativeAddresses)
{
String hrefPath = f.getName();
if (needsDirectoryNameInRelativeAddresses)
{
hrefPath = parent.getName() + "/" + hrefPath;
}
String result = "<a href=\"" + hrefPath + "\">" + f.getName() + "</a>";
return result;
}
/**
* Tries to get contents from an index page within the specified directory.
* @return null if no index page is found.
*/
private byte[] getIndexPageContentsForDirectory(File dir)
{
String []indexPageNames = new String[]
{"index.html","index.htm","default.html","default.htm"};
byte[] result = null;
for (String pageName: indexPageNames)
{
result = getFileContents(dir, pageName);
if (result!=null)
return result;
}
return null;
}
/**
* Automatically generates indexing content for a directory.
* @param requestPath may seem redundant but it is needed to
* determine if the browser needs the directory name in relative addresses.
* The directory name is needed in relative addresses if and only if '/' is not
* at the end of the request path.
*/
private byte[] getContentForDirectory(File dir,boolean needsDirectoryNameInRelativeAddresses)
{
if (!dir.isDirectory())
{
System.err.println("FileHTTPRequestHandler getContentForDirectory expected a directory instead of ");
}
byte[] indexPageContents = getIndexPageContentsForDirectory(dir);
if (indexPageContents != null)
return indexPageContents;
try
{
ByteArrayOutputStream bout = new ByteArrayOutputStream();
PrintStream out = new PrintStream(bout);
File[] files = dir.listFiles();
out.println("<html>");
out.println(" <head>");
out.println(" <title>Directory '"+dir.getName()+"'</title>");
out.println(" </head>");
out.println("<body>");
out.println(" <h1>Directory '" + dir.getName() + "'</h1><hr />");
out.println("<ul>");
out.println("<li>");
// loop through these files
for (int i = 0; i < files.length; i++)
{
File f = files[i];
out.println(" <li>"+getFileInfoContentFor(dir,f,needsDirectoryNameInRelativeAddresses)+"</li>");
}
out.println("</ul><hr />");
out.println("Generated by Simple Web Server");
out.println("</body></html>");
return bout.toByteArray();
}
catch (Throwable t)
{
t.printStackTrace();
System.err.println("Unable to create directory content");
}
return (""+dir.getName()).getBytes();
}
/**
* @param filePath is the path sent from the HTTP request.
* The specified file would be within the targetDirectory.
* @return null if the file doesn't exist.
*/
private byte[] getFileContents(String filePath)
{
return getFileContents(getFileFrom(filePath));
}
private File getFileFrom(String filePath)
{
return getFileFrom(new File(targetDirectory),filePath);
}
private File getFileFrom(File parentDirectory, String filePath)
{
final String separator = System.getProperty("file.separator");
if (filePath.startsWith(separator))
{
filePath = filePath.substring(separator.length());
}
File f = new File(parentDirectory + separator + filePath);
return f;
}
private byte[] getFileContents(File parentDirectory, String filePath)
{
return getFileContents(getFileFrom(parentDirectory, filePath));
}
/**
* Gets the contents of the specified file.
* @return null if there is a problem.
*/
private byte[] getFileContents(File f)
{
if (!f.exists())
return null;
try
{
InputStream in = new FileInputStream(f);
byte[] data = new byte[(int)f.length()];
int position = 0;
while (position < data.length)
{
int numBytesRead = in.read(data,position,data.length-position);
if (numBytesRead < 0)
{
throw new EOFException("Unexpected end of file in '"+f.getAbsolutePath()+"' "
+position+" bytes were read in until the end. "
+data.length+" was the expected length.");
}
position += numBytesRead;
}
return data;
}
catch (Throwable t)
{
t.printStackTrace();
System.err.println("Unable to read from requested file: "+f);
}
return null;
}
private byte[] get404ResponseContents()
{
byte[] result = getFileContents("404.html");
if (result == null)
return "<html>404 - File not found</html>".getBytes();
else
return result;
}
/**
* Gets an appropriate response to a request for the specified file.
* If the file doesn't exist or can't be read 404 is returned.
* If the file is a directory, an index page is searched for.
* If an index page isn't found, one is automatically generated.
*/
private HTTPResponse getResponseForFile(String filePath,boolean needsDirectoryNameInRelativeAddresses)
{
HTTPResponse response = new HTTPResponse();
File f = getFileFrom(filePath);
byte[] contents = null;
if (f.isDirectory())
{
contents = getContentForDirectory(f, needsDirectoryNameInRelativeAddresses);
}
else
contents = getFileContents(f);
try
{
if (contents == null)
{ // file not found or problem reading from file
response.setReponseCodeNumber(404);
contents = get404ResponseContents();
response.setContent(contents);
response.setContentType("text/html");
}
else
{
if (!f.isDirectory())
response.setContentType(ContentTypes.guessContentTypeFromPath(filePath));
response.setContent(contents);
}
}
catch (Throwable t)
{
t.printStackTrace();
System.err.println("Problem generating response to client request for '"+filePath+"'.");
}
return response;
}
public void handleRequest(HTTPRequest request)
{
/* try to handle the specified request by sending
* a response to its socket's output stream
*/
String filePath = request.getFilePath();
HTTPResponse response = getResponseForFile(filePath,!request.isForDirectory());
try
{
/**
* Write the response to the client.
*/
response.writeTo(request.getSocket().getOutputStream());
}
catch (Throwable t)
{
t.printStackTrace();
System.err.println("Unable to properly respond to the client.");
}
}
}
?? 快捷鍵說明
復(fù)制代碼
Ctrl + C
搜索代碼
Ctrl + F
全屏模式
F11
切換主題
Ctrl + Shift + D
顯示快捷鍵
?
增大字號
Ctrl + =
減小字號
Ctrl + -