Replaced tabs with 4 spaces.

This commit is contained in:
vibul 2012-04-27 09:32:35 +10:00
parent 802e5366b2
commit 66b4735acd
22 changed files with 4123 additions and 4252 deletions

View File

@ -27,14 +27,15 @@ import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.util.CharsetUtil; import org.jboss.netty.util.CharsetUtil;
public class HttpUploadClientHandler extends SimpleChannelUpstreamHandler { public class HttpUploadClientHandler extends SimpleChannelUpstreamHandler {
private static final InternalLogger logger = private static final InternalLogger logger = InternalLoggerFactory
InternalLoggerFactory.getInstance(HttpUploadClientHandler.class); .getInstance(HttpUploadClientHandler.class);
private volatile boolean readingChunks; private volatile boolean readingChunks;
@Override @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
if (!readingChunks) { if (!readingChunks) {
HttpResponse response = (HttpResponse) e.getMessage(); HttpResponse response = (HttpResponse) e.getMessage();
@ -42,8 +43,8 @@ public class HttpUploadClientHandler extends SimpleChannelUpstreamHandler {
logger.info("VERSION: " + response.getProtocolVersion()); logger.info("VERSION: " + response.getProtocolVersion());
if (!response.getHeaderNames().isEmpty()) { if (!response.getHeaderNames().isEmpty()) {
for (String name: response.getHeaderNames()) { for (String name : response.getHeaderNames()) {
for (String value: response.getHeaders(name)) { for (String value : response.getHeaders(name)) {
logger.info("HEADER: " + name + " = " + value); logger.info("HEADER: " + name + " = " + value);
} }
} }

View File

@ -41,8 +41,8 @@ public class HttpUploadClientPipelineFactory implements ChannelPipelineFactory {
// Enable HTTPS if necessary. // Enable HTTPS if necessary.
if (ssl) { if (ssl) {
SSLEngine engine = SSLEngine engine = SecureChatSslContextFactory.getClientContext()
SecureChatSslContextFactory.getClientContext().createSSLEngine(); .createSSLEngine();
engine.setUseClientMode(true); engine.setUseClientMode(true);
pipeline.addLast("ssl", new SslHandler(engine)); pipeline.addLast("ssl", new SslHandler(engine));
@ -50,12 +50,13 @@ public class HttpUploadClientPipelineFactory implements ChannelPipelineFactory {
pipeline.addLast("codec", new HttpClientCodec()); pipeline.addLast("codec", new HttpClientCodec());
// Remove the following line if you don't want automatic content decompression. // Remove the following line if you don't want automatic content
// decompression.
pipeline.addLast("inflater", new HttpContentDecompressor()); pipeline.addLast("inflater", new HttpContentDecompressor());
// to be used since huge file transfer // to be used since huge file transfer
pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler());
pipeline.addLast("handler", new HttpUploadClientHandler()); pipeline.addLast("handler", new HttpUploadClientHandler());
return pipeline; return pipeline;
} }

View File

@ -23,33 +23,33 @@ import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory;
public class HttpUploadServer { public class HttpUploadServer {
private final int port; private final int port;
public HttpUploadServer(int port) { public HttpUploadServer(int port) {
this.port = port; this.port = port;
} }
public void run() { public void run() {
// Configure the server. // Configure the server.
ServerBootstrap bootstrap = new ServerBootstrap( ServerBootstrap bootstrap = new ServerBootstrap(
new NioServerSocketChannelFactory( new NioServerSocketChannelFactory(
Executors.newCachedThreadPool(), Executors.newCachedThreadPool(),
Executors.newCachedThreadPool())); Executors.newCachedThreadPool()));
// Set up the event pipeline factory. // Set up the event pipeline factory.
bootstrap.setPipelineFactory(new HttpUploadServerPipelineFactory()); bootstrap.setPipelineFactory(new HttpUploadServerPipelineFactory());
// Bind and start to accept incoming connections. // Bind and start to accept incoming connections.
bootstrap.bind(new InetSocketAddress(port)); bootstrap.bind(new InetSocketAddress(port));
} }
public static void main(String[] args) { public static void main(String[] args) {
int port; int port;
if (args.length > 0) { if (args.length > 0) {
port = Integer.parseInt(args[0]); port = Integer.parseInt(args[0]);
} else { } else {
port = 8080; port = 8080;
} }
new HttpUploadServer(port).run(); new HttpUploadServer(port).run();
} }
} }

View File

@ -63,9 +63,9 @@ import org.jboss.netty.logging.InternalLoggerFactory;
import org.jboss.netty.util.CharsetUtil; import org.jboss.netty.util.CharsetUtil;
public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler { public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
private static final InternalLogger logger = private static final InternalLogger logger = InternalLoggerFactory
InternalLoggerFactory.getInstance(HttpUploadServerHandler.class); .getInstance(HttpUploadServerHandler.class);
private volatile HttpRequest request; private volatile HttpRequest request;
@ -96,7 +96,8 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
} }
@Override @Override
public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { public void messageReceived(ChannelHandlerContext ctx, MessageEvent e)
throws Exception {
if (!readingChunks) { if (!readingChunks) {
// clean previous FileUpload if Any // clean previous FileUpload if Any
if (decoder != null) { if (decoder != null) {
@ -115,18 +116,18 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n");
responseContent.append("===================================\r\n"); responseContent.append("===================================\r\n");
responseContent.append("VERSION: " + responseContent.append("VERSION: "
request.getProtocolVersion().getText() + "\r\n"); + request.getProtocolVersion().getText() + "\r\n");
responseContent.append("REQUEST_URI: " + request.getUri() + responseContent.append("REQUEST_URI: " + request.getUri()
"\r\n\r\n"); + "\r\n\r\n");
responseContent.append("\r\n\r\n"); responseContent.append("\r\n\r\n");
// new method // new method
List<Entry<String, String>> headers = request.getHeaders(); List<Entry<String, String>> headers = request.getHeaders();
for (Entry<String, String> entry: headers) { for (Entry<String, String> entry : headers) {
responseContent.append("HEADER: " + entry.getKey() + "=" + responseContent.append("HEADER: " + entry.getKey() + "="
entry.getValue() + "\r\n"); + entry.getValue() + "\r\n");
} }
responseContent.append("\r\n\r\n"); responseContent.append("\r\n\r\n");
@ -139,19 +140,19 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
CookieDecoder decoder = new CookieDecoder(); CookieDecoder decoder = new CookieDecoder();
cookies = decoder.decode(value); cookies = decoder.decode(value);
} }
for (Cookie cookie: cookies) { for (Cookie cookie : cookies) {
responseContent.append("COOKIE: " + cookie.toString() + "\r\n"); responseContent.append("COOKIE: " + cookie.toString() + "\r\n");
} }
responseContent.append("\r\n\r\n"); responseContent.append("\r\n\r\n");
QueryStringDecoder decoderQuery = new QueryStringDecoder(request QueryStringDecoder decoderQuery = new QueryStringDecoder(
.getUri()); request.getUri());
Map<String, List<String>> uriAttributes = decoderQuery Map<String, List<String>> uriAttributes = decoderQuery
.getParameters(); .getParameters();
for (String key: uriAttributes.keySet()) { for (String key : uriAttributes.keySet()) {
for (String valuen: uriAttributes.get(key)) { for (String valuen : uriAttributes.get(key)) {
responseContent.append("URI: " + key + "=" + valuen + responseContent.append("URI: " + key + "=" + valuen
"\r\n"); + "\r\n");
} }
} }
responseContent.append("\r\n\r\n"); responseContent.append("\r\n\r\n");
@ -174,10 +175,10 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
return; return;
} }
responseContent.append("Is Chunked: " + request.isChunked() + responseContent.append("Is Chunked: " + request.isChunked()
"\r\n"); + "\r\n");
responseContent.append("IsMultipart: " + decoder.isMultipart() + responseContent.append("IsMultipart: " + decoder.isMultipart()
"\r\n"); + "\r\n");
if (request.isChunked()) { if (request.isChunked()) {
// Chunk version // Chunk version
responseContent.append("Chunks: "); responseContent.append("Chunks: ");
@ -202,7 +203,8 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
return; return;
} }
responseContent.append("o"); responseContent.append("o");
// example of reading chunk by chunk (minimize memory usage due to Factory) // example of reading chunk by chunk (minimize memory usage due to
// Factory)
readHttpDataChunkByChunk(e.getChannel()); readHttpDataChunkByChunk(e.getChannel());
// example of reading only if at the end // example of reading only if at the end
if (chunk.isLast()) { if (chunk.isLast()) {
@ -215,7 +217,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
/** /**
* Example of reading all InterfaceHttpData from finished transfer * Example of reading all InterfaceHttpData from finished transfer
* *
* @param channel * @param channel
*/ */
private void readHttpDataAllReceive(Channel channel) { private void readHttpDataAllReceive(Channel channel) {
@ -230,7 +232,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
Channels.close(channel); Channels.close(channel);
return; return;
} }
for (InterfaceHttpData data: datas) { for (InterfaceHttpData data : datas) {
writeHttpData(data); writeHttpData(data);
} }
responseContent.append("\r\n\r\nEND OF CONTENT AT FINAL END\r\n"); responseContent.append("\r\n\r\nEND OF CONTENT AT FINAL END\r\n");
@ -239,7 +241,7 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
/** /**
* Example of reading request by chunk and getting values from chunk to * Example of reading request by chunk and getting values from chunk to
* chunk * chunk
* *
* @param channel * @param channel
*/ */
private void readHttpDataChunkByChunk(Channel channel) { private void readHttpDataChunkByChunk(Channel channel) {
@ -267,25 +269,25 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
} catch (IOException e1) { } catch (IOException e1) {
// Error while reading data from File, only print name and error // Error while reading data from File, only print name and error
e1.printStackTrace(); e1.printStackTrace();
responseContent.append("\r\nBODY Attribute: " + responseContent.append("\r\nBODY Attribute: "
attribute.getHttpDataType().name() + ": " + + attribute.getHttpDataType().name() + ": "
attribute.getName() + " Error while reading value: " + + attribute.getName() + " Error while reading value: "
e1.getMessage() + "\r\n"); + e1.getMessage() + "\r\n");
return; return;
} }
if (value.length() > 100) { if (value.length() > 100) {
responseContent.append("\r\nBODY Attribute: " + responseContent.append("\r\nBODY Attribute: "
attribute.getHttpDataType().name() + ": " + + attribute.getHttpDataType().name() + ": "
attribute.getName() + " data too long\r\n"); + attribute.getName() + " data too long\r\n");
} else { } else {
responseContent.append("\r\nBODY Attribute: " + responseContent.append("\r\nBODY Attribute: "
attribute.getHttpDataType().name() + ": " + + attribute.getHttpDataType().name() + ": "
attribute.toString() + "\r\n"); + attribute.toString() + "\r\n");
} }
} else { } else {
responseContent.append("\r\nBODY FileUpload: " + responseContent.append("\r\nBODY FileUpload: "
data.getHttpDataType().name() + ": " + data.toString() + + data.getHttpDataType().name() + ": " + data.toString()
"\r\n"); + "\r\n");
if (data.getHttpDataType() == HttpDataType.FileUpload) { if (data.getHttpDataType() == HttpDataType.FileUpload) {
FileUpload fileUpload = (FileUpload) data; FileUpload fileUpload = (FileUpload) data;
if (fileUpload.isCompleted()) { if (fileUpload.isCompleted()) {
@ -303,8 +305,8 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
responseContent.append("\r\n"); responseContent.append("\r\n");
} else { } else {
responseContent responseContent
.append("\tFile too long to be printed out:" + .append("\tFile too long to be printed out:"
fileUpload.length() + "\r\n"); + fileUpload.length() + "\r\n");
} }
// fileUpload.isInMemory();// tells if the file is in Memory // fileUpload.isInMemory();// tells if the file is in Memory
// or on File // or on File
@ -322,15 +324,15 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
private void writeResponse(Channel channel) { private void writeResponse(Channel channel) {
// Convert the response content to a ChannelBuffer. // Convert the response content to a ChannelBuffer.
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent ChannelBuffer buf = ChannelBuffers.copiedBuffer(
.toString(), CharsetUtil.UTF_8); responseContent.toString(), CharsetUtil.UTF_8);
responseContent.setLength(0); responseContent.setLength(0);
// Decide whether to close the connection or not. // Decide whether to close the connection or not.
boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request
.getHeader(HttpHeaders.Names.CONNECTION)) || .getHeader(HttpHeaders.Names.CONNECTION))
request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0)
!HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request
.getHeader(HttpHeaders.Names.CONNECTION)); .getHeader(HttpHeaders.Names.CONNECTION));
// Build the response object. // Build the response object.
@ -343,8 +345,8 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
if (!close) { if (!close) {
// There's no need to add 'Content-Length' header // There's no need to add 'Content-Length' header
// if this is the last response. // if this is the last response.
response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
.valueOf(buf.readableBytes())); String.valueOf(buf.readableBytes()));
} }
Set<Cookie> cookies; Set<Cookie> cookies;
@ -358,11 +360,11 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
if (!cookies.isEmpty()) { if (!cookies.isEmpty()) {
// Reset the cookies if necessary. // Reset the cookies if necessary.
CookieEncoder cookieEncoder = new CookieEncoder(true); CookieEncoder cookieEncoder = new CookieEncoder(true);
for (Cookie cookie: cookies) { for (Cookie cookie : cookies) {
cookieEncoder.addCookie(cookie); cookieEncoder.addCookie(cookie);
} }
response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder response.addHeader(HttpHeaders.Names.SET_COOKIE,
.encode()); cookieEncoder.encode());
} }
// Write the response. // Write the response.
ChannelFuture future = channel.write(response); ChannelFuture future = channel.write(response);
@ -468,16 +470,16 @@ public class HttpUploadServerHandler extends SimpleChannelUpstreamHandler {
responseContent.append("</body>"); responseContent.append("</body>");
responseContent.append("</html>"); responseContent.append("</html>");
ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent ChannelBuffer buf = ChannelBuffers.copiedBuffer(
.toString(), CharsetUtil.UTF_8); responseContent.toString(), CharsetUtil.UTF_8);
// Build the response object. // Build the response object.
HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1,
HttpResponseStatus.OK); HttpResponseStatus.OK);
response.setContent(buf); response.setContent(buf);
response.setHeader(HttpHeaders.Names.CONTENT_TYPE, response.setHeader(HttpHeaders.Names.CONTENT_TYPE,
"text/html; charset=UTF-8"); "text/html; charset=UTF-8");
response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf response.setHeader(HttpHeaders.Names.CONTENT_LENGTH,
.readableBytes())); String.valueOf(buf.readableBytes()));
// Write the response. // Write the response.
e.getChannel().write(response); e.getChannel().write(response);
} }

View File

@ -30,15 +30,17 @@ public class HttpUploadServerPipelineFactory implements ChannelPipelineFactory {
ChannelPipeline pipeline = pipeline(); ChannelPipeline pipeline = pipeline();
// Uncomment the following line if you want HTTPS // Uncomment the following line if you want HTTPS
//SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); // SSLEngine engine =
//engine.setUseClientMode(false); // SecureChatSslContextFactory.getServerContext().createSSLEngine();
//pipeline.addLast("ssl", new SslHandler(engine)); // engine.setUseClientMode(false);
// pipeline.addLast("ssl", new SslHandler(engine));
pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("decoder", new HttpRequestDecoder());
pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("encoder", new HttpResponseEncoder());
// Remove the following line if you don't want automatic content compression. // Remove the following line if you don't want automatic content
// compression.
pipeline.addLast("deflater", new HttpContentCompressor()); pipeline.addLast("deflater", new HttpContentCompressor());
pipeline.addLast("handler", new HttpUploadServerHandler()); pipeline.addLast("handler", new HttpUploadServerHandler());

View File

@ -344,4 +344,4 @@ public abstract class AbstractDiskHttpData extends AbstractHttpData {
return file; return file;
} }
} }

View File

@ -94,4 +94,4 @@ public abstract class AbstractHttpData implements HttpData {
public long length() { public long length() {
return size; return size;
} }
} }

View File

@ -223,4 +223,4 @@ public abstract class AbstractMemoryHttpData extends AbstractHttpData {
public File getFile() throws IOException { public File getFile() throws IOException {
throw new IOException("Not represented by a file"); throw new IOException("Not represented by a file");
} }
} }

View File

@ -31,4 +31,4 @@ public interface Attribute extends HttpData {
* @param value * @param value
*/ */
void setValue(String value) throws IOException; void setValue(String value) throws IOException;
} }

View File

@ -21,8 +21,6 @@ import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentHashMap;
import org.jboss.netty.handler.codec.http.HttpRequest;
/** /**
* Default factory giving Attribute and FileUpload according to constructor * Default factory giving Attribute and FileUpload according to constructor
* *
@ -187,4 +185,4 @@ public class DefaultHttpDataFactory implements HttpDataFactory {
requestFileDeleteMap.remove(request); requestFileDeleteMap.remove(request);
} }
} }
} }

View File

@ -144,4 +144,4 @@ public class DiskAttribute extends AbstractDiskHttpData implements Attribute {
protected String getPrefix() { protected String getPrefix() {
return prefix; return prefix;
} }
} }

View File

@ -18,8 +18,6 @@ package org.jboss.netty.handler.codec.http;
import java.io.File; import java.io.File;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import org.jboss.netty.handler.codec.http.HttpHeaders;
/** /**
* Disk FileUpload implementation that stores file into real files * Disk FileUpload implementation that stores file into real files
*/ */
@ -159,4 +157,4 @@ public class DiskFileUpload extends AbstractDiskHttpData implements FileUpload {
protected String getPrefix() { protected String getPrefix() {
return prefix; return prefix;
} }
} }

View File

@ -178,4 +178,4 @@ final class HttpPostBodyUtil {
return result; return result;
} }
} }

View File

@ -33,4 +33,4 @@ public interface InterfaceHttpData extends Comparable<InterfaceHttpData> {
* @return The HttpDataType * @return The HttpDataType
*/ */
HttpDataType getHttpDataType(); HttpDataType getHttpDataType();
} }

View File

@ -105,4 +105,4 @@ public class MemoryAttribute extends AbstractMemoryHttpData implements Attribute
return getName() + "=" + getValue(); return getName() + "=" + getValue();
} }
} }

View File

@ -17,8 +17,6 @@ package org.jboss.netty.handler.codec.http;
import java.nio.charset.Charset; import java.nio.charset.Charset;
import org.jboss.netty.handler.codec.http.HttpHeaders;
/** /**
* Default FileUpload implementation that stores file into memory.<br><br> * Default FileUpload implementation that stores file into memory.<br><br>
* *
@ -125,4 +123,4 @@ public class MemoryFileUpload extends AbstractMemoryHttpData implements FileUplo
"Completed: " + isCompleted() + "Completed: " + isCompleted() +
"\r\nIsInMemory: " + isInMemory(); "\r\nIsInMemory: " + isInMemory();
} }
} }

View File

@ -199,4 +199,4 @@ public class MixedAttribute implements Attribute {
return attribute.getFile(); return attribute.getFile();
} }
} }

View File

@ -224,4 +224,4 @@ public class MixedFileUpload implements FileUpload {
return fileUpload.getFile(); return fileUpload.getFile();
} }
} }