Commit a1b3873b authored by O'Reilly Media, Inc.'s avatar O'Reilly Media, Inc.

Initial commit

parents
9780596003845
\ No newline at end of file
import java.io.*;
import java.sql.*;
import java.util.Date;
import javax.servlet.*;
import javax.servlet.http.*;
public class AsciiResult extends HttpServlet {
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
res.setContentType("text/html");
ServletOutputStream out = res.getOutputStream();
// ServletOutputStream has println() methods for writing strings
// The println() call only works for single-byte character encodings
// If you need multibyte, make sure to set the charset in the Content-Type
// and use for example out.write(str.getBytes("Shift_JIS")) for Japanese
out.println("Content current as of");
out.println(new Date().toString());
// ... retrieve a database ResultSet here ...
ResultSet resultSet = null;
try {
InputStream ascii = resultSet.getAsciiStream(1);
returnStream(ascii, out);
}
catch (SQLException e) {
throw new ServletException(e);
}
}
public static void returnStream(InputStream in, OutputStream out)
throws FileNotFoundException, IOException {
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
}
}
import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class LibraryLoader {
static final String CONFIG_FILE = "library.properties";
static final String CACHE_FILE = "library.ser";
public ConfigData load() throws IOException {
// Find the config file and fetch its contents as Properties
Resource config = new Resource(CONFIG_FILE);
Properties props = new Properties();
props.load(config.getInputStream());
// Determine the source dir of the config file and look for a cache file
// next to it containing a full representation of our program state.
// If we find a cache file and it is current, load and return that data.
if (config.getDirectory() != null) {
File cache = new File(config.getDirectory(), CACHE_FILE);
if (cache.exists() &&
cache.lastModified() >= config.lastModified()) {
try {
return loadCache(new FileInputStream(cache));
}
catch (IOException ignored) { }
}
}
// We get here if there's no cache file or it's stale and we need to do a
// full reload. Locate the name of the raw data file from the config file
// and return its contents using Resource.
Resource data = new Resource(props.getProperty("data.file"));
return loadData(data.getInputStream());
}
private ConfigData loadCache(InputStream in) {
// Read the file, perhaps as a serialized object
return null;
}
private ConfigData loadData(InputStream in) {
// Read the file, perhaps as XML
return null;
}
class ConfigData {
// An example class that would hold config data
}
}
import java.io.*;
import java.util.prefs.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class NoConversions extends HttpServlet {
String name = "content.txt"; // demo file to send
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String file = getServletContext().getRealPath(name);
res.setContentType("text/plain");
OutputStream out = res.getOutputStream();
returnFile(file, out);
}
public static void returnFile(String filename, OutputStream out)
throws FileNotFoundException, IOException {
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(filename));
byte[] buf = new byte[4 * 1024]; // 4K buffer
int bytesRead;
while ((bytesRead = in.read(buf)) != -1) {
out.write(buf, 0, bytesRead);
}
}
finally {
if (in != null) in.close();
}
}
}
## Example files for the title:
# 9780596003845
[![9780596003845](https://resources.oreilly.com/uploads/system/group/avatar/3/tarsier_hi_elbows.png)](https://www.safaribooksonline.com/)
The following applies to example files from material published by O’Reilly Media, Inc. Content from other publishers may include different rules of usage. Please refer to any additional usage rights explained in the actual example files or refer to the publisher’s website.
O'Reilly books are here to help you get your job done. In general, you may use the code in O'Reilly books in your programs and documentation. You do not need to contact us for permission unless you're reproducing a significant portion of the code. For example, writing a program that uses several chunks of code from our books does not require permission. Answering a question by citing our books and quoting example code does not require permission. On the other hand, selling or distributing a CD-ROM of examples from O'Reilly books does require permission. Incorporating a significant amount of example code from our books into your product's documentation does require permission.
We appreciate, but do not require, attribution. An attribution usually includes the title, author, publisher, and ISBN.
If you think your use of code examples falls outside fair use or the permission given here, feel free to contact us at <permissions@oreilly.com>.
Please note that the examples are not production code and have not been carefully testing. They are provided "as-is" and come with no warranty of any kind.
import java.io.*;
import java.net.*;
import java.util.*;
/**
* A class to locate resources, retrieve their contents, and determine their
* last modified time. To find the resource the class searches the CLASSPATH
* first, then Resource.class.getResource("/" + name). If the Resource finds
* a "file:" URL then the file path will be treated as a file. Otherwise the
* path is treated as a URL and has limited last modified info.
*/
public class Resource implements Serializable {
private String name;
private File file;
private URL url;
public Resource(String name) throws IOException {
this.name = name;
SecurityException exception = null;
try {
// Search using the CLASSPATH. If found, "file" is set and the call
// returns true. A SecurityException may bubble up.
if (tryClasspath(name)) {
return;
}
}
catch (SecurityException e) {
exception = e; // save for later
}
try {
// Search using the class loader getResource(). If found as a file,
// "file" is set, if found as a URL then "url" is set.
if (tryLoader(name)) {
return;
}
}
catch (SecurityException e) {
exception = e; // save for later
}
// If we get here we failed, report the exception
String msg = "";
if (exception != null) {
msg = ": " + exception;
}
throw new IOException("Resource '" + name + "' could not be found in " +
"the CLASSPATH (" + System.getProperty("java.class.path") +
"), nor could it be located by the classloader responsible for the " +
"web application (WEB-INF/classes)" + msg);
}
/**
* Returns the resource name, as passed to the constructor.
*/
public String getName() {
return name;
}
/**
* Returns an input stream to read the resource contents.
*/
public InputStream getInputStream() throws IOException {
if (file != null) {
return new BufferedInputStream(new FileInputStream(file));
}
else if (url != null) {
return new BufferedInputStream(url.openStream());
}
return null;
}
/**
* Returns when the resource was last modified. If the resource was found
* using a URL, this method will only work if the URL connection supports
* last modified information. If there's no support, Long.MAX_VALUE is
* returned. Perhaps this should return -1 but we return MAX_VALUE on
* the assumption that if you can't determine the time, assume it's
* maximally new.
*/
public long lastModified() {
if (file != null) {
return file.lastModified();
}
else if (url != null) {
try {
return url.openConnection().getLastModified(); // hail mary
}
catch (IOException e) { return Long.MAX_VALUE; }
}
return 0; // can't happen
}
/**
* Returns the directory containing the resource, or null if the resource
* isn't directly available on the filesystem. This value can be used to
* locate the config file on disk or write files in the same directory.
*/
public String getDirectory() {
if (file != null) {
return file.getParent();
}
else if (url != null) {
return null;
}
return null;
}
// Returns true if found
private boolean tryClasspath(String filename) {
String classpath = System.getProperty("java.class.path");
String[] paths = split(classpath, File.pathSeparator);
file = searchDirectories(paths, filename);
return (file != null);
}
private static File searchDirectories(String[] paths, String filename) {
SecurityException exception = null;
for (int i = 0; i < paths.length; i++) {
try {
File file = new File(paths[i], filename);
if (file.exists() && !file.isDirectory()) {
return file;
}
}
catch (SecurityException e) {
// Security exceptions can usually be ignored, but if all attempts
// to find the file fail, then report the (last) security exception.
exception = e;
}
}
// Couldn't find any match
if (exception != null) {
throw exception;
}
else {
return null;
}
}
// Splits a String into pieces according to a delimiter.
// Uses JDK 1.1 classes for backward compatibility.
// JDK 1.4 actually has a split() method now.
private static String[] split(String str, String delim) {
// Use a Vector to hold the splittee strings
Vector v = new Vector();
// Use a StringTokenizer to do the splitting
StringTokenizer tokenizer = new StringTokenizer(str, delim);
while (tokenizer.hasMoreTokens()) {
v.addElement(tokenizer.nextToken());
}
String[] ret = new String[v.size()];
v.copyInto(ret);
return ret;
}
// Returns true if found
private boolean tryLoader(String name) {
name = "/" + name;
URL res = Resource.class.getResource(name);
if (res == null) {
return false;
}
// Try converting from a URL to a File
File resFile = urlToFile(res);
if (resFile != null) {
file = resFile;
}
else {
url = res;
}
return true;
}
private static File urlToFile(URL res) {
String externalForm = res.toExternalForm();
if (externalForm.startsWith("file:")) {
return new File(externalForm.substring(5));
}
return null;
}
public String toString() {
return "[Resource: File: " + file + " URL: " + url + "]";
}
}
import java.io.*;
import java.util.prefs.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class WastedConversions extends HttpServlet {
// Random file, for demo purposes only
String name = "content.txt";
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
String file = getServletContext().getRealPath(name);
res.setContentType("text/plain");
PrintWriter out = res.getWriter();
returnFile(file, out);
}
public static void returnFile(String filename, Writer out)
throws FileNotFoundException, IOException {
Reader in = null;
try {
in = new BufferedReader(new FileReader(filename));
char[] buf = new char[4 * 1024]; // 4K char buffer
int charsRead;
while ((charsRead = in.read(buf)) != -1) {
out.write(buf, 0, charsRead);
}
}
finally {
if (in != null) in.close();
}
}
}
logo.gif

157 KB

Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment