code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.contrib.compress; import java.io.IOException; import org.apache.http.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.protocol.HttpContext; /** * Client-side interceptor to handle Gzip-compressed responses. * * * @since 4.0 */ public class ResponseGzipUncompress implements HttpResponseInterceptor { private static final String GZIP_CODEC = "gzip"; public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpEntity entity = response.getEntity(); if (entity != null) { Header ceheader = entity.getContentEncoding(); if (ceheader != null) { HeaderElement[] codecs = ceheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase(GZIP_CODEC)) { response.setEntity(new GzipDecompressingEntity(response.getEntity())); return; } } } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.contrib.compress; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestInterceptor; import org.apache.http.protocol.HttpContext; /** * Client-side interceptor to indicate support for Gzip content compression. * * * @since 4.0 */ public class RequestAcceptEncoding implements HttpRequestInterceptor { private static final String ACCEPT_ENCODING = "Accept-Encoding"; private static final String GZIP_CODEC = "gzip"; public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (!request.containsHeader(ACCEPT_ENCODING)) { request.addHeader(ACCEPT_ENCODING, GZIP_CODEC); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; import java.net.URL; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.http.benchmark.httpcore.HttpCoreNIOServer; import org.apache.http.benchmark.httpcore.HttpCoreServer; import org.apache.http.benchmark.jetty.JettyNIOServer; import org.apache.http.benchmark.jetty.JettyServer; import org.apache.http.benchmark.CommandLineUtils; import org.apache.http.benchmark.Config; import org.apache.http.benchmark.HttpBenchmark; public class Benchmark { private static final int PORT = 8989; public static void main(String[] args) throws Exception { Config config = new Config(); if (args.length > 0) { Options options = CommandLineUtils.getOptions(); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (cmd.hasOption('h')) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("Benchmark [options]", options); System.exit(1); } CommandLineUtils.parseCommandLine(cmd, config); } else { config.setKeepAlive(true); config.setRequests(20000); config.setThreads(25); } URL target = new URL("http", "localhost", PORT, "/rnd?c=2048"); config.setUrl(target); Benchmark benchmark = new Benchmark(); benchmark.run(new JettyServer(PORT), config); benchmark.run(new HttpCoreServer(PORT), config); benchmark.run(new JettyNIOServer(PORT), config); benchmark.run(new HttpCoreNIOServer(PORT), config); } public Benchmark() { super(); } public void run(final HttpServer server, final Config config) throws Exception { server.start(); try { System.out.println("---------------------------------------------------------------"); System.out.println(server.getName() + "; version: " + server.getVersion()); System.out.println("---------------------------------------------------------------"); HttpBenchmark ab = new HttpBenchmark(config); ab.execute(); System.out.println("---------------------------------------------------------------"); } finally { server.shutdown(); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.jetty; import java.io.IOException; import org.apache.http.benchmark.HttpServer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.nio.SelectChannelConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; public class JettyNIOServer implements HttpServer { private final Server server; public JettyNIOServer(int port) throws IOException { super(); if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } SelectChannelConnector connector = new SelectChannelConnector(); connector.setPort(port); connector.setRequestBufferSize(12 * 1024); connector.setResponseBufferSize(12 * 1024); connector.setAcceptors(2); QueuedThreadPool threadpool = new QueuedThreadPool(); threadpool.setMinThreads(25); threadpool.setMaxThreads(200); this.server = new Server(); this.server.addConnector(connector); this.server.setThreadPool(threadpool); this.server.setHandler(new RandomDataHandler()); } public String getName() { return "Jetty (NIO)"; } public String getVersion() { return Server.getVersion(); } public void start() throws Exception { this.server.start(); } public void shutdown() { try { this.server.stop(); } catch (Exception ex) { } try { this.server.join(); } catch (InterruptedException ex) { } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final JettyNIOServer server = new JettyNIOServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(); } }); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.jetty; import java.io.IOException; import org.apache.http.benchmark.HttpServer; import org.eclipse.jetty.server.Server; import org.eclipse.jetty.server.bio.SocketConnector; import org.eclipse.jetty.util.thread.QueuedThreadPool; public class JettyServer implements HttpServer { private final Server server; public JettyServer(int port) throws IOException { super(); if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } SocketConnector connector = new SocketConnector(); connector.setPort(port); connector.setRequestBufferSize(12 * 1024); connector.setResponseBufferSize(12 * 1024); connector.setAcceptors(2); QueuedThreadPool threadpool = new QueuedThreadPool(); threadpool.setMinThreads(25); threadpool.setMaxThreads(200); this.server = new Server(); this.server.addConnector(connector); this.server.setThreadPool(threadpool); this.server.setHandler(new RandomDataHandler()); } public String getName() { return "Jetty (blocking I/O)"; } public String getVersion() { return Server.getVersion(); } public void start() throws Exception { this.server.start(); } public void shutdown() { try { this.server.stop(); } catch (Exception ex) { } try { this.server.join(); } catch (InterruptedException ex) { } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final JettyServer server = new JettyServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(); } }); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.jetty; import java.io.IOException; import java.io.OutputStream; import java.io.Writer; import javax.servlet.ServletException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.eclipse.jetty.http.HttpStatus; import org.eclipse.jetty.server.Request; import org.eclipse.jetty.server.handler.AbstractHandler; class RandomDataHandler extends AbstractHandler { public RandomDataHandler() { super(); } public void handle( final String target, final Request baseRequest, final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { if (target.equals("/rnd")) { rnd(request, response); } else { response.setStatus(HttpStatus.NOT_FOUND_404); Writer writer = response.getWriter(); writer.write("Target not found: " + target); writer.flush(); } } private void rnd( final HttpServletRequest request, final HttpServletResponse response) throws IOException, ServletException { int count = 100; String s = request.getParameter("c"); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatus(500); Writer writer = response.getWriter(); writer.write("Invalid query format: " + request.getQueryString()); writer.flush(); return; } response.setStatus(200); response.setContentLength(count); OutputStream outstream = response.getOutputStream(); byte[] tmp = new byte[1024]; int r = Math.abs(tmp.hashCode()); int remaining = count; while (remaining > 0) { int chunk = Math.min(tmp.length, remaining); for (int i = 0; i < chunk; i++) { tmp[i] = (byte) ((r + i) % 96 + 32); } outstream.write(tmp, 0, chunk); remaining -= chunk; } outstream.flush(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import java.io.InterruptedIOException; import java.net.ServerSocket; import java.net.Socket; import org.apache.http.impl.DefaultHttpServerConnection; import org.apache.http.protocol.HttpService; class HttpListener extends Thread { private final ServerSocket serversocket; private final HttpService httpservice; private final HttpWorkerCallback workercallback; private volatile boolean shutdown; private volatile Exception exception; public HttpListener( final ServerSocket serversocket, final HttpService httpservice, final HttpWorkerCallback workercallback) { super(); this.serversocket = serversocket; this.httpservice = httpservice; this.workercallback = workercallback; } public boolean isShutdown() { return this.shutdown; } public Exception getException() { return this.exception; } @Override public void run() { while (!Thread.interrupted() && !this.shutdown) { try { // Set up HTTP connection Socket socket = this.serversocket.accept(); DefaultHttpServerConnection conn = new DefaultHttpServerConnection(); conn.bind(socket, this.httpservice.getParams()); // Start worker thread HttpWorker t = new HttpWorker(this.httpservice, conn, this.workercallback); t.start(); } catch (InterruptedIOException ex) { terminate(); } catch (IOException ex) { this.exception = ex; terminate(); } } } public void terminate() { if (this.shutdown) { return; } this.shutdown = true; try { this.serversocket.close(); } catch (IOException ex) { if (this.exception != null) { this.exception = ex; } } } public void awaitTermination(long millis) throws InterruptedException { this.join(millis); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import org.apache.http.HttpServerConnection; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpService; class HttpWorker extends Thread { private final HttpService httpservice; private final HttpServerConnection conn; private final HttpWorkerCallback workercallback; private volatile boolean shutdown; private volatile Exception exception; public HttpWorker( final HttpService httpservice, final HttpServerConnection conn, final HttpWorkerCallback workercallback) { super(); this.httpservice = httpservice; this.conn = conn; this.workercallback = workercallback; } public boolean isShutdown() { return this.shutdown; } public Exception getException() { return this.exception; } @Override public void run() { this.workercallback.started(this); try { HttpContext context = new BasicHttpContext(); while (!Thread.interrupted() && !this.shutdown) { this.httpservice.handleRequest(this.conn, context); } } catch (Exception ex) { this.exception = ex; } finally { terminate(); this.workercallback.shutdown(this); } } public void terminate() { if (this.shutdown) { return; } this.shutdown = true; try { this.conn.shutdown(); } catch (IOException ex) { if (this.exception != null) { this.exception = ex; } } } public void awaitTermination(long millis) throws InterruptedException { this.join(millis); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; interface HttpWorkerCallback { void started(HttpWorker worker); void shutdown(HttpWorker worker); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import java.net.ServerSocket; import java.util.Queue; import java.util.concurrent.ConcurrentLinkedQueue; import org.apache.http.HttpResponseInterceptor; import org.apache.http.benchmark.HttpServer; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.HttpRequestHandlerRegistry; import org.apache.http.protocol.HttpService; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.util.VersionInfo; public class HttpCoreServer implements HttpServer { private final Queue<HttpWorker> workers; private final HttpListener listener; public HttpCoreServer(int port) throws IOException { super(); if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 12 * 1024) .setIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpCore-Test/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry(); reqistry.register("/rnd", new RandomDataHandler()); HttpService httpservice = new HttpService( httpproc, new DefaultConnectionReuseStrategy(), new DefaultHttpResponseFactory(), reqistry, params); this.workers = new ConcurrentLinkedQueue<HttpWorker>(); this.listener = new HttpListener( new ServerSocket(port), httpservice, new StdHttpWorkerCallback(this.workers)); } public String getName() { return "HttpCore (blocking I/O)"; } public String getVersion() { VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http", Thread.currentThread().getContextClassLoader()); return vinfo.getRelease(); } public void start() { this.listener.start(); } public void shutdown() { this.listener.terminate(); try { this.listener.awaitTermination(1000); } catch (InterruptedException ex) { } Exception ex = this.listener.getException(); if (ex != null) { System.out.println("Error: " + ex.getMessage()); } while (!this.workers.isEmpty()) { HttpWorker worker = this.workers.remove(); worker.terminate(); try { worker.awaitTermination(1000); } catch (InterruptedException iex) { } ex = worker.getException(); if (ex != null) { System.out.println("Error: " + ex.getMessage()); } } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final HttpCoreServer server = new HttpCoreServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(); } }); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.http.HttpResponseInterceptor; import org.apache.http.benchmark.HttpServer; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpResponseFactory; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor; import org.apache.http.nio.protocol.AsyncNHttpServiceHandler; import org.apache.http.nio.protocol.NHttpRequestHandlerRegistry; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListeningIOReactor; import org.apache.http.params.CoreConnectionPNames; import org.apache.http.params.CoreProtocolPNames; import org.apache.http.params.HttpParams; import org.apache.http.params.SyncBasicHttpParams; import org.apache.http.protocol.HttpProcessor; import org.apache.http.protocol.ImmutableHttpProcessor; import org.apache.http.protocol.ResponseConnControl; import org.apache.http.protocol.ResponseContent; import org.apache.http.protocol.ResponseDate; import org.apache.http.protocol.ResponseServer; import org.apache.http.util.VersionInfo; public class HttpCoreNIOServer implements HttpServer { private final int port; private final NHttpListener listener; public HttpCoreNIOServer(int port) throws IOException { if (port <= 0) { throw new IllegalArgumentException("Server port may not be negative or null"); } this.port = port; HttpParams params = new SyncBasicHttpParams(); params .setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 10000) .setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 12 * 1024) .setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true) .setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpCore-NIO-Test/1.1"); HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] { new ResponseDate(), new ResponseServer(), new ResponseContent(), new ResponseConnControl() }); AsyncNHttpServiceHandler handler = new AsyncNHttpServiceHandler( httpproc, new DefaultHttpResponseFactory(), new DefaultConnectionReuseStrategy(), params); NHttpRequestHandlerRegistry reqistry = new NHttpRequestHandlerRegistry(); reqistry.register("/rnd", new NRandomDataHandler()); handler.setHandlerResolver(reqistry); ListeningIOReactor ioreactor = new DefaultListeningIOReactor(2, params); IOEventDispatch ioEventDispatch = new DefaultServerIOEventDispatch(handler, params); this.listener = new NHttpListener(ioreactor, ioEventDispatch); } public String getName() { return "HttpCore (NIO)"; } public String getVersion() { VersionInfo vinfo = VersionInfo.loadVersionInfo("org.apache.http", Thread.currentThread().getContextClassLoader()); return vinfo.getRelease(); } public void start() throws Exception { this.listener.start(); this.listener.listen(new InetSocketAddress(this.port)); } public void shutdown() { this.listener.terminate(); try { this.listener.awaitTermination(1000); } catch (InterruptedException ex) { } Exception ex = this.listener.getException(); if (ex != null) { System.out.println("Error: " + ex.getMessage()); } } public static void main(String[] args) throws Exception { if (args.length != 1) { System.out.println("Usage: <port>"); System.exit(1); } int port = Integer.parseInt(args[0]); final HttpCoreNIOServer server = new HttpCoreNIOServer(port); System.out.println("Listening on port: " + port); server.start(); Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { server.shutdown(); } }); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.HttpRequestHandler; import org.apache.http.util.EntityUtils; class RandomDataHandler implements HttpRequestHandler { public RandomDataHandler() { super(); } public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); EntityUtils.consume(entity); } String target = request.getRequestLine().getUri(); int count = 100; int idx = target.indexOf('?'); if (idx != -1) { String s = target.substring(idx + 1); if (s.startsWith("c=")) { s = s.substring(2); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setEntity(new StringEntity("Invalid query format: " + s, "text/plain", "ASCII")); return; } } } response.setStatusCode(HttpStatus.SC_OK); RandomEntity body = new RandomEntity(count); response.setEntity(body); } static class RandomEntity extends AbstractHttpEntity { private int count; private final byte[] buf; public RandomEntity(int count) { super(); this.count = count; this.buf = new byte[1024]; setContentType("text/plain"); } public InputStream getContent() throws IOException, IllegalStateException { throw new IllegalStateException("Method not supported"); } public long getContentLength() { return this.count; } public boolean isRepeatable() { return true; } public boolean isStreaming() { return false; } public void writeTo(final OutputStream outstream) throws IOException { int r = Math.abs(this.buf.hashCode()); int remaining = this.count; while (remaining > 0) { int chunk = Math.min(this.buf.length, remaining); for (int i = 0; i < chunk; i++) { this.buf[i] = (byte) ((r + i) % 96 + 32); } outstream.write(this.buf, 0, chunk); remaining -= chunk; } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import java.net.SocketTimeoutException; import java.util.Queue; import org.apache.http.ConnectionClosedException; import org.apache.http.HttpException; class StdHttpWorkerCallback implements HttpWorkerCallback { private final Queue<HttpWorker> queue; public StdHttpWorkerCallback(final Queue<HttpWorker> queue) { super(); this.queue = queue; } public void started(final HttpWorker worker) { this.queue.add(worker); } public void shutdown(final HttpWorker worker) { this.queue.remove(worker); Exception ex = worker.getException(); if (ex != null) { if (ex instanceof HttpException) { System.err.println("HTTP protocol error: " + ex.getMessage()); } else if (ex instanceof SocketTimeoutException) { // ignore } else if (ex instanceof ConnectionClosedException) { // ignore } else if (ex instanceof IOException) { System.err.println("I/O error: " + ex); } else { System.err.println("Unexpected error: " + ex.getMessage()); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.http.nio.reactor.IOEventDispatch; import org.apache.http.nio.reactor.ListenerEndpoint; import org.apache.http.nio.reactor.ListeningIOReactor; public class NHttpListener extends Thread { private final ListeningIOReactor ioreactor; private final IOEventDispatch ioEventDispatch; private volatile Exception exception; public NHttpListener( final ListeningIOReactor ioreactor, final IOEventDispatch ioEventDispatch) throws IOException { super(); this.ioreactor = ioreactor; this.ioEventDispatch = ioEventDispatch; } @Override public void run() { try { this.ioreactor.execute(this.ioEventDispatch); } catch (Exception ex) { this.exception = ex; } } public void listen(final InetSocketAddress address) throws InterruptedException { ListenerEndpoint endpoint = this.ioreactor.listen(address); endpoint.waitFor(); } public void terminate() { try { this.ioreactor.shutdown(); } catch (IOException ex) { } } public Exception getException() { return this.exception; } public void awaitTermination(long millis) throws InterruptedException { this.join(millis); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark.httpcore; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.util.Locale; import org.apache.http.HttpEntity; import org.apache.http.HttpEntityEnclosingRequest; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.MethodNotSupportedException; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.entity.StringEntity; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.entity.BufferingNHttpEntity; import org.apache.http.nio.entity.ConsumingNHttpEntity; import org.apache.http.nio.entity.ProducingNHttpEntity; import org.apache.http.nio.protocol.NHttpRequestHandler; import org.apache.http.nio.protocol.NHttpResponseTrigger; import org.apache.http.nio.util.HeapByteBufferAllocator; import org.apache.http.protocol.HttpContext; import org.apache.http.util.EntityUtils; class NRandomDataHandler implements NHttpRequestHandler { public NRandomDataHandler() { super(); } public ConsumingNHttpEntity entityRequest( final HttpEntityEnclosingRequest request, final HttpContext context) throws HttpException, IOException { // Use buffering entity for simplicity return new BufferingNHttpEntity(request.getEntity(), new HeapByteBufferAllocator()); } public void handle( final HttpRequest request, final HttpResponse response, final NHttpResponseTrigger trigger, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); EntityUtils.consume(entity); } String target = request.getRequestLine().getUri(); int count = 100; int idx = target.indexOf('?'); if (idx != -1) { String s = target.substring(idx + 1); if (s.startsWith("c=")) { s = s.substring(2); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setEntity(new StringEntity("Invalid query format: " + s, "text/plain", "ASCII")); return; } } } response.setStatusCode(HttpStatus.SC_OK); RandomEntity body = new RandomEntity(count); response.setEntity(body); trigger.submitResponse(response); } public void handle( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH); if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) { throw new MethodNotSupportedException(method + " method not supported"); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity(); EntityUtils.consume(entity); } String target = request.getRequestLine().getUri(); int count = 100; int idx = target.indexOf('?'); if (idx != -1) { String s = target.substring(idx + 1); if (s.startsWith("c=")) { s = s.substring(2); try { count = Integer.parseInt(s); } catch (NumberFormatException ex) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); response.setEntity(new StringEntity("Invalid query format: " + s, "text/plain", "ASCII")); return; } } } response.setStatusCode(HttpStatus.SC_OK); RandomEntity body = new RandomEntity(count); response.setEntity(body); } static class RandomEntity extends AbstractHttpEntity implements ProducingNHttpEntity { private final int count; private final ByteBuffer buf; private int remaining; public RandomEntity(int count) { super(); this.count = count; this.remaining = count; this.buf = ByteBuffer.allocate(1024); setContentType("text/plain"); } public InputStream getContent() throws IOException, IllegalStateException { throw new IllegalStateException("Method not supported"); } public long getContentLength() { return this.count; } public boolean isRepeatable() { return true; } public boolean isStreaming() { return false; } public void writeTo(final OutputStream outstream) throws IOException { throw new IllegalStateException("Method not supported"); } public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { int r = Math.abs(this.buf.hashCode()); int chunk = Math.min(this.buf.remaining(), this.remaining); if (chunk > 0) { for (int i = 0; i < chunk; i++) { byte b = (byte) ((r + i) % 96 + 32); this.buf.put(b); } } this.buf.flip(); int bytesWritten = encoder.write(this.buf); this.remaining -= bytesWritten; if (this.remaining == 0 && this.buf.remaining() == 0) { encoder.complete(); } this.buf.compact(); } public void finish() throws IOException { this.remaining = this.count; } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; public interface HttpServer { String getName(); String getVersion(); void start() throws Exception; void shutdown(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; import java.io.File; import java.net.URL; public class Config { private URL url; private int requests; private int threads; private boolean keepAlive; private int verbosity; private boolean headInsteadOfGet; private boolean useHttp1_0; private String contentType; private String[] headers; private int socketTimeout; private String method = "GET"; private boolean useChunking; private boolean useExpectContinue; private boolean useAcceptGZip; private File payloadFile = null; private String payloadText = null; private String soapAction = null; private boolean disableSSLVerification = true; private String trustStorePath = null; private String identityStorePath = null; private String trustStorePassword = null; private String identityStorePassword = null; public Config() { super(); this.url = null; this.requests = 1; this.threads = 1; this.keepAlive = false; this.verbosity = 0; this.headInsteadOfGet = false; this.useHttp1_0 = false; this.payloadFile = null; this.payloadText = null; this.contentType = null; this.headers = null; this.socketTimeout = 60000; } public URL getUrl() { return url; } public void setUrl(URL url) { this.url = url; } public int getRequests() { return requests; } public void setRequests(int requests) { this.requests = requests; } public int getThreads() { return threads; } public void setThreads(int threads) { this.threads = threads; } public boolean isKeepAlive() { return keepAlive; } public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; } public int getVerbosity() { return verbosity; } public void setVerbosity(int verbosity) { this.verbosity = verbosity; } public boolean isHeadInsteadOfGet() { return headInsteadOfGet; } public void setHeadInsteadOfGet(boolean headInsteadOfGet) { this.headInsteadOfGet = headInsteadOfGet; this.method = "HEAD"; } public boolean isUseHttp1_0() { return useHttp1_0; } public void setUseHttp1_0(boolean useHttp1_0) { this.useHttp1_0 = useHttp1_0; } public File getPayloadFile() { return payloadFile; } public void setPayloadFile(File payloadFile) { this.payloadFile = payloadFile; } public String getContentType() { return contentType; } public void setContentType(String contentType) { this.contentType = contentType; } public String[] getHeaders() { return headers; } public void setHeaders(String[] headers) { this.headers = headers; } public int getSocketTimeout() { return socketTimeout; } public void setSocketTimeout(int socketTimeout) { this.socketTimeout = socketTimeout; } public void setMethod(String method) { this.method = method; } public void setUseChunking(boolean useChunking) { this.useChunking = useChunking; } public void setUseExpectContinue(boolean useExpectContinue) { this.useExpectContinue = useExpectContinue; } public void setUseAcceptGZip(boolean useAcceptGZip) { this.useAcceptGZip = useAcceptGZip; } public String getMethod() { return method; } public boolean isUseChunking() { return useChunking; } public boolean isUseExpectContinue() { return useExpectContinue; } public boolean isUseAcceptGZip() { return useAcceptGZip; } public String getPayloadText() { return payloadText; } public String getSoapAction() { return soapAction; } public boolean isDisableSSLVerification() { return disableSSLVerification; } public String getTrustStorePath() { return trustStorePath; } public String getIdentityStorePath() { return identityStorePath; } public String getTrustStorePassword() { return trustStorePassword; } public String getIdentityStorePassword() { return identityStorePassword; } public void setPayloadText(String payloadText) { this.payloadText = payloadText; } public void setSoapAction(String soapAction) { this.soapAction = soapAction; } public void setDisableSSLVerification(boolean disableSSLVerification) { this.disableSSLVerification = disableSSLVerification; } public void setTrustStorePath(String trustStorePath) { this.trustStorePath = trustStorePath; } public void setIdentityStorePath(String identityStorePath) { this.identityStorePath = identityStorePath; } public void setTrustStorePassword(String trustStorePassword) { this.trustStorePassword = trustStorePassword; } public void setIdentityStorePassword(String identityStorePassword) { this.identityStorePassword = identityStorePassword; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; /** * Helper to gather statistics for an {@link HttpBenchmark HttpBenchmark}. * * * @since 4.0 */ public class Stats { private long startTime = -1; // nano seconds - does not represent an actual time private long finishTime = -1; // nano seconds - does not represent an actual time private int successCount = 0; private int failureCount = 0; private int writeErrors = 0; private int keepAliveCount = 0; private String serverName = null; private long totalBytesRecv = 0; private long contentLength = -1; public Stats() { super(); } public void start() { this.startTime = System.nanoTime(); } public void finish() { this.finishTime = System.nanoTime(); } public long getFinishTime() { return this.finishTime; } public long getStartTime() { return this.startTime; } /** * Total execution time measured in nano seconds * * @return duration in nanoseconds */ public long getDuration() { // we are using System.nanoTime() and the return values could be negative // but its only the difference that we are concerned about return this.finishTime - this.startTime; } public void incSuccessCount() { this.successCount++; } public int getSuccessCount() { return this.successCount; } public void incFailureCount() { this.failureCount++; } public int getFailureCount() { return this.failureCount; } public void incWriteErrors() { this.writeErrors++; } public int getWriteErrors() { return this.writeErrors; } public void incKeepAliveCount() { this.keepAliveCount++; } public int getKeepAliveCount() { return this.keepAliveCount; } public long getTotalBytesRecv() { return this.totalBytesRecv; } public void incTotalBytesRecv(int n) { this.totalBytesRecv += n; } public long getContentLength() { return this.contentLength; } public void setContentLength(long contentLength) { this.contentLength = contentLength; } public String getServerName() { return this.serverName; } public void setServerName(final String serverName) { this.serverName = serverName; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; import org.apache.http.HttpHost; import java.text.NumberFormat; public class ResultProcessor { static NumberFormat nf2 = NumberFormat.getInstance(); static NumberFormat nf3 = NumberFormat.getInstance(); static NumberFormat nf6 = NumberFormat.getInstance(); static { nf2.setMaximumFractionDigits(2); nf2.setMinimumFractionDigits(2); nf3.setMaximumFractionDigits(3); nf3.setMinimumFractionDigits(3); nf6.setMaximumFractionDigits(6); nf6.setMinimumFractionDigits(6); } static String printResults(BenchmarkWorker[] workers, HttpHost host, String uri, long contentLength) { double totalTimeNano = 0; long successCount = 0; long failureCount = 0; long writeErrors = 0; long keepAliveCount = 0; long totalBytesRcvd = 0; Stats stats = workers[0].getStats(); for (int i = 0; i < workers.length; i++) { Stats s = workers[i].getStats(); totalTimeNano += s.getDuration(); successCount += s.getSuccessCount(); failureCount += s.getFailureCount(); writeErrors += s.getWriteErrors(); keepAliveCount += s.getKeepAliveCount(); totalBytesRcvd += s.getTotalBytesRecv(); } int threads = workers.length; double totalTimeMs = (totalTimeNano / threads) / 1000000; // convert nano secs to milli secs double timePerReqMs = totalTimeMs / successCount; double totalTimeSec = totalTimeMs / 1000; double reqsPerSec = successCount / totalTimeSec; long totalBytesSent = contentLength * successCount; long totalBytes = totalBytesRcvd + (totalBytesSent > 0 ? totalBytesSent : 0); StringBuilder sb = new StringBuilder(1024); printAndAppend(sb,"\nServer Software:\t\t" + stats.getServerName()); printAndAppend(sb, "Server Hostname:\t\t" + host.getHostName()); printAndAppend(sb, "Server Port:\t\t\t" + (host.getPort() > 0 ? host.getPort() : uri.startsWith("https") ? "443" : "80") + "\n"); printAndAppend(sb, "Document Path:\t\t\t" + uri); printAndAppend(sb, "Document Length:\t\t" + stats.getContentLength() + " bytes\n"); printAndAppend(sb, "Concurrency Level:\t\t" + workers.length); printAndAppend(sb, "Time taken for tests:\t\t" + nf6.format(totalTimeSec) + " seconds"); printAndAppend(sb, "Complete requests:\t\t" + successCount); printAndAppend(sb, "Failed requests:\t\t" + failureCount); printAndAppend(sb, "Write errors:\t\t\t" + writeErrors); printAndAppend(sb, "Kept alive:\t\t\t" + keepAliveCount); printAndAppend(sb, "Total transferred:\t\t" + totalBytes + " bytes"); printAndAppend(sb, "Requests per second:\t\t" + nf2.format(reqsPerSec) + " [#/sec] (mean)"); printAndAppend(sb, "Time per request:\t\t" + nf3.format(timePerReqMs * workers.length) + " [ms] (mean)"); printAndAppend(sb, "Time per request:\t\t" + nf3.format(timePerReqMs) + " [ms] (mean, across all concurrent requests)"); printAndAppend(sb, "Transfer rate:\t\t\t" + nf2.format(totalBytesRcvd/1000/totalTimeSec) + " [Kbytes/sec] received"); printAndAppend(sb, "\t\t\t\t" + (totalBytesSent > 0 ? nf2.format(totalBytesSent/1000/totalTimeSec) : -1) + " kb/s sent"); printAndAppend(sb, "\t\t\t\t" + nf2.format(totalBytes/1000/totalTimeSec) + " kb/s total"); return sb.toString(); } private static void printAndAppend(StringBuilder sb, String s) { System.out.println(s); sb.append(s).append("\r\n"); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; import java.io.UnsupportedEncodingException; import java.net.URL; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.CommandLineParser; import org.apache.commons.cli.Options; import org.apache.commons.cli.PosixParser; import org.apache.http.Header; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpVersion; import org.apache.http.entity.FileEntity; import org.apache.http.message.BasicHttpEntityEnclosingRequest; import org.apache.http.message.BasicHttpRequest; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.params.HttpProtocolParams; import org.apache.http.protocol.HTTP; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import org.apache.http.HttpEntity; import org.apache.http.entity.StringEntity; /** * Main program of the HTTP benchmark. * * * @since 4.0 */ public class HttpBenchmark { private final Config config; private HttpParams params = null; private HttpRequest[] request = null; private HttpHost host = null; private long contentLength = -1; public static void main(String[] args) throws Exception { Options options = CommandLineUtils.getOptions(); CommandLineParser parser = new PosixParser(); CommandLine cmd = parser.parse(options, args); if (args.length == 0 || cmd.hasOption('h') || cmd.getArgs().length != 1) { CommandLineUtils.showUsage(options); System.exit(1); } Config config = new Config(); CommandLineUtils.parseCommandLine(cmd, config); if (config.getUrl() == null) { CommandLineUtils.showUsage(options); System.exit(1); } HttpBenchmark httpBenchmark = new HttpBenchmark(config); httpBenchmark.execute(); } public HttpBenchmark(final Config config) { super(); this.config = config != null ? config : new Config(); } private void prepare() throws UnsupportedEncodingException { // prepare http params params = getHttpParams(config.getSocketTimeout(), config.isUseHttp1_0(), config.isUseExpectContinue()); URL url = config.getUrl(); host = new HttpHost(url.getHost(), url.getPort(), url.getProtocol()); HttpEntity entity = null; // Prepare requests for each thread if (config.getPayloadFile() != null) { entity = new FileEntity(config.getPayloadFile(), config.getContentType()); ((FileEntity) entity).setChunked(config.isUseChunking()); contentLength = config.getPayloadFile().length(); } else if (config.getPayloadText() != null) { entity = new StringEntity(config.getPayloadText(), config.getContentType(), "UTF-8"); ((StringEntity) entity).setChunked(config.isUseChunking()); contentLength = config.getPayloadText().getBytes().length; } request = new HttpRequest[config.getThreads()]; for (int i = 0; i < request.length; i++) { if ("POST".equals(config.getMethod())) { BasicHttpEntityEnclosingRequest httppost = new BasicHttpEntityEnclosingRequest("POST", url.getPath()); httppost.setEntity(entity); request[i] = httppost; } else if ("PUT".equals(config.getMethod())) { BasicHttpEntityEnclosingRequest httpput = new BasicHttpEntityEnclosingRequest("PUT", url.getPath()); httpput.setEntity(entity); request[i] = httpput; } else { String path = url.getPath(); if (url.getQuery() != null && url.getQuery().length() > 0) { path += "?" + url.getQuery(); } else if (path.trim().length() == 0) { path = "/"; } request[i] = new BasicHttpRequest(config.getMethod(), path); } } if (!config.isKeepAlive()) { for (int i = 0; i < request.length; i++) { request[i].addHeader(new DefaultHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE)); } } String[] headers = config.getHeaders(); if (headers != null) { for (int i = 0; i < headers.length; i++) { String s = headers[i]; int pos = s.indexOf(':'); if (pos != -1) { Header header = new DefaultHeader(s.substring(0, pos).trim(), s.substring(pos + 1)); for (int j = 0; j < request.length; j++) { request[j].addHeader(header); } } } } if (config.isUseAcceptGZip()) { for (int i = 0; i < request.length; i++) { request[i].addHeader(new DefaultHeader("Accept-Encoding", "gzip")); } } if (config.getSoapAction() != null && config.getSoapAction().length() > 0) { for (int i = 0; i < request.length; i++) { request[i].addHeader(new DefaultHeader("SOAPAction", config.getSoapAction())); } } } public String execute() throws Exception { prepare(); ThreadPoolExecutor workerPool = new ThreadPoolExecutor( config.getThreads(), config.getThreads(), 5, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(), new ThreadFactory() { public Thread newThread(Runnable r) { return new Thread(r, "ClientPool"); } }); workerPool.prestartAllCoreThreads(); BenchmarkWorker[] workers = new BenchmarkWorker[config.getThreads()]; for (int i = 0; i < workers.length; i++) { workers[i] = new BenchmarkWorker( params, config.getVerbosity(), request[i], host, config.getRequests(), config.isKeepAlive(), config.isDisableSSLVerification(), config.getTrustStorePath(), config.getTrustStorePassword(), config.getIdentityStorePath(), config.getIdentityStorePassword()); workerPool.execute(workers[i]); } while (workerPool.getCompletedTaskCount() < config.getThreads()) { Thread.yield(); try { Thread.sleep(1000); } catch (InterruptedException ignore) { } } workerPool.shutdown(); return ResultProcessor.printResults(workers, host, config.getUrl().toString(), contentLength); } private HttpParams getHttpParams( int socketTimeout, boolean useHttp1_0, boolean useExpectContinue) { HttpParams params = new BasicHttpParams(); params.setParameter(HttpProtocolParams.PROTOCOL_VERSION, useHttp1_0 ? HttpVersion.HTTP_1_0 : HttpVersion.HTTP_1_1) .setParameter(HttpProtocolParams.USER_AGENT, "HttpCore-AB/1.1") .setBooleanParameter(HttpProtocolParams.USE_EXPECT_CONTINUE, useExpectContinue) .setBooleanParameter(HttpConnectionParams.STALE_CONNECTION_CHECK, false) .setIntParameter(HttpConnectionParams.SO_TIMEOUT, socketTimeout); return params; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; import org.apache.commons.cli.CommandLine; import org.apache.commons.cli.HelpFormatter; import org.apache.commons.cli.Option; import org.apache.commons.cli.Options; import java.io.File; import java.net.MalformedURLException; import java.net.URL; public class CommandLineUtils { public static Options getOptions() { Option iopt = new Option("i", false, "Do HEAD requests instead of GET (deprecated)"); iopt.setRequired(false); Option oopt = new Option("o", false, "Use HTTP/S 1.0 instead of 1.1 (default)"); oopt.setRequired(false); Option kopt = new Option("k", false, "Enable the HTTP KeepAlive feature, " + "i.e., perform multiple requests within one HTTP session. " + "Default is no KeepAlive"); kopt.setRequired(false); Option uopt = new Option("u", false, "Chunk entity. Default is false"); uopt.setRequired(false); Option xopt = new Option("x", false, "Use Expect-Continue. Default is false"); xopt.setRequired(false); Option gopt = new Option("g", false, "Accept GZip. Default is false"); gopt.setRequired(false); Option nopt = new Option("n", true, "Number of requests to perform for the " + "benchmarking session. The default is to just perform a single " + "request which usually leads to non-representative benchmarking " + "results"); nopt.setRequired(false); nopt.setArgName("requests"); Option copt = new Option("c", true, "Concurrency while performing the " + "benchmarking session. The default is to just use a single thread/client"); copt.setRequired(false); copt.setArgName("concurrency"); Option popt = new Option("p", true, "File containing data to POST or PUT"); popt.setRequired(false); popt.setArgName("Payload file"); Option mopt = new Option("m", true, "HTTP Method. Default is POST. " + "Possible options are GET, POST, PUT, DELETE, HEAD, OPTIONS, TRACE"); mopt.setRequired(false); mopt.setArgName("HTTP method"); Option Topt = new Option("T", true, "Content-type header to use for POST/PUT data"); Topt.setRequired(false); Topt.setArgName("content-type"); Option topt = new Option("t", true, "Client side socket timeout (in ms) - default 60 Secs"); topt.setRequired(false); topt.setArgName("socket-Timeout"); Option Hopt = new Option("H", true, "Add arbitrary header line, " + "eg. 'Accept-Encoding: gzip' inserted after all normal " + "header lines. (repeatable as -H \"h1: v1\",\"h2: v2\" etc)"); Hopt.setRequired(false); Hopt.setArgName("header"); Option vopt = new Option("v", true, "Set verbosity level - 4 and above " + "prints response content, 3 and above prints " + "information on headers, 2 and above prints response codes (404, 200, " + "etc.), 1 and above prints warnings and info"); vopt.setRequired(false); vopt.setArgName("verbosity"); Option hopt = new Option("h", false, "Display usage information"); nopt.setRequired(false); Options options = new Options(); options.addOption(iopt); options.addOption(mopt); options.addOption(uopt); options.addOption(xopt); options.addOption(gopt); options.addOption(kopt); options.addOption(nopt); options.addOption(copt); options.addOption(popt); options.addOption(Topt); options.addOption(vopt); options.addOption(Hopt); options.addOption(hopt); options.addOption(topt); options.addOption(oopt); return options; } public static void parseCommandLine(CommandLine cmd, Config config) { if (cmd.hasOption('v')) { String s = cmd.getOptionValue('v'); try { config.setVerbosity(Integer.parseInt(s)); } catch (NumberFormatException ex) { printError("Invalid verbosity level: " + s); } } if (cmd.hasOption('k')) { config.setKeepAlive(true); } if (cmd.hasOption('c')) { String s = cmd.getOptionValue('c'); try { config.setThreads(Integer.parseInt(s)); } catch (NumberFormatException ex) { printError("Invalid number for concurrency: " + s); } } if (cmd.hasOption('n')) { String s = cmd.getOptionValue('n'); try { config.setRequests(Integer.parseInt(s)); } catch (NumberFormatException ex) { printError("Invalid number of requests: " + s); } } if (cmd.hasOption('p')) { File file = new File(cmd.getOptionValue('p')); if (!file.exists()) { printError("File not found: " + file); } config.setPayloadFile(file); } if (cmd.hasOption('T')) { config.setContentType(cmd.getOptionValue('T')); } if (cmd.hasOption('i')) { config.setHeadInsteadOfGet(true); } if (cmd.hasOption('H')) { String headerStr = cmd.getOptionValue('H'); config.setHeaders(headerStr.split(",")); } if (cmd.hasOption('t')) { String t = cmd.getOptionValue('t'); try { config.setSocketTimeout(Integer.parseInt(t)); } catch (NumberFormatException ex) { printError("Invalid socket timeout: " + t); } } if (cmd.hasOption('o')) { config.setUseHttp1_0(true); } if (cmd.hasOption('m')) { config.setMethod(cmd.getOptionValue('m')); } else if (cmd.hasOption('p')) { config.setMethod("POST"); } if (cmd.hasOption('u')) { config.setUseChunking(true); } if (cmd.hasOption('x')) { config.setUseExpectContinue(true); } if (cmd.hasOption('g')) { config.setUseAcceptGZip(true); } String[] cmdargs = cmd.getArgs(); if (cmdargs.length > 0) { try { config.setUrl(new URL(cmdargs[0])); } catch (MalformedURLException e) { printError("Invalid request URL : " + cmdargs[0]); } } } static void showUsage(final Options options) { HelpFormatter formatter = new HelpFormatter(); formatter.printHelp("HttpBenchmark [options] [http://]hostname[:port]/path?query", options); } static void printError(String msg) { System.err.println(msg); showUsage(getOptions()); System.exit(-1); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; import org.apache.http.message.BasicHeader; public class DefaultHeader extends BasicHeader { public DefaultHeader(final String name, final String value) { super(name, value); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.benchmark; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.net.Socket; import java.security.KeyStore; import javax.net.SocketFactory; import javax.net.ssl.*; import org.apache.http.ConnectionReuseStrategy; import org.apache.http.Header; import org.apache.http.HeaderIterator; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpHost; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpStatus; import org.apache.http.impl.DefaultConnectionReuseStrategy; import org.apache.http.impl.DefaultHttpClientConnection; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpParams; import org.apache.http.params.DefaultedHttpParams; import org.apache.http.protocol.BasicHttpProcessor; import org.apache.http.protocol.HTTP; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.BasicHttpContext; import org.apache.http.protocol.ExecutionContext; import org.apache.http.protocol.HttpRequestExecutor; import org.apache.http.protocol.RequestConnControl; import org.apache.http.protocol.RequestContent; import org.apache.http.protocol.RequestExpectContinue; import org.apache.http.protocol.RequestTargetHost; import org.apache.http.protocol.RequestUserAgent; import org.apache.http.util.EntityUtils; /** * Worker thread for the {@link HttpBenchmark HttpBenchmark}. * * * @since 4.0 */ public class BenchmarkWorker implements Runnable { private byte[] buffer = new byte[4096]; private final int verbosity; private final HttpParams params; private final HttpContext context; private final BasicHttpProcessor httpProcessor; private final HttpRequestExecutor httpexecutor; private final ConnectionReuseStrategy connstrategy; private final HttpRequest request; private final HttpHost targetHost; private final int count; private final boolean keepalive; private final boolean disableSSLVerification; private final Stats stats = new Stats(); private final TrustManager[] trustAllCerts; private final String trustStorePath; private final String trustStorePassword; private final String identityStorePath; private final String identityStorePassword; public BenchmarkWorker( final HttpParams params, int verbosity, final HttpRequest request, final HttpHost targetHost, int count, boolean keepalive, boolean disableSSLVerification, String trustStorePath, String trustStorePassword, String identityStorePath, String identityStorePassword) { super(); this.params = params; this.context = new BasicHttpContext(null); this.request = request; this.targetHost = targetHost; this.count = count; this.keepalive = keepalive; this.httpProcessor = new BasicHttpProcessor(); this.httpexecutor = new HttpRequestExecutor(); // Required request interceptors this.httpProcessor.addInterceptor(new RequestContent()); this.httpProcessor.addInterceptor(new RequestTargetHost()); // Recommended request interceptors this.httpProcessor.addInterceptor(new RequestConnControl()); this.httpProcessor.addInterceptor(new RequestUserAgent()); this.httpProcessor.addInterceptor(new RequestExpectContinue()); this.connstrategy = new DefaultConnectionReuseStrategy(); this.verbosity = verbosity; this.disableSSLVerification = disableSSLVerification; this.trustStorePath = trustStorePath; this.trustStorePassword = trustStorePassword; this.identityStorePath = identityStorePath; this.identityStorePassword = identityStorePassword; // Create a trust manager that does not validate certificate chains trustAllCerts = new TrustManager[]{ new X509TrustManager() { public java.security.cert.X509Certificate[] getAcceptedIssuers() { return null; } public void checkClientTrusted( java.security.cert.X509Certificate[] certs, String authType) { } public void checkServerTrusted( java.security.cert.X509Certificate[] certs, String authType) { } } }; } public void run() { HttpResponse response = null; DefaultHttpClientConnection conn = new DefaultHttpClientConnection(); String hostname = targetHost.getHostName(); int port = targetHost.getPort(); if (port == -1) { port = 80; } // Populate the execution context this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.targetHost); this.context.setAttribute(ExecutionContext.HTTP_REQUEST, this.request); stats.start(); request.setParams(new DefaultedHttpParams(new BasicHttpParams(), this.params)); for (int i = 0; i < count; i++) { try { resetHeader(request); if (!conn.isOpen()) { Socket socket = null; if ("https".equals(targetHost.getSchemeName())) { if (disableSSLVerification) { SSLContext sc = SSLContext.getInstance("SSL"); if (identityStorePath != null) { KeyStore identityStore = KeyStore.getInstance(KeyStore.getDefaultType()); FileInputStream instream = new FileInputStream(identityStorePath); try { identityStore.load(instream, identityStorePassword.toCharArray()); } finally { try { instream.close(); } catch (IOException ignore) {} } KeyManagerFactory kmf = KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm()); kmf.init(identityStore, identityStorePassword.toCharArray()); sc.init(kmf.getKeyManagers(), trustAllCerts, null); } else { sc.init(null, trustAllCerts, null); } HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); socket = sc.getSocketFactory().createSocket(hostname, port); } else { if (trustStorePath != null) { System.setProperty("javax.net.ssl.trustStore", trustStorePath); } if (trustStorePassword != null) { System.setProperty("javax.net.ssl.trustStorePassword", trustStorePassword); } SocketFactory socketFactory = SSLSocketFactory.getDefault(); socket = socketFactory.createSocket(hostname, port); } } else { socket = new Socket(hostname, port); } conn.bind(socket, params); } try { // Prepare request this.httpexecutor.preProcess(this.request, this.httpProcessor, this.context); // Execute request and get a response response = this.httpexecutor.execute(this.request, conn, this.context); // Finalize response this.httpexecutor.postProcess(response, this.httpProcessor, this.context); } catch (HttpException e) { stats.incWriteErrors(); if (this.verbosity >= 2) { System.err.println("Failed HTTP request : " + e.getMessage()); } continue; } verboseOutput(response); if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { stats.incSuccessCount(); } else { stats.incFailureCount(); continue; } HttpEntity entity = response.getEntity(); if (entity != null) { String charset = EntityUtils.getContentCharSet(entity); if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } long contentlen = 0; InputStream instream = entity.getContent(); int l = 0; while ((l = instream.read(this.buffer)) != -1) { stats.incTotalBytesRecv(l); contentlen += l; if (this.verbosity >= 4) { String s = new String(this.buffer, 0, l, charset); System.out.print(s); } } instream.close(); stats.setContentLength(contentlen); } if (this.verbosity >= 4) { System.out.println(); System.out.println(); } if (!keepalive || !this.connstrategy.keepAlive(response, this.context)) { conn.close(); } else { stats.incKeepAliveCount(); } } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } catch (Exception ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("Generic error: " + ex.getMessage()); } } } stats.finish(); if (response != null) { Header header = response.getFirstHeader("Server"); if (header != null) { stats.setServerName(header.getValue()); } } try { conn.close(); } catch (IOException ex) { ex.printStackTrace(); stats.incFailureCount(); if (this.verbosity >= 2) { System.err.println("I/O error: " + ex.getMessage()); } } } private void verboseOutput(HttpResponse response) { if (this.verbosity >= 3) { System.out.println(">> " + request.getRequestLine().toString()); Header[] headers = request.getAllHeaders(); for (int h = 0; h < headers.length; h++) { System.out.println(">> " + headers[h].toString()); } System.out.println(); } if (this.verbosity >= 2) { System.out.println(response.getStatusLine().getStatusCode()); } if (this.verbosity >= 3) { System.out.println("<< " + response.getStatusLine().toString()); Header[] headers = response.getAllHeaders(); for (int h = 0; h < headers.length; h++) { System.out.println("<< " + headers[h].toString()); } System.out.println(); } } private static void resetHeader(final HttpRequest request) { for (HeaderIterator it = request.headerIterator(); it.hasNext();) { Header header = it.nextHeader(); if (!(header instanceof DefaultHeader)) { it.remove(); } } } public Stats getStats() { return stats; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.net.InetAddress; /** * An HTTP connection over the Internet Protocol (IP). * * @since 4.0 */ public interface HttpInetConnection extends HttpConnection { InetAddress getLocalAddress(); int getLocalPort(); InetAddress getRemoteAddress(); int getRemotePort(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * Constants enumerating the HTTP status codes. * All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and * RFC2518 (WebDAV) are listed. * * @see StatusLine * * @since 4.0 */ public interface HttpStatus { // --- 1xx Informational --- /** <tt>100 Continue</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_CONTINUE = 100; /** <tt>101 Switching Protocols</tt> (HTTP/1.1 - RFC 2616)*/ public static final int SC_SWITCHING_PROTOCOLS = 101; /** <tt>102 Processing</tt> (WebDAV - RFC 2518) */ public static final int SC_PROCESSING = 102; // --- 2xx Success --- /** <tt>200 OK</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_OK = 200; /** <tt>201 Created</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_CREATED = 201; /** <tt>202 Accepted</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_ACCEPTED = 202; /** <tt>203 Non Authoritative Information</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_NON_AUTHORITATIVE_INFORMATION = 203; /** <tt>204 No Content</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NO_CONTENT = 204; /** <tt>205 Reset Content</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_RESET_CONTENT = 205; /** <tt>206 Partial Content</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_PARTIAL_CONTENT = 206; /** * <tt>207 Multi-Status</tt> (WebDAV - RFC 2518) or <tt>207 Partial Update * OK</tt> (HTTP/1.1 - draft-ietf-http-v11-spec-rev-01?) */ public static final int SC_MULTI_STATUS = 207; // --- 3xx Redirection --- /** <tt>300 Mutliple Choices</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_MULTIPLE_CHOICES = 300; /** <tt>301 Moved Permanently</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_PERMANENTLY = 301; /** <tt>302 Moved Temporarily</tt> (Sometimes <tt>Found</tt>) (HTTP/1.0 - RFC 1945) */ public static final int SC_MOVED_TEMPORARILY = 302; /** <tt>303 See Other</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_SEE_OTHER = 303; /** <tt>304 Not Modified</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_MODIFIED = 304; /** <tt>305 Use Proxy</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_USE_PROXY = 305; /** <tt>307 Temporary Redirect</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_TEMPORARY_REDIRECT = 307; // --- 4xx Client Error --- /** <tt>400 Bad Request</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_BAD_REQUEST = 400; /** <tt>401 Unauthorized</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_UNAUTHORIZED = 401; /** <tt>402 Payment Required</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_PAYMENT_REQUIRED = 402; /** <tt>403 Forbidden</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_FORBIDDEN = 403; /** <tt>404 Not Found</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_FOUND = 404; /** <tt>405 Method Not Allowed</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** <tt>406 Not Acceptable</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_NOT_ACCEPTABLE = 406; /** <tt>407 Proxy Authentication Required</tt> (HTTP/1.1 - RFC 2616)*/ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** <tt>408 Request Timeout</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TIMEOUT = 408; /** <tt>409 Conflict</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_CONFLICT = 409; /** <tt>410 Gone</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_GONE = 410; /** <tt>411 Length Required</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_LENGTH_REQUIRED = 411; /** <tt>412 Precondition Failed</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_PRECONDITION_FAILED = 412; /** <tt>413 Request Entity Too Large</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_TOO_LONG = 413; /** <tt>414 Request-URI Too Long</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** <tt>415 Unsupported Media Type</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** <tt>416 Requested Range Not Satisfiable</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_REQUESTED_RANGE_NOT_SATISFIABLE = 416; /** <tt>417 Expectation Failed</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_EXPECTATION_FAILED = 417; /** * Static constant for a 418 error. * <tt>418 Unprocessable Entity</tt> (WebDAV drafts?) * or <tt>418 Reauthentication Required</tt> (HTTP/1.1 drafts?) */ // not used // public static final int SC_UNPROCESSABLE_ENTITY = 418; /** * Static constant for a 419 error. * <tt>419 Insufficient Space on Resource</tt> * (WebDAV - draft-ietf-webdav-protocol-05?) * or <tt>419 Proxy Reauthentication Required</tt> * (HTTP/1.1 drafts?) */ public static final int SC_INSUFFICIENT_SPACE_ON_RESOURCE = 419; /** * Static constant for a 420 error. * <tt>420 Method Failure</tt> * (WebDAV - draft-ietf-webdav-protocol-05?) */ public static final int SC_METHOD_FAILURE = 420; /** <tt>422 Unprocessable Entity</tt> (WebDAV - RFC 2518) */ public static final int SC_UNPROCESSABLE_ENTITY = 422; /** <tt>423 Locked</tt> (WebDAV - RFC 2518) */ public static final int SC_LOCKED = 423; /** <tt>424 Failed Dependency</tt> (WebDAV - RFC 2518) */ public static final int SC_FAILED_DEPENDENCY = 424; // --- 5xx Server Error --- /** <tt>500 Server Error</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_INTERNAL_SERVER_ERROR = 500; /** <tt>501 Not Implemented</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_NOT_IMPLEMENTED = 501; /** <tt>502 Bad Gateway</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_BAD_GATEWAY = 502; /** <tt>503 Service Unavailable</tt> (HTTP/1.0 - RFC 1945) */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** <tt>504 Gateway Timeout</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_GATEWAY_TIMEOUT = 504; /** <tt>505 HTTP Version Not Supported</tt> (HTTP/1.1 - RFC 2616) */ public static final int SC_HTTP_VERSION_NOT_SUPPORTED = 505; /** <tt>507 Insufficient Storage</tt> (WebDAV - RFC 2518) */ public static final int SC_INSUFFICIENT_STORAGE = 507; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * A factory for {@link HttpRequest HttpRequest} objects. * * @since 4.0 */ public interface HttpRequestFactory { HttpRequest newHttpRequest(RequestLine requestline) throws MethodNotSupportedException; HttpRequest newHttpRequest(String method, String uri) throws MethodNotSupportedException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.params.HttpProtocolParams; /** * RequestUserAgent is responsible for adding <code>User-Agent</code> header. * This interceptor is recommended for client side protocol processors. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USER_AGENT}</li> * </ul> * * @since 4.0 */ public class RequestUserAgent implements HttpRequestInterceptor { public RequestUserAgent() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (!request.containsHeader(HTTP.USER_AGENT)) { String useragent = HttpProtocolParams.getUserAgent(request.getParams()); if (useragent != null) { request.addHeader(HTTP.USER_AGENT, useragent); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; /** * Defines an interface to verify whether an incoming HTTP request meets * the target server's expectations. *<p> * The Expect request-header field is used to indicate that particular * server behaviors are required by the client. *</p> *<pre> * Expect = "Expect" ":" 1#expectation * * expectation = "100-continue" | expectation-extension * expectation-extension = token [ "=" ( token | quoted-string ) * *expect-params ] * expect-params = ";" token [ "=" ( token | quoted-string ) ] *</pre> *<p> * A server that does not understand or is unable to comply with any of * the expectation values in the Expect field of a request MUST respond * with appropriate error status. The server MUST respond with a 417 * (Expectation Failed) status if any of the expectations cannot be met * or, if there are other problems with the request, some other 4xx * status. *</p> * * @since 4.0 */ public interface HttpExpectationVerifier { /** * Verifies whether the given request meets the server's expectations. * <p> * If the request fails to meet particular criteria, this method can * trigger a terminal response back to the client by setting the status * code of the response object to a value greater or equal to * <code>200</code>. In this case the client will not have to transmit * the request body. If the request meets expectations this method can * terminate without modifying the response object. Per default the status * code of the response object will be set to <code>100</code>. * * @param request the HTTP request. * @param response the HTTP response. * @param context the HTTP context. * @throws HttpException in case of an HTTP protocol violation. */ void verify(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; /** * Constants and static helpers related to the HTTP protocol. * * @since 4.0 */ public final class HTTP { public static final int CR = 13; // <US-ASCII CR, carriage return (13)> public static final int LF = 10; // <US-ASCII LF, linefeed (10)> public static final int SP = 32; // <US-ASCII SP, space (32)> public static final int HT = 9; // <US-ASCII HT, horizontal-tab (9)> /** HTTP header definitions */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; public static final String CONTENT_LEN = "Content-Length"; public static final String CONTENT_TYPE = "Content-Type"; public static final String CONTENT_ENCODING = "Content-Encoding"; public static final String EXPECT_DIRECTIVE = "Expect"; public static final String CONN_DIRECTIVE = "Connection"; public static final String TARGET_HOST = "Host"; public static final String USER_AGENT = "User-Agent"; public static final String DATE_HEADER = "Date"; public static final String SERVER_HEADER = "Server"; /** HTTP expectations */ public static final String EXPECT_CONTINUE = "100-continue"; /** HTTP connection control */ public static final String CONN_CLOSE = "Close"; public static final String CONN_KEEP_ALIVE = "Keep-Alive"; /** Transfer encoding definitions */ public static final String CHUNK_CODING = "chunked"; public static final String IDENTITY_CODING = "identity"; /** Common charset definitions */ public static final String UTF_8 = "UTF-8"; public static final String UTF_16 = "UTF-16"; public static final String US_ASCII = "US-ASCII"; public static final String ASCII = "ASCII"; public static final String ISO_8859_1 = "ISO-8859-1"; /** Default charsets */ public static final String DEFAULT_CONTENT_CHARSET = ISO_8859_1; public static final String DEFAULT_PROTOCOL_CHARSET = US_ASCII; /** Content type definitions */ public final static String OCTET_STREAM_TYPE = "application/octet-stream"; public final static String PLAIN_TEXT_TYPE = "text/plain"; public final static String CHARSET_PARAM = "; charset="; /** Default content type */ public final static String DEFAULT_CONTENT_TYPE = OCTET_STREAM_TYPE; public static boolean isWhitespace(char ch) { return ch == SP || ch == HT || ch == CR || ch == LF; } private HTTP() { } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; /** * RequestDate interceptor is responsible for adding <code>Date</code> header * to the outgoing requests This interceptor is optional for client side * protocol processors. * * @since 4.0 */ public class RequestDate implements HttpRequestInterceptor { private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); public RequestDate() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException ("HTTP request may not be null."); } if ((request instanceof HttpEntityEnclosingRequest) && !request.containsHeader(HTTP.DATE_HEADER)) { String httpdate = DATE_GENERATOR.getCurrentDate(); request.setHeader(HTTP.DATE_HEADER, httpdate); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; /** * HttpRequestHandler represents a routine for processing of a specific group * of HTTP requests. Protocol handlers are designed to take care of protocol * specific aspects, whereas individual request handlers are expected to take * care of application specific HTTP processing. The main purpose of a request * handler is to generate a response object with a content entity to be sent * back to the client in response to the given request * * @since 4.0 */ public interface HttpRequestHandler { /** * Handles the request and produces a response to be sent back to * the client. * * @param request the HTTP request. * @param response the HTTP response. * @param context the HTTP execution context. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ void handle(HttpRequest request, HttpResponse response, HttpContext context) throws HttpException, IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; /** * HttpRequestHandlerResolver can be used to resolve an instance of * {@link HttpRequestHandler} matching a particular request URI. Usually the * resolved request handler will be used to process the request with the * specified request URI. * * @since 4.0 */ public interface HttpRequestHandlerResolver { /** * Looks up a handler matching the given request URI. * * @param requestURI the request URI * @return HTTP request handler or <code>null</code> if no match * is found. */ HttpRequestHandler lookup(String requestURI); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.ProtocolVersion; /** * RequestContent is the most important interceptor for outgoing requests. * It is responsible for delimiting content length by adding * <code>Content-Length</code> or <code>Transfer-Content</code> headers based * on the properties of the enclosed entity and the protocol version. * This interceptor is required for correct functioning of client side protocol * processors. * * @since 4.0 */ public class RequestContent implements HttpRequestInterceptor { public RequestContent() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (request instanceof HttpEntityEnclosingRequest) { if (request.containsHeader(HTTP.TRANSFER_ENCODING)) { throw new ProtocolException("Transfer-encoding header already present"); } if (request.containsHeader(HTTP.CONTENT_LEN)) { throw new ProtocolException("Content-Length header already present"); } ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); if (entity == null) { request.addHeader(HTTP.CONTENT_LEN, "0"); return; } // Must specify a transfer encoding or a content length if (entity.isChunked() || entity.getContentLength() < 0) { if (ver.lessEquals(HttpVersion.HTTP_1_0)) { throw new ProtocolException( "Chunked transfer encoding not allowed for " + ver); } request.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); } else { request.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); } // Specify a content type if known if (entity.getContentType() != null && !request.containsHeader( HTTP.CONTENT_TYPE )) { request.addHeader(entity.getContentType()); } // Specify a content encoding if known if (entity.getContentEncoding() != null && !request.containsHeader( HTTP.CONTENT_ENCODING)) { request.addHeader(entity.getContentEncoding()); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import java.net.InetAddress; import org.apache.ogt.http.HttpConnection; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpHost; import org.apache.ogt.http.HttpInetConnection; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.ProtocolVersion; /** * RequestTargetHost is responsible for adding <code>Host</code> header. This * interceptor is required for client side protocol processors. * * @since 4.0 */ public class RequestTargetHost implements HttpRequestInterceptor { public RequestTargetHost() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT") && ver.lessEquals(HttpVersion.HTTP_1_0)) { return; } if (!request.containsHeader(HTTP.TARGET_HOST)) { HttpHost targethost = (HttpHost) context .getAttribute(ExecutionContext.HTTP_TARGET_HOST); if (targethost == null) { HttpConnection conn = (HttpConnection) context .getAttribute(ExecutionContext.HTTP_CONNECTION); if (conn instanceof HttpInetConnection) { // Populate the context with a default HTTP host based on the // inet address of the target host InetAddress address = ((HttpInetConnection) conn).getRemoteAddress(); int port = ((HttpInetConnection) conn).getRemotePort(); if (address != null) { targethost = new HttpHost(address.getHostName(), port); } } if (targethost == null) { if (ver.lessEquals(HttpVersion.HTTP_1_0)) { return; } else { throw new ProtocolException("Target host missing"); } } } request.addHeader(HTTP.TARGET_HOST, targethost.toHostString()); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import java.net.ProtocolException; import org.apache.ogt.http.HttpClientConnection; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.params.CoreProtocolPNames; /** * HttpRequestExecutor is a client side HTTP protocol handler based on the * blocking I/O model that implements the essential requirements of the HTTP * protocol for the client side message processing, as described by RFC 2616. * <br> * HttpRequestExecutor relies on {@link HttpProcessor} to generate mandatory * protocol headers for all outgoing messages and apply common, cross-cutting * message transformations to all incoming and outgoing messages. Application * specific processing can be implemented outside HttpRequestExecutor once the * request has been executed and a response has been received. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#WAIT_FOR_CONTINUE}</li> * </ul> * * @since 4.0 */ public class HttpRequestExecutor { /** * Create a new request executor. */ public HttpRequestExecutor() { super(); } /** * Decide whether a response comes with an entity. * The implementation in this class is based on RFC 2616. * <br/> * Derived executors can override this method to handle * methods and response codes not specified in RFC 2616. * * @param request the request, to obtain the executed method * @param response the response, to obtain the status code */ protected boolean canResponseHaveBody(final HttpRequest request, final HttpResponse response) { if ("HEAD".equalsIgnoreCase(request.getRequestLine().getMethod())) { return false; } int status = response.getStatusLine().getStatusCode(); return status >= HttpStatus.SC_OK && status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT; } /** * Sends the request and obtain a response. * * @param request the request to execute. * @param conn the connection over which to execute the request. * * @return the response to the request. * * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ public HttpResponse execute( final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("Client connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } try { HttpResponse response = doSendRequest(request, conn, context); if (response == null) { response = doReceiveResponse(request, conn, context); } return response; } catch (IOException ex) { closeConnection(conn); throw ex; } catch (HttpException ex) { closeConnection(conn); throw ex; } catch (RuntimeException ex) { closeConnection(conn); throw ex; } } private final static void closeConnection(final HttpClientConnection conn) { try { conn.close(); } catch (IOException ignore) { } } /** * Pre-process the given request using the given protocol processor and * initiates the process of request execution. * * @param request the request to prepare * @param processor the processor to use * @param context the context for sending the request * * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ public void preProcess( final HttpRequest request, final HttpProcessor processor, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (processor == null) { throw new IllegalArgumentException("HTTP processor may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } context.setAttribute(ExecutionContext.HTTP_REQUEST, request); processor.process(request, context); } /** * Send the given request over the given connection. * <p> * This method also handles the expect-continue handshake if necessary. * If it does not have to handle an expect-continue handshake, it will * not use the connection for reading or anything else that depends on * data coming in over the connection. * * @param request the request to send, already * {@link #preProcess preprocessed} * @param conn the connection over which to send the request, * already established * @param context the context for sending the request * * @return a terminal response received as part of an expect-continue * handshake, or * <code>null</code> if the expect-continue handshake is not used * * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ protected HttpResponse doSendRequest( final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws IOException, HttpException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("HTTP connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpResponse response = null; context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.FALSE); conn.sendRequestHeader(request); if (request instanceof HttpEntityEnclosingRequest) { // Check for expect-continue handshake. We have to flush the // headers and wait for an 100-continue response to handle it. // If we get a different response, we must not send the entity. boolean sendentity = true; final ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (((HttpEntityEnclosingRequest) request).expectContinue() && !ver.lessEquals(HttpVersion.HTTP_1_0)) { conn.flush(); // As suggested by RFC 2616 section 8.2.3, we don't wait for a // 100-continue response forever. On timeout, send the entity. int tms = request.getParams().getIntParameter( CoreProtocolPNames.WAIT_FOR_CONTINUE, 2000); if (conn.isResponseAvailable(tms)) { response = conn.receiveResponseHeader(); if (canResponseHaveBody(request, response)) { conn.receiveResponseEntity(response); } int status = response.getStatusLine().getStatusCode(); if (status < 200) { if (status != HttpStatus.SC_CONTINUE) { throw new ProtocolException( "Unexpected response: " + response.getStatusLine()); } // discard 100-continue response = null; } else { sendentity = false; } } } if (sendentity) { conn.sendRequestEntity((HttpEntityEnclosingRequest) request); } } conn.flush(); context.setAttribute(ExecutionContext.HTTP_REQ_SENT, Boolean.TRUE); return response; } /** * Waits for and receives a response. * This method will automatically ignore intermediate responses * with status code 1xx. * * @param request the request for which to obtain the response * @param conn the connection over which the request was sent * @param context the context for receiving the response * * @return the terminal response, not yet post-processed * * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ protected HttpResponse doReceiveResponse( final HttpRequest request, final HttpClientConnection conn, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (conn == null) { throw new IllegalArgumentException("HTTP connection may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } HttpResponse response = null; int statuscode = 0; while (response == null || statuscode < HttpStatus.SC_OK) { response = conn.receiveResponseHeader(); if (canResponseHaveBody(request, response)) { conn.receiveResponseEntity(response); } statuscode = response.getStatusLine().getStatusCode(); } // while intermediate response return response; } /** * Post-processes the given response using the given protocol processor and * completes the process of request execution. * <p> * This method does <i>not</i> read the response entity, if any. * The connection over which content of the response entity is being * streamed from cannot be reused until {@link HttpEntity#consumeContent()} * has been invoked. * * @param response the response object to post-process * @param processor the processor to use * @param context the context for post-processing the response * * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ public void postProcess( final HttpResponse response, final HttpProcessor processor, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } if (processor == null) { throw new IllegalArgumentException("HTTP processor may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } context.setAttribute(ExecutionContext.HTTP_RESPONSE, response); processor.process(response, context); } } // class HttpRequestExecutor
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Locale; import java.util.TimeZone; /** * Generates a date in the format required by the HTTP protocol. * * @since 4.0 */ public class HttpDateGenerator { /** Date format pattern used to generate the header in RFC 1123 format. */ public static final String PATTERN_RFC1123 = "EEE, dd MMM yyyy HH:mm:ss zzz"; /** The time zone to use in the date header. */ public static final TimeZone GMT = TimeZone.getTimeZone("GMT"); private final DateFormat dateformat; private long dateAsLong = 0L; private String dateAsText = null; public HttpDateGenerator() { super(); this.dateformat = new SimpleDateFormat(PATTERN_RFC1123, Locale.US); this.dateformat.setTimeZone(GMT); } public synchronized String getCurrentDate() { long now = System.currentTimeMillis(); if (now - this.dateAsLong > 1000) { // Generate new date string this.dateAsText = this.dateformat.format(new Date(now)); this.dateAsLong = now; } return this.dateAsText; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; /** * Immutable {@link HttpProcessor}. * * @since 4.1 */ //@ThreadSafe public final class ImmutableHttpProcessor implements HttpProcessor { private final HttpRequestInterceptor[] requestInterceptors; private final HttpResponseInterceptor[] responseInterceptors; public ImmutableHttpProcessor( final HttpRequestInterceptor[] requestInterceptors, final HttpResponseInterceptor[] responseInterceptors) { super(); if (requestInterceptors != null) { int count = requestInterceptors.length; this.requestInterceptors = new HttpRequestInterceptor[count]; for (int i = 0; i < count; i++) { this.requestInterceptors[i] = requestInterceptors[i]; } } else { this.requestInterceptors = new HttpRequestInterceptor[0]; } if (responseInterceptors != null) { int count = responseInterceptors.length; this.responseInterceptors = new HttpResponseInterceptor[count]; for (int i = 0; i < count; i++) { this.responseInterceptors[i] = responseInterceptors[i]; } } else { this.responseInterceptors = new HttpResponseInterceptor[0]; } } public ImmutableHttpProcessor( final HttpRequestInterceptorList requestInterceptors, final HttpResponseInterceptorList responseInterceptors) { super(); if (requestInterceptors != null) { int count = requestInterceptors.getRequestInterceptorCount(); this.requestInterceptors = new HttpRequestInterceptor[count]; for (int i = 0; i < count; i++) { this.requestInterceptors[i] = requestInterceptors.getRequestInterceptor(i); } } else { this.requestInterceptors = new HttpRequestInterceptor[0]; } if (responseInterceptors != null) { int count = responseInterceptors.getResponseInterceptorCount(); this.responseInterceptors = new HttpResponseInterceptor[count]; for (int i = 0; i < count; i++) { this.responseInterceptors[i] = responseInterceptors.getResponseInterceptor(i); } } else { this.responseInterceptors = new HttpResponseInterceptor[0]; } } public ImmutableHttpProcessor(final HttpRequestInterceptor[] requestInterceptors) { this(requestInterceptors, null); } public ImmutableHttpProcessor(final HttpResponseInterceptor[] responseInterceptors) { this(null, responseInterceptors); } public void process( final HttpRequest request, final HttpContext context) throws IOException, HttpException { for (int i = 0; i < this.requestInterceptors.length; i++) { this.requestInterceptors[i].process(request, context); } } public void process( final HttpResponse response, final HttpContext context) throws IOException, HttpException { for (int i = 0; i < this.responseInterceptors.length; i++) { this.responseInterceptors[i].process(response, context); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.util.List; import org.apache.ogt.http.HttpResponseInterceptor; /** * Provides access to an ordered list of response interceptors. * Lists are expected to be built upfront and used read-only afterwards * for {@link HttpProcessor processing}. * * @since 4.0 */ public interface HttpResponseInterceptorList { /** * Appends a response interceptor to this list. * * @param interceptor the response interceptor to add */ void addResponseInterceptor(HttpResponseInterceptor interceptor); /** * Inserts a response interceptor at the specified index. * * @param interceptor the response interceptor to add * @param index the index to insert the interceptor at */ void addResponseInterceptor(HttpResponseInterceptor interceptor, int index); /** * Obtains the current size of this list. * * @return the number of response interceptors in this list */ int getResponseInterceptorCount(); /** * Obtains a response interceptor from this list. * * @param index the index of the interceptor to obtain, * 0 for first * * @return the interceptor at the given index, or * <code>null</code> if the index is out of range */ HttpResponseInterceptor getResponseInterceptor(int index); /** * Removes all response interceptors from this list. */ void clearResponseInterceptors(); /** * Removes all response interceptor of the specified class * * @param clazz the class of the instances to be removed. */ void removeResponseInterceptorByClass(Class clazz); /** * Sets the response interceptors in this list. * This list will be cleared and re-initialized to contain * all response interceptors from the argument list. * If the argument list includes elements that are not response * interceptors, the behavior is implementation dependent. * * @param list the list of response interceptors */ void setInterceptors(List list); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.ProtocolVersion; /** * ResponseContent is the most important interceptor for outgoing responses. * It is responsible for delimiting content length by adding * <code>Content-Length</code> or <code>Transfer-Content</code> headers based * on the properties of the enclosed entity and the protocol version. * This interceptor is required for correct functioning of server side protocol * processors. * * @since 4.0 */ public class ResponseContent implements HttpResponseInterceptor { public ResponseContent() { super(); } public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (response.containsHeader(HTTP.TRANSFER_ENCODING)) { throw new ProtocolException("Transfer-encoding header already present"); } if (response.containsHeader(HTTP.CONTENT_LEN)) { throw new ProtocolException("Content-Length header already present"); } ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); HttpEntity entity = response.getEntity(); if (entity != null) { long len = entity.getContentLength(); if (entity.isChunked() && !ver.lessEquals(HttpVersion.HTTP_1_0)) { response.addHeader(HTTP.TRANSFER_ENCODING, HTTP.CHUNK_CODING); } else if (len >= 0) { response.addHeader(HTTP.CONTENT_LEN, Long.toString(entity.getContentLength())); } // Specify a content type if known if (entity.getContentType() != null && !response.containsHeader( HTTP.CONTENT_TYPE )) { response.addHeader(entity.getContentType()); } // Specify a content encoding if known if (entity.getContentEncoding() != null && !response.containsHeader( HTTP.CONTENT_ENCODING)) { response.addHeader(entity.getContentEncoding()); } } else { int status = response.getStatusLine().getStatusCode(); if (status != HttpStatus.SC_NO_CONTENT && status != HttpStatus.SC_NOT_MODIFIED && status != HttpStatus.SC_RESET_CONTENT) { response.addHeader(HTTP.CONTENT_LEN, "0"); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.HttpResponseInterceptor; /** * HTTP protocol processor is a collection of protocol interceptors that * implements the 'Chain of Responsibility' pattern, where each individual * protocol interceptor is expected to work on a particular aspect of the HTTP * protocol the interceptor is responsible for. * <p> * Usually the order in which interceptors are executed should not matter as * long as they do not depend on a particular state of the execution context. * If protocol interceptors have interdependencies and therefore must be * executed in a particular order, they should be added to the protocol * processor in the same sequence as their expected execution order. * <p> * Protocol interceptors must be implemented as thread-safe. Similarly to * servlets, protocol interceptors should not use instance variables unless * access to those variables is synchronized. * * @since 4.0 */ public interface HttpProcessor extends HttpRequestInterceptor, HttpResponseInterceptor { // no additional methods }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.util.HashMap; /** * HttpContext represents execution state of an HTTP process. It is a structure * that can be used to map an attribute name to an attribute value. Internally * HTTP context implementations are usually backed by a {@link HashMap}. * <p> * The primary purpose of the HTTP context is to facilitate information sharing * among various logically related components. HTTP context can be used * to store a processing state for one message or several consecutive messages. * Multiple logically related messages can participate in a logical session * if the same context is reused between consecutive messages. * * @since 4.0 */ public interface HttpContext { /** The prefix reserved for use by HTTP components. "http." */ public static final String RESERVED_PREFIX = "http."; /** * Obtains attribute with the given name. * * @param id the attribute name. * @return attribute value, or <code>null</code> if not set. */ Object getAttribute(String id); /** * Sets value of the attribute with the given name. * * @param id the attribute name. * @param obj the attribute value. */ void setAttribute(String id, Object obj); /** * Removes attribute with the given name from the context. * * @param id the attribute name. * @return attribute value, or <code>null</code> if not set. */ Object removeAttribute(String id); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; /** * Thread-safe extension of the {@link BasicHttpContext}. * * @since 4.0 */ public class SyncBasicHttpContext extends BasicHttpContext { public SyncBasicHttpContext(final HttpContext parentContext) { super(parentContext); } public synchronized Object getAttribute(final String id) { return super.getAttribute(id); } public synchronized void setAttribute(final String id, final Object obj) { super.setAttribute(id, obj); } public synchronized Object removeAttribute(final String id) { return super.removeAttribute(id); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; /** * Default implementation of {@link HttpProcessor}. * <p> * Please note access to the internal structures of this class is not * synchronized and therefore this class may be thread-unsafe. * * @since 4.0 */ //@NotThreadSafe // Lists are not synchronized public final class BasicHttpProcessor implements HttpProcessor, HttpRequestInterceptorList, HttpResponseInterceptorList, Cloneable { // Don't allow direct access, as nulls are not allowed protected final List requestInterceptors = new ArrayList(); protected final List responseInterceptors = new ArrayList(); public void addRequestInterceptor(final HttpRequestInterceptor itcp) { if (itcp == null) { return; } this.requestInterceptors.add(itcp); } public void addRequestInterceptor( final HttpRequestInterceptor itcp, int index) { if (itcp == null) { return; } this.requestInterceptors.add(index, itcp); } public void addResponseInterceptor( final HttpResponseInterceptor itcp, int index) { if (itcp == null) { return; } this.responseInterceptors.add(index, itcp); } public void removeRequestInterceptorByClass(final Class clazz) { for (Iterator it = this.requestInterceptors.iterator(); it.hasNext(); ) { Object request = it.next(); if (request.getClass().equals(clazz)) { it.remove(); } } } public void removeResponseInterceptorByClass(final Class clazz) { for (Iterator it = this.responseInterceptors.iterator(); it.hasNext(); ) { Object request = it.next(); if (request.getClass().equals(clazz)) { it.remove(); } } } public final void addInterceptor(final HttpRequestInterceptor interceptor) { addRequestInterceptor(interceptor); } public final void addInterceptor(final HttpRequestInterceptor interceptor, int index) { addRequestInterceptor(interceptor, index); } public int getRequestInterceptorCount() { return this.requestInterceptors.size(); } public HttpRequestInterceptor getRequestInterceptor(int index) { if ((index < 0) || (index >= this.requestInterceptors.size())) return null; return (HttpRequestInterceptor) this.requestInterceptors.get(index); } public void clearRequestInterceptors() { this.requestInterceptors.clear(); } public void addResponseInterceptor(final HttpResponseInterceptor itcp) { if (itcp == null) { return; } this.responseInterceptors.add(itcp); } public final void addInterceptor(final HttpResponseInterceptor interceptor) { addResponseInterceptor(interceptor); } public final void addInterceptor(final HttpResponseInterceptor interceptor, int index) { addResponseInterceptor(interceptor, index); } public int getResponseInterceptorCount() { return this.responseInterceptors.size(); } public HttpResponseInterceptor getResponseInterceptor(int index) { if ((index < 0) || (index >= this.responseInterceptors.size())) return null; return (HttpResponseInterceptor) this.responseInterceptors.get(index); } public void clearResponseInterceptors() { this.responseInterceptors.clear(); } /** * Sets the interceptor lists. * First, both interceptor lists maintained by this processor * will be cleared. * Subsequently, * elements of the argument list that are request interceptors will be * added to the request interceptor list. * Elements that are response interceptors will be * added to the response interceptor list. * Elements that are both request and response interceptor will be * added to both lists. * Elements that are neither request nor response interceptor * will be ignored. * * @param list the list of request and response interceptors * from which to initialize */ public void setInterceptors(final List list) { if (list == null) { throw new IllegalArgumentException("List must not be null."); } this.requestInterceptors.clear(); this.responseInterceptors.clear(); for (int i = 0; i < list.size(); i++) { Object obj = list.get(i); if (obj instanceof HttpRequestInterceptor) { addInterceptor((HttpRequestInterceptor)obj); } if (obj instanceof HttpResponseInterceptor) { addInterceptor((HttpResponseInterceptor)obj); } } } /** * Clears both interceptor lists maintained by this processor. */ public void clearInterceptors() { clearRequestInterceptors(); clearResponseInterceptors(); } public void process( final HttpRequest request, final HttpContext context) throws IOException, HttpException { for (int i = 0; i < this.requestInterceptors.size(); i++) { HttpRequestInterceptor interceptor = (HttpRequestInterceptor) this.requestInterceptors.get(i); interceptor.process(request, context); } } public void process( final HttpResponse response, final HttpContext context) throws IOException, HttpException { for (int i = 0; i < this.responseInterceptors.size(); i++) { HttpResponseInterceptor interceptor = (HttpResponseInterceptor) this.responseInterceptors.get(i); interceptor.process(response, context); } } /** * Sets up the target to have the same list of interceptors * as the current instance. * * @param target object to be initialised */ protected void copyInterceptors(final BasicHttpProcessor target) { target.requestInterceptors.clear(); target.requestInterceptors.addAll(this.requestInterceptors); target.responseInterceptors.clear(); target.responseInterceptors.addAll(this.responseInterceptors); } /** * Creates a copy of this instance * * @return new instance of the BasicHttpProcessor */ public BasicHttpProcessor copy() { BasicHttpProcessor clone = new BasicHttpProcessor(); copyInterceptors(clone); return clone; } public Object clone() throws CloneNotSupportedException { BasicHttpProcessor clone = (BasicHttpProcessor) super.clone(); copyInterceptors(clone); return clone; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.params.HttpProtocolParams; /** * RequestExpectContinue is responsible for enabling the 'expect-continue' * handshake by adding <code>Expect</code> header. This interceptor is * recommended for client side protocol processors. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#USE_EXPECT_CONTINUE}</li> * </ul> * * @since 4.0 */ public class RequestExpectContinue implements HttpRequestInterceptor { public RequestExpectContinue() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); // Do not send the expect header if request body is known to be empty if (entity != null && entity.getContentLength() != 0) { ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (HttpProtocolParams.useExpectContinue(request.getParams()) && !ver.lessEquals(HttpVersion.HTTP_1_0)) { request.addHeader(HTTP.EXPECT_DIRECTIVE, HTTP.EXPECT_CONTINUE); } } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpRequestInterceptor; /** * RequestConnControl is responsible for adding <code>Connection</code> header * to the outgoing requests, which is essential for managing persistence of * <code>HTTP/1.0</code> connections. This interceptor is recommended for * client side protocol processors. * * @since 4.0 */ public class RequestConnControl implements HttpRequestInterceptor { public RequestConnControl() { super(); } public void process(final HttpRequest request, final HttpContext context) throws HttpException, IOException { if (request == null) { throw new IllegalArgumentException("HTTP request may not be null"); } String method = request.getRequestLine().getMethod(); if (method.equalsIgnoreCase("CONNECT")) { return; } if (!request.containsHeader(HTTP.CONN_DIRECTIVE)) { // Default policy is to keep connection alive // whenever possible request.addHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_KEEP_ALIVE); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.util.List; import org.apache.ogt.http.HttpRequestInterceptor; /** * Provides access to an ordered list of request interceptors. * Lists are expected to be built upfront and used read-only afterwards * for {@link HttpProcessor processing}. * * @since 4.0 */ public interface HttpRequestInterceptorList { /** * Appends a request interceptor to this list. * * @param interceptor the request interceptor to add */ void addRequestInterceptor(HttpRequestInterceptor interceptor); /** * Inserts a request interceptor at the specified index. * * @param interceptor the request interceptor to add * @param index the index to insert the interceptor at */ void addRequestInterceptor(HttpRequestInterceptor interceptor, int index); /** * Obtains the current size of this list. * * @return the number of request interceptors in this list */ int getRequestInterceptorCount(); /** * Obtains a request interceptor from this list. * * @param index the index of the interceptor to obtain, * 0 for first * * @return the interceptor at the given index, or * <code>null</code> if the index is out of range */ HttpRequestInterceptor getRequestInterceptor(int index); /** * Removes all request interceptors from this list. */ void clearRequestInterceptors(); /** * Removes all request interceptor of the specified class * * @param clazz the class of the instances to be removed. */ void removeRequestInterceptorByClass(Class clazz); /** * Sets the request interceptors in this list. * This list will be cleared and re-initialized to contain * all request interceptors from the argument list. * If the argument list includes elements that are not request * interceptors, the behavior is implementation dependent. * * @param list the list of request interceptors */ void setInterceptors(List list); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.util.Map; /** * Maintains a map of HTTP request handlers keyed by a request URI pattern. * <br> * Patterns may have three formats: * <ul> * <li><code>*</code></li> * <li><code>*&lt;uri&gt;</code></li> * <li><code>&lt;uri&gt;*</code></li> * </ul> * <br> * This class can be used to resolve an instance of * {@link HttpRequestHandler} matching a particular request URI. Usually the * resolved request handler will be used to process the request with the * specified request URI. * * @since 4.0 */ public class HttpRequestHandlerRegistry implements HttpRequestHandlerResolver { private final UriPatternMatcher matcher; public HttpRequestHandlerRegistry() { matcher = new UriPatternMatcher(); } /** * Registers the given {@link HttpRequestHandler} as a handler for URIs * matching the given pattern. * * @param pattern the pattern to register the handler for. * @param handler the handler. */ public void register(final String pattern, final HttpRequestHandler handler) { if (pattern == null) { throw new IllegalArgumentException("URI request pattern may not be null"); } if (handler == null) { throw new IllegalArgumentException("Request handler may not be null"); } matcher.register(pattern, handler); } /** * Removes registered handler, if exists, for the given pattern. * * @param pattern the pattern to unregister the handler for. */ public void unregister(final String pattern) { matcher.unregister(pattern); } /** * Sets handlers from the given map. * @param map the map containing handlers keyed by their URI patterns. */ public void setHandlers(final Map map) { matcher.setObjects(map); } public HttpRequestHandler lookup(final String requestURI) { return (HttpRequestHandler) matcher.lookup(requestURI); } /** * @deprecated */ protected boolean matchUriRequestPattern(final String pattern, final String requestUri) { return matcher.matchUriRequestPattern(pattern, requestUri); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.params.CoreProtocolPNames; /** * ResponseServer is responsible for adding <code>Server</code> header. This * interceptor is recommended for server side protocol processors. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#ORIGIN_SERVER}</li> * </ul> * * @since 4.0 */ public class ResponseServer implements HttpResponseInterceptor { public ResponseServer() { super(); } public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP request may not be null"); } if (!response.containsHeader(HTTP.SERVER_HEADER)) { String s = (String) response.getParams().getParameter( CoreProtocolPNames.ORIGIN_SERVER); if (s != null) { response.addHeader(HTTP.SERVER_HEADER, s); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; /** * {@link HttpContext} attribute names for protocol execution. * * @since 4.0 */ public interface ExecutionContext { /** * Attribute name of a {@link org.apache.ogt.http.HttpConnection} object that * represents the actual HTTP connection. */ public static final String HTTP_CONNECTION = "http.connection"; /** * Attribute name of a {@link org.apache.ogt.http.HttpRequest} object that * represents the actual HTTP request. */ public static final String HTTP_REQUEST = "http.request"; /** * Attribute name of a {@link org.apache.ogt.http.HttpResponse} object that * represents the actual HTTP response. */ public static final String HTTP_RESPONSE = "http.response"; /** * Attribute name of a {@link org.apache.ogt.http.HttpHost} object that * represents the connection target. */ public static final String HTTP_TARGET_HOST = "http.target_host"; /** * Attribute name of a {@link org.apache.ogt.http.HttpHost} object that * represents the connection proxy. */ public static final String HTTP_PROXY_HOST = "http.proxy_host"; /** * Attribute name of a {@link Boolean} object that represents the * the flag indicating whether the actual request has been fully transmitted * to the target host. */ public static final String HTTP_REQ_SENT = "http.request_sent"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ProtocolVersion; /** * ResponseConnControl is responsible for adding <code>Connection</code> header * to the outgoing responses, which is essential for managing persistence of * <code>HTTP/1.0</code> connections. This interceptor is recommended for * server side protocol processors. * * @since 4.0 */ public class ResponseConnControl implements HttpResponseInterceptor { public ResponseConnControl() { super(); } public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException("HTTP response may not be null"); } if (context == null) { throw new IllegalArgumentException("HTTP context may not be null"); } // Always drop connection after certain type of responses int status = response.getStatusLine().getStatusCode(); if (status == HttpStatus.SC_BAD_REQUEST || status == HttpStatus.SC_REQUEST_TIMEOUT || status == HttpStatus.SC_LENGTH_REQUIRED || status == HttpStatus.SC_REQUEST_TOO_LONG || status == HttpStatus.SC_REQUEST_URI_TOO_LONG || status == HttpStatus.SC_SERVICE_UNAVAILABLE || status == HttpStatus.SC_NOT_IMPLEMENTED) { response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); return; } // Always drop connection for HTTP/1.0 responses and below // if the content body cannot be correctly delimited HttpEntity entity = response.getEntity(); if (entity != null) { ProtocolVersion ver = response.getStatusLine().getProtocolVersion(); if (entity.getContentLength() < 0 && (!entity.isChunked() || ver.lessEquals(HttpVersion.HTTP_1_0))) { response.setHeader(HTTP.CONN_DIRECTIVE, HTTP.CONN_CLOSE); return; } } // Drop connection if requested by the client HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); if (request != null) { Header header = request.getFirstHeader(HTTP.CONN_DIRECTIVE); if (header != null) { response.setHeader(HTTP.CONN_DIRECTIVE, header.getValue()); } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseInterceptor; import org.apache.ogt.http.HttpStatus; /** * ResponseDate is responsible for adding <code>Date<c/ode> header to the * outgoing responses. This interceptor is recommended for server side protocol * processors. * * @since 4.0 */ public class ResponseDate implements HttpResponseInterceptor { private static final HttpDateGenerator DATE_GENERATOR = new HttpDateGenerator(); public ResponseDate() { super(); } public void process(final HttpResponse response, final HttpContext context) throws HttpException, IOException { if (response == null) { throw new IllegalArgumentException ("HTTP response may not be null."); } int status = response.getStatusLine().getStatusCode(); if ((status >= HttpStatus.SC_OK) && !response.containsHeader(HTTP.DATE_HEADER)) { String httpdate = DATE_GENERATOR.getCurrentDate(); response.setHeader(HTTP.DATE_HEADER, httpdate); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; /** * {@link HttpContext} implementation that delegates resolution of an attribute * to the given default {@link HttpContext} instance if the attribute is not * present in the local one. The state of the local context can be mutated, * whereas the default context is treated as read-only. * * @since 4.0 */ public final class DefaultedHttpContext implements HttpContext { private final HttpContext local; private final HttpContext defaults; public DefaultedHttpContext(final HttpContext local, final HttpContext defaults) { super(); if (local == null) { throw new IllegalArgumentException("HTTP context may not be null"); } this.local = local; this.defaults = defaults; } public Object getAttribute(final String id) { Object obj = this.local.getAttribute(id); if (obj == null) { return this.defaults.getAttribute(id); } else { return obj; } } public Object removeAttribute(final String id) { return this.local.removeAttribute(id); } public void setAttribute(final String id, final Object obj) { this.local.setAttribute(id, obj); } public HttpContext getDefaults() { return this.defaults; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.io.IOException; import org.apache.ogt.http.ConnectionReuseStrategy; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.HttpResponse; import org.apache.ogt.http.HttpResponseFactory; import org.apache.ogt.http.HttpServerConnection; import org.apache.ogt.http.HttpStatus; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.MethodNotSupportedException; import org.apache.ogt.http.ProtocolException; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.UnsupportedHttpVersionException; import org.apache.ogt.http.entity.ByteArrayEntity; import org.apache.ogt.http.params.DefaultedHttpParams; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.util.EncodingUtils; import org.apache.ogt.http.util.EntityUtils; /** * HttpService is a server side HTTP protocol handler based in the blocking * I/O model that implements the essential requirements of the HTTP protocol * for the server side message processing as described by RFC 2616. * <br> * HttpService relies on {@link HttpProcessor} to generate mandatory protocol * headers for all outgoing messages and apply common, cross-cutting message * transformations to all incoming and outgoing messages, whereas individual * {@link HttpRequestHandler}s are expected to take care of application specific * content generation and processing. * <br> * HttpService relies on {@link HttpRequestHandler} to resolve matching request * handler for a particular request URI of an incoming HTTP request. * <br> * HttpService can use optional {@link HttpExpectationVerifier} to ensure that * incoming requests meet server's expectations. * * @since 4.0 */ public class HttpService { /** * TODO: make all variables final in the next major version */ private volatile HttpParams params = null; private volatile HttpProcessor processor = null; private volatile HttpRequestHandlerResolver handlerResolver = null; private volatile ConnectionReuseStrategy connStrategy = null; private volatile HttpResponseFactory responseFactory = null; private volatile HttpExpectationVerifier expectationVerifier = null; /** * Create a new HTTP service. * * @param processor the processor to use on requests and responses * @param connStrategy the connection reuse strategy * @param responseFactory the response factory * @param handlerResolver the handler resolver. May be null. * @param expectationVerifier the expectation verifier. May be null. * @param params the HTTP parameters * * @since 4.1 */ public HttpService( final HttpProcessor processor, final ConnectionReuseStrategy connStrategy, final HttpResponseFactory responseFactory, final HttpRequestHandlerResolver handlerResolver, final HttpExpectationVerifier expectationVerifier, final HttpParams params) { super(); if (processor == null) { throw new IllegalArgumentException("HTTP processor may not be null"); } if (connStrategy == null) { throw new IllegalArgumentException("Connection reuse strategy may not be null"); } if (responseFactory == null) { throw new IllegalArgumentException("Response factory may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } this.processor = processor; this.connStrategy = connStrategy; this.responseFactory = responseFactory; this.handlerResolver = handlerResolver; this.expectationVerifier = expectationVerifier; this.params = params; } /** * Create a new HTTP service. * * @param processor the processor to use on requests and responses * @param connStrategy the connection reuse strategy * @param responseFactory the response factory * @param handlerResolver the handler resolver. May be null. * @param params the HTTP parameters * * @since 4.1 */ public HttpService( final HttpProcessor processor, final ConnectionReuseStrategy connStrategy, final HttpResponseFactory responseFactory, final HttpRequestHandlerResolver handlerResolver, final HttpParams params) { this(processor, connStrategy, responseFactory, handlerResolver, null, params); } /** * Create a new HTTP service. * * @param proc the processor to use on requests and responses * @param connStrategy the connection reuse strategy * @param responseFactory the response factory * * @deprecated use {@link HttpService#HttpService(HttpProcessor, * ConnectionReuseStrategy, HttpResponseFactory, HttpRequestHandlerResolver, HttpParams)} */ public HttpService( final HttpProcessor proc, final ConnectionReuseStrategy connStrategy, final HttpResponseFactory responseFactory) { super(); setHttpProcessor(proc); setConnReuseStrategy(connStrategy); setResponseFactory(responseFactory); } /** * @deprecated set {@link HttpProcessor} using constructor */ public void setHttpProcessor(final HttpProcessor processor) { if (processor == null) { throw new IllegalArgumentException("HTTP processor may not be null"); } this.processor = processor; } /** * @deprecated set {@link ConnectionReuseStrategy} using constructor */ public void setConnReuseStrategy(final ConnectionReuseStrategy connStrategy) { if (connStrategy == null) { throw new IllegalArgumentException("Connection reuse strategy may not be null"); } this.connStrategy = connStrategy; } /** * @deprecated set {@link HttpResponseFactory} using constructor */ public void setResponseFactory(final HttpResponseFactory responseFactory) { if (responseFactory == null) { throw new IllegalArgumentException("Response factory may not be null"); } this.responseFactory = responseFactory; } /** * @deprecated set {@link HttpResponseFactory} using constructor */ public void setParams(final HttpParams params) { this.params = params; } /** * @deprecated set {@link HttpRequestHandlerResolver} using constructor */ public void setHandlerResolver(final HttpRequestHandlerResolver handlerResolver) { this.handlerResolver = handlerResolver; } /** * @deprecated set {@link HttpExpectationVerifier} using constructor */ public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) { this.expectationVerifier = expectationVerifier; } public HttpParams getParams() { return this.params; } /** * Handles receives one HTTP request over the given connection within the * given execution context and sends a response back to the client. * * @param conn the active connection to the client * @param context the actual execution context. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ public void handleRequest( final HttpServerConnection conn, final HttpContext context) throws IOException, HttpException { context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn); HttpResponse response = null; try { HttpRequest request = conn.receiveRequestHeader(); request.setParams( new DefaultedHttpParams(request.getParams(), this.params)); ProtocolVersion ver = request.getRequestLine().getProtocolVersion(); if (!ver.lessEquals(HttpVersion.HTTP_1_1)) { // Downgrade protocol version if greater than HTTP/1.1 ver = HttpVersion.HTTP_1_1; } if (request instanceof HttpEntityEnclosingRequest) { if (((HttpEntityEnclosingRequest) request).expectContinue()) { response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_CONTINUE, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); if (this.expectationVerifier != null) { try { this.expectationVerifier.verify(request, response, context); } catch (HttpException ex) { response = this.responseFactory.newHttpResponse(HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } } if (response.getStatusLine().getStatusCode() < 200) { // Send 1xx response indicating the server expections // have been met conn.sendResponseHeader(response); conn.flush(); response = null; conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); } } else { conn.receiveRequestEntity((HttpEntityEnclosingRequest) request); } } if (response == null) { response = this.responseFactory.newHttpResponse(ver, HttpStatus.SC_OK, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); context.setAttribute(ExecutionContext.HTTP_REQUEST, request); context.setAttribute(ExecutionContext.HTTP_RESPONSE, response); this.processor.process(request, context); doService(request, response, context); } // Make sure the request content is fully consumed if (request instanceof HttpEntityEnclosingRequest) { HttpEntity entity = ((HttpEntityEnclosingRequest)request).getEntity(); EntityUtils.consume(entity); } } catch (HttpException ex) { response = this.responseFactory.newHttpResponse (HttpVersion.HTTP_1_0, HttpStatus.SC_INTERNAL_SERVER_ERROR, context); response.setParams( new DefaultedHttpParams(response.getParams(), this.params)); handleException(ex, response); } this.processor.process(response, context); conn.sendResponseHeader(response); conn.sendResponseEntity(response); conn.flush(); if (!this.connStrategy.keepAlive(response, context)) { conn.close(); } } /** * Handles the given exception and generates an HTTP response to be sent * back to the client to inform about the exceptional condition encountered * in the course of the request processing. * * @param ex the exception. * @param response the HTTP response. */ protected void handleException(final HttpException ex, final HttpResponse response) { if (ex instanceof MethodNotSupportedException) { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } else if (ex instanceof UnsupportedHttpVersionException) { response.setStatusCode(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED); } else if (ex instanceof ProtocolException) { response.setStatusCode(HttpStatus.SC_BAD_REQUEST); } else { response.setStatusCode(HttpStatus.SC_INTERNAL_SERVER_ERROR); } byte[] msg = EncodingUtils.getAsciiBytes(ex.getMessage()); ByteArrayEntity entity = new ByteArrayEntity(msg); entity.setContentType("text/plain; charset=US-ASCII"); response.setEntity(entity); } /** * The default implementation of this method attempts to resolve an * {@link HttpRequestHandler} for the request URI of the given request * and, if found, executes its * {@link HttpRequestHandler#handle(HttpRequest, HttpResponse, HttpContext)} * method. * <p> * Super-classes can override this method in order to provide a custom * implementation of the request processing logic. * * @param request the HTTP request. * @param response the HTTP response. * @param context the execution context. * @throws IOException in case of an I/O error. * @throws HttpException in case of HTTP protocol violation or a processing * problem. */ protected void doService( final HttpRequest request, final HttpResponse response, final HttpContext context) throws HttpException, IOException { HttpRequestHandler handler = null; if (this.handlerResolver != null) { String requestURI = request.getRequestLine().getUri(); handler = this.handlerResolver.lookup(requestURI); } if (handler != null) { handler.handle(request, response, context); } else { response.setStatusCode(HttpStatus.SC_NOT_IMPLEMENTED); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.util.HashMap; import java.util.Iterator; import java.util.Map; /** * Maintains a map of objects keyed by a request URI pattern. * <br> * Patterns may have three formats: * <ul> * <li><code>*</code></li> * <li><code>*&lt;uri&gt;</code></li> * <li><code>&lt;uri&gt;*</code></li> * </ul> * <br> * This class can be used to resolve an object matching a particular request * URI. * * @since 4.0 */ public class UriPatternMatcher { /** * TODO: Replace with ConcurrentHashMap */ private final Map map; public UriPatternMatcher() { super(); this.map = new HashMap(); } /** * Registers the given object for URIs matching the given pattern. * * @param pattern the pattern to register the handler for. * @param obj the object. */ public synchronized void register(final String pattern, final Object obj) { if (pattern == null) { throw new IllegalArgumentException("URI request pattern may not be null"); } this.map.put(pattern, obj); } /** * Removes registered object, if exists, for the given pattern. * * @param pattern the pattern to unregister. */ public synchronized void unregister(final String pattern) { if (pattern == null) { return; } this.map.remove(pattern); } /** * @deprecated use {@link #setObjects(Map)} */ public synchronized void setHandlers(final Map map) { if (map == null) { throw new IllegalArgumentException("Map of handlers may not be null"); } this.map.clear(); this.map.putAll(map); } /** * Sets objects from the given map. * @param map the map containing objects keyed by their URI patterns. */ public synchronized void setObjects(final Map map) { if (map == null) { throw new IllegalArgumentException("Map of handlers may not be null"); } this.map.clear(); this.map.putAll(map); } /** * Looks up an object matching the given request URI. * * @param requestURI the request URI * @return object or <code>null</code> if no match is found. */ public synchronized Object lookup(String requestURI) { if (requestURI == null) { throw new IllegalArgumentException("Request URI may not be null"); } //Strip away the query part part if found int index = requestURI.indexOf("?"); if (index != -1) { requestURI = requestURI.substring(0, index); } // direct match? Object obj = this.map.get(requestURI); if (obj == null) { // pattern match? String bestMatch = null; for (Iterator it = this.map.keySet().iterator(); it.hasNext();) { String pattern = (String) it.next(); if (matchUriRequestPattern(pattern, requestURI)) { // we have a match. is it any better? if (bestMatch == null || (bestMatch.length() < pattern.length()) || (bestMatch.length() == pattern.length() && pattern.endsWith("*"))) { obj = this.map.get(pattern); bestMatch = pattern; } } } } return obj; } /** * Tests if the given request URI matches the given pattern. * * @param pattern the pattern * @param requestUri the request URI * @return <code>true</code> if the request URI matches the pattern, * <code>false</code> otherwise. */ protected boolean matchUriRequestPattern(final String pattern, final String requestUri) { if (pattern.equals("*")) { return true; } else { return (pattern.endsWith("*") && requestUri.startsWith(pattern.substring(0, pattern.length() - 1))) || (pattern.startsWith("*") && requestUri.endsWith(pattern.substring(1, pattern.length()))); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.protocol; import java.util.HashMap; import java.util.Map; /** * Default implementation of {@link HttpContext}. * <p> * Please note methods of this class are not synchronized and therefore may * be threading unsafe. * * @since 4.0 */ public class BasicHttpContext implements HttpContext { private final HttpContext parentContext; private Map map = null; public BasicHttpContext() { this(null); } public BasicHttpContext(final HttpContext parentContext) { super(); this.parentContext = parentContext; } public Object getAttribute(final String id) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } Object obj = null; if (this.map != null) { obj = this.map.get(id); } if (obj == null && this.parentContext != null) { obj = this.parentContext.getAttribute(id); } return obj; } public void setAttribute(final String id, final Object obj) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } if (this.map == null) { this.map = new HashMap(); } this.map.put(id, obj); } public Object removeAttribute(final String id) { if (id == null) { throw new IllegalArgumentException("Id may not be null"); } if (this.map != null) { return this.map.remove(id); } else { return null; } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; /** * Signals that the target server failed to respond with a valid HTTP response. * * @since 4.0 */ public class NoHttpResponseException extends IOException { private static final long serialVersionUID = -7658940387386078766L; /** * Creates a new NoHttpResponseException with the specified detail message. * * @param message exception message */ public NoHttpResponseException(String message) { super(message); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.util.Iterator; /** * A type-safe iterator for {@link HeaderElement} objects. * * @since 4.0 */ public interface HeaderElementIterator extends Iterator { /** * Indicates whether there is another header element in this * iteration. * * @return <code>true</code> if there is another header element, * <code>false</code> otherwise */ boolean hasNext(); /** * Obtains the next header element from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next header element in this iteration */ HeaderElement nextElement(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * An entity that can be sent or received with an HTTP message. * Entities can be found in some * {@link HttpEntityEnclosingRequest requests} and in * {@link HttpResponse responses}, where they are optional. * <p> * There are three distinct types of entities in HttpCore, * depending on where their {@link #getContent content} originates: * <ul> * <li><b>streamed</b>: The content is received from a stream, or * generated on the fly. In particular, this category includes * entities being received from a {@link HttpConnection connection}. * {@link #isStreaming Streamed} entities are generally not * {@link #isRepeatable repeatable}. * </li> * <li><b>self-contained</b>: The content is in memory or obtained by * means that are independent from a connection or other entity. * Self-contained entities are generally {@link #isRepeatable repeatable}. * </li> * <li><b>wrapping</b>: The content is obtained from another entity. * </li> * </ul> * This distinction is important for connection management with incoming * entities. For entities that are created by an application and only sent * using the HTTP components framework, the difference between streamed * and self-contained is of little importance. In that case, it is suggested * to consider non-repeatable entities as streamed, and those that are * repeatable (without a huge effort) as self-contained. * * @since 4.0 */ public interface HttpEntity { /** * Tells if the entity is capable of producing its data more than once. * A repeatable entity's getContent() and writeTo(OutputStream) methods * can be called more than once whereas a non-repeatable entity's can not. * @return true if the entity is repeatable, false otherwise. */ boolean isRepeatable(); /** * Tells about chunked encoding for this entity. * The primary purpose of this method is to indicate whether * chunked encoding should be used when the entity is sent. * For entities that are received, it can also indicate whether * the entity was received with chunked encoding. * <br/> * The behavior of wrapping entities is implementation dependent, * but should respect the primary purpose. * * @return <code>true</code> if chunked encoding is preferred for this * entity, or <code>false</code> if it is not */ boolean isChunked(); /** * Tells the length of the content, if known. * * @return the number of bytes of the content, or * a negative number if unknown. If the content length is known * but exceeds {@link java.lang.Long#MAX_VALUE Long.MAX_VALUE}, * a negative number is returned. */ long getContentLength(); /** * Obtains the Content-Type header, if known. * This is the header that should be used when sending the entity, * or the one that was received with the entity. It can include a * charset attribute. * * @return the Content-Type header for this entity, or * <code>null</code> if the content type is unknown */ Header getContentType(); /** * Obtains the Content-Encoding header, if known. * This is the header that should be used when sending the entity, * or the one that was received with the entity. * Wrapping entities that modify the content encoding should * adjust this header accordingly. * * @return the Content-Encoding header for this entity, or * <code>null</code> if the content encoding is unknown */ Header getContentEncoding(); /** * Returns a content stream of the entity. * {@link #isRepeatable Repeatable} entities are expected * to create a new instance of {@link InputStream} for each invocation * of this method and therefore can be consumed multiple times. * Entities that are not {@link #isRepeatable repeatable} are expected * to return the same {@link InputStream} instance and therefore * may not be consumed more than once. * <p> * IMPORTANT: Please note all entity implementations must ensure that * all allocated resources are properly deallocated after * the {@link InputStream#close()} method is invoked. * * @return content stream of the entity. * * @throws IOException if the stream could not be created * @throws IllegalStateException * if content stream cannot be created. * * @see #isRepeatable() */ InputStream getContent() throws IOException, IllegalStateException; /** * Writes the entity content out to the output stream. * <p> * <p> * IMPORTANT: Please note all entity implementations must ensure that * all allocated resources are properly deallocated when this method * returns. * * @param outstream the output stream to write entity content to * * @throws IOException if an I/O error occurs */ void writeTo(OutputStream outstream) throws IOException; /** * Tells whether this entity depends on an underlying stream. * Streamed entities that read data directly from the socket should * return <code>true</code>. Self-contained entities should return * <code>false</code>. Wrapping entities should delegate this call * to the wrapped entity. * * @return <code>true</code> if the entity content is streamed, * <code>false</code> otherwise */ boolean isStreaming(); // don't expect an exception here /** * This method is deprecated since version 4.1. Please use standard * java convention to ensure resource deallocation by calling * {@link InputStream#close()} on the input stream returned by * {@link #getContent()} * <p> * This method is called to indicate that the content of this entity * is no longer required. All entity implementations are expected to * release all allocated resources as a result of this method * invocation. Content streaming entities are also expected to * dispose of the remaining content, if any. Wrapping entities should * delegate this call to the wrapped entity. * <p> * This method is of particular importance for entities being * received from a {@link HttpConnection connection}. The entity * needs to be consumed completely in order to re-use the connection * with keep-alive. * * @throws IOException if an I/O error occurs. * * @deprecated Use {@link org.apache.ogt.http.util.EntityUtils#consume(HttpEntity)} * * @see #getContent() and #writeTo(OutputStream) */ void consumeContent() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; /** * A generic HTTP connection, useful on client and server side. * * @since 4.0 */ public interface HttpConnection { /** * Closes this connection gracefully. * This method will attempt to flush the internal output * buffer prior to closing the underlying socket. * This method MUST NOT be called from a different thread to force * shutdown of the connection. Use {@link #shutdown shutdown} instead. */ public void close() throws IOException; /** * Checks if this connection is open. * @return true if it is open, false if it is closed. */ public boolean isOpen(); /** * Checks whether this connection has gone down. * Network connections may get closed during some time of inactivity * for several reasons. The next time a read is attempted on such a * connection it will throw an IOException. * This method tries to alleviate this inconvenience by trying to * find out if a connection is still usable. Implementations may do * that by attempting a read with a very small timeout. Thus this * method may block for a small amount of time before returning a result. * It is therefore an <i>expensive</i> operation. * * @return <code>true</code> if attempts to use this connection are * likely to succeed, or <code>false</code> if they are likely * to fail and this connection should be closed */ public boolean isStale(); /** * Sets the socket timeout value. * * @param timeout timeout value in milliseconds */ void setSocketTimeout(int timeout); /** * Returns the socket timeout value. * * @return positive value in milliseconds if a timeout is set, * <code>0</code> if timeout is disabled or <code>-1</code> if * timeout is undefined. */ int getSocketTimeout(); /** * Force-closes this connection. * This is the only method of a connection which may be called * from a different thread to terminate the connection. * This method will not attempt to flush the transmitter's * internal buffer prior to closing the underlying socket. */ public void shutdown() throws IOException; /** * Returns a collection of connection metrics. * * @return HttpConnectionMetrics */ HttpConnectionMetrics getMetrics(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import org.apache.ogt.http.util.ExceptionUtils; /** * Signals that an HTTP exception has occurred. * * @since 4.0 */ public class HttpException extends Exception { private static final long serialVersionUID = -5437299376222011036L; /** * Creates a new HttpException with a <tt>null</tt> detail message. */ public HttpException() { super(); } /** * Creates a new HttpException with the specified detail message. * * @param message the exception detail message */ public HttpException(final String message) { super(message); } /** * Creates a new HttpException with the specified detail message and cause. * * @param message the exception detail message * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt> * if the cause is unavailable, unknown, or not a <tt>Throwable</tt> */ public HttpException(final String message, final Throwable cause) { super(message); ExceptionUtils.initCause(this, cause); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import org.apache.ogt.http.protocol.HttpContext; /** * Interface for deciding whether a connection can be re-used for * subsequent requests and should be kept alive. * <p> * Implementations of this interface must be thread-safe. Access to shared * data must be synchronized as methods of this interface may be executed * from multiple threads. * * @since 4.0 */ public interface ConnectionReuseStrategy { /** * Decides whether a connection can be kept open after a request. * If this method returns <code>false</code>, the caller MUST * close the connection to correctly comply with the HTTP protocol. * If it returns <code>true</code>, the caller SHOULD attempt to * keep the connection open for reuse with another request. * <br/> * One can use the HTTP context to retrieve additional objects that * may be relevant for the keep-alive strategy: the actual HTTP * connection, the original HTTP request, target host if known, * number of times the connection has been reused already and so on. * <br/> * If the connection is already closed, <code>false</code> is returned. * The stale connection check MUST NOT be triggered by a * connection reuse strategy. * * @param response * The last response received over that connection. * @param context the context in which the connection is being * used. * * @return <code>true</code> if the connection is allowed to be reused, or * <code>false</code> if it MUST NOT be reused */ boolean keepAlive(HttpResponse response, HttpContext context); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.util.Iterator; /** * An iterator for {@link String} tokens. * This interface is designed as a complement to * {@link HeaderElementIterator}, in cases where the items * are plain strings rather than full header elements. * * @since 4.0 */ public interface TokenIterator extends Iterator { /** * Indicates whether there is another token in this iteration. * * @return <code>true</code> if there is another token, * <code>false</code> otherwise */ boolean hasNext(); /** * Obtains the next token from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next token in this iteration */ String nextToken(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; import org.apache.ogt.http.protocol.HttpContext; /** * HTTP protocol interceptor is a routine that implements a specific aspect of * the HTTP protocol. Usually protocol interceptors are expected to act upon * one specific header or a group of related headers of the incoming message * or populate the outgoing message with one specific header or a group of * related headers. Protocol * <p> * Interceptors can also manipulate content entities enclosed with messages. * Usually this is accomplished by using the 'Decorator' pattern where a wrapper * entity class is used to decorate the original entity. * <p> * Protocol interceptors must be implemented as thread-safe. Similarly to * servlets, protocol interceptors should not use instance variables unless * access to those variables is synchronized. * * @since 4.0 */ public interface HttpResponseInterceptor { /** * Processes a response. * On the server side, this step is performed before the response is * sent to the client. On the client side, this step is performed * on incoming messages before the message body is evaluated. * * @param response the response to postprocess * @param context the context for the request * * @throws HttpException in case of an HTTP protocol violation * @throws IOException in case of an I/O error */ void process(HttpResponse response, HttpContext context) throws HttpException, IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import org.apache.ogt.http.ProtocolException; /** * Signals an unsupported version of the HTTP protocol. * * @since 4.0 */ public class UnsupportedHttpVersionException extends ProtocolException { private static final long serialVersionUID = -1348448090193107031L; /** * Creates an exception without a detail message. */ public UnsupportedHttpVersionException() { super(); } /** * Creates an exception with the specified detail message. * * @param message The exception detail message */ public UnsupportedHttpVersionException(final String message) { super(message); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; /** * Base class for wrapping entities. * Keeps a {@link #wrappedEntity wrappedEntity} and delegates all * calls to it. Implementations of wrapping entities can derive * from this class and need to override only those methods that * should not be delegated to the wrapped entity. * * @since 4.0 */ public class HttpEntityWrapper implements HttpEntity { /** The wrapped entity. */ protected HttpEntity wrappedEntity; /** * Creates a new entity wrapper. * * @param wrapped the entity to wrap, not null * @throws IllegalArgumentException if wrapped is null */ public HttpEntityWrapper(HttpEntity wrapped) { super(); if (wrapped == null) { throw new IllegalArgumentException ("wrapped entity must not be null"); } wrappedEntity = wrapped; } // constructor public boolean isRepeatable() { return wrappedEntity.isRepeatable(); } public boolean isChunked() { return wrappedEntity.isChunked(); } public long getContentLength() { return wrappedEntity.getContentLength(); } public Header getContentType() { return wrappedEntity.getContentType(); } public Header getContentEncoding() { return wrappedEntity.getContentEncoding(); } public InputStream getContent() throws IOException { return wrappedEntity.getContent(); } public void writeTo(OutputStream outstream) throws IOException { wrappedEntity.writeTo(outstream); } public boolean isStreaming() { return wrappedEntity.isStreaming(); } /** * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { wrappedEntity.consumeContent(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import org.apache.ogt.http.protocol.HTTP; /** * A self contained, repeatable entity that obtains its content from * a {@link String}. * * @since 4.0 */ public class StringEntity extends AbstractHttpEntity implements Cloneable { protected final byte[] content; /** * Creates a StringEntity with the specified content, mimetype and charset * * @param string content to be used. Not {@code null}. * @param mimeType mime type to be used. May be {@code null}, in which case the default is {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain" * @param charset character set to be used. May be {@code null}, in which case the default is {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1" * * @since 4.1 * @throws IllegalArgumentException if the string parameter is null */ public StringEntity(final String string, String mimeType, String charset) throws UnsupportedEncodingException { super(); if (string == null) { throw new IllegalArgumentException("Source string may not be null"); } if (mimeType == null) { mimeType = HTTP.PLAIN_TEXT_TYPE; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } this.content = string.getBytes(charset); setContentType(mimeType + HTTP.CHARSET_PARAM + charset); } /** * Creates a StringEntity with the specified content and charset. * <br/> * The mime type defaults to {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain". * * @param string content to be used. Not {@code null}. * @param charset character set to be used. May be {@code null}, in which case the default is {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1" * * @throws IllegalArgumentException if the string parameter is null */ public StringEntity(final String string, String charset) throws UnsupportedEncodingException { this(string, null, charset); } /** * Creates a StringEntity with the specified content and charset. * <br/> * The charset defaults to {@link HTTP#DEFAULT_CONTENT_CHARSET} i.e. "ISO-8859-1". * <br/> * The mime type defaults to {@link HTTP#PLAIN_TEXT_TYPE} i.e. "text/plain". * * @param string content to be used. Not {@code null}. * * @throws IllegalArgumentException if the string parameter is null */ public StringEntity(final String string) throws UnsupportedEncodingException { this(string, null); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.content.length; } public InputStream getContent() throws IOException { return new ByteArrayInputStream(this.content); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } outstream.write(this.content); outstream.flush(); } /** * Tells that this entity is not streaming. * * @return <code>false</code> */ public boolean isStreaming() { return false; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class StringEntity
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * Entity that delegates the process of content generation * to a {@link ContentProducer}. * * @since 4.0 */ public class EntityTemplate extends AbstractHttpEntity { private final ContentProducer contentproducer; public EntityTemplate(final ContentProducer contentproducer) { super(); if (contentproducer == null) { throw new IllegalArgumentException("Content producer may not be null"); } this.contentproducer = contentproducer; } public long getContentLength() { return -1; } public InputStream getContent() { throw new UnsupportedOperationException("Entity template does not implement getContent()"); } public boolean isRepeatable() { return true; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } this.contentproducer.writeTo(outstream); } public boolean isStreaming() { return false; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.IOException; import java.io.OutputStream; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.message.BasicHeader; import org.apache.ogt.http.protocol.HTTP; /** * Abstract base class for entities. * Provides the commonly used attributes for streamed and self-contained * implementations of {@link HttpEntity HttpEntity}. * * @since 4.0 */ public abstract class AbstractHttpEntity implements HttpEntity { protected Header contentType; protected Header contentEncoding; protected boolean chunked; /** * Protected default constructor. * The contentType, contentEncoding and chunked attributes of the created object are set to * <code>null</code>, <code>null</code> and <code>false</code>, respectively. */ protected AbstractHttpEntity() { super(); } /** * Obtains the Content-Type header. * The default implementation returns the value of the * {@link #contentType contentType} attribute. * * @return the Content-Type header, or <code>null</code> */ public Header getContentType() { return this.contentType; } /** * Obtains the Content-Encoding header. * The default implementation returns the value of the * {@link #contentEncoding contentEncoding} attribute. * * @return the Content-Encoding header, or <code>null</code> */ public Header getContentEncoding() { return this.contentEncoding; } /** * Obtains the 'chunked' flag. * The default implementation returns the value of the * {@link #chunked chunked} attribute. * * @return the 'chunked' flag */ public boolean isChunked() { return this.chunked; } /** * Specifies the Content-Type header. * The default implementation sets the value of the * {@link #contentType contentType} attribute. * * @param contentType the new Content-Encoding header, or * <code>null</code> to unset */ public void setContentType(final Header contentType) { this.contentType = contentType; } /** * Specifies the Content-Type header, as a string. * The default implementation calls * {@link #setContentType(Header) setContentType(Header)}. * * @param ctString the new Content-Type header, or * <code>null</code> to unset */ public void setContentType(final String ctString) { Header h = null; if (ctString != null) { h = new BasicHeader(HTTP.CONTENT_TYPE, ctString); } setContentType(h); } /** * Specifies the Content-Encoding header. * The default implementation sets the value of the * {@link #contentEncoding contentEncoding} attribute. * * @param contentEncoding the new Content-Encoding header, or * <code>null</code> to unset */ public void setContentEncoding(final Header contentEncoding) { this.contentEncoding = contentEncoding; } /** * Specifies the Content-Encoding header, as a string. * The default implementation calls * {@link #setContentEncoding(Header) setContentEncoding(Header)}. * * @param ceString the new Content-Encoding header, or * <code>null</code> to unset */ public void setContentEncoding(final String ceString) { Header h = null; if (ceString != null) { h = new BasicHeader(HTTP.CONTENT_ENCODING, ceString); } setContentEncoding(h); } /** * Specifies the 'chunked' flag. * <p> * Note that the chunked setting is a hint only. * If using HTTP/1.0, chunking is never performed. * Otherwise, even if chunked is false, HttpClient must * use chunk coding if the entity content length is * unknown (-1). * <p> * The default implementation sets the value of the * {@link #chunked chunked} attribute. * * @param b the new 'chunked' flag */ public void setChunked(boolean b) { this.chunked = b; } /** * The default implementation does not consume anything. * * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A self contained, repeatable entity that obtains its content from a byte array. * * @since 4.0 */ public class ByteArrayEntity extends AbstractHttpEntity implements Cloneable { protected final byte[] content; public ByteArrayEntity(final byte[] b) { super(); if (b == null) { throw new IllegalArgumentException("Source byte array may not be null"); } this.content = b; } public boolean isRepeatable() { return true; } public long getContentLength() { return this.content.length; } public InputStream getContent() { return new ByteArrayInputStream(this.content); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } outstream.write(this.content); outstream.flush(); } /** * Tells that this entity is not streaming. * * @return <code>false</code> */ public boolean isStreaming() { return false; } public Object clone() throws CloneNotSupportedException { return super.clone(); } } // class ByteArrayEntity
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A generic streamed, non-repeatable entity that obtains its content * from an {@link InputStream}. * * @since 4.0 */ public class BasicHttpEntity extends AbstractHttpEntity { private InputStream content; private long length; /** * Creates a new basic entity. * The content is initially missing, the content length * is set to a negative number. */ public BasicHttpEntity() { super(); this.length = -1; } public long getContentLength() { return this.length; } /** * Obtains the content, once only. * * @return the content, if this is the first call to this method * since {@link #setContent setContent} has been called * * @throws IllegalStateException * if the content has not been provided */ public InputStream getContent() throws IllegalStateException { if (this.content == null) { throw new IllegalStateException("Content has not been provided"); } return this.content; } /** * Tells that this entity is not repeatable. * * @return <code>false</code> */ public boolean isRepeatable() { return false; } /** * Specifies the length of the content. * * @param len the number of bytes in the content, or * a negative number to indicate an unknown length */ public void setContentLength(long len) { this.length = len; } /** * Specifies the content. * * @param instream the stream to return with the next call to * {@link #getContent getContent} */ public void setContent(final InputStream instream) { this.content = instream; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = getContent(); try { int l; byte[] tmp = new byte[2048]; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } } finally { instream.close(); } } public boolean isStreaming() { return this.content != null; } /** * Closes the content InputStream. * * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { if (content != null) { content.close(); // reads to the end of the entity } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A streamed, non-repeatable entity that obtains its content from * an {@link InputStream}. * * @since 4.0 */ public class InputStreamEntity extends AbstractHttpEntity { private final static int BUFFER_SIZE = 2048; private final InputStream content; private final long length; public InputStreamEntity(final InputStream instream, long length) { super(); if (instream == null) { throw new IllegalArgumentException("Source input stream may not be null"); } this.content = instream; this.length = length; } public boolean isRepeatable() { return false; } public long getContentLength() { return this.length; } public InputStream getContent() throws IOException { return this.content; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = this.content; try { byte[] buffer = new byte[BUFFER_SIZE]; int l; if (this.length < 0) { // consume until EOF while ((l = instream.read(buffer)) != -1) { outstream.write(buffer, 0, l); } } else { // consume no more than length long remaining = this.length; while (remaining > 0) { l = instream.read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining)); if (l == -1) { break; } outstream.write(buffer, 0, l); remaining -= l; } } } finally { instream.close(); } } public boolean isStreaming() { return true; } /** * @deprecated Either use {@link #getContent()} and call {@link java.io.InputStream#close()} on that; * otherwise call {@link #writeTo(OutputStream)} which is required to free the resources. */ public void consumeContent() throws IOException { // If the input stream is from a connection, closing it will read to // the end of the content. Otherwise, we don't care what it does. this.content.close(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.io.Serializable; /** * A streamed entity that obtains its content from a {@link Serializable}. * The content obtained from the {@link Serializable} instance can * optionally be buffered in a byte array in order to make the * entity self-contained and repeatable. * * @since 4.0 */ public class SerializableEntity extends AbstractHttpEntity { private byte[] objSer; private Serializable objRef; /** * Creates new instance of this class. * * @param ser input * @param bufferize tells whether the content should be * stored in an internal buffer * @throws IOException in case of an I/O error */ public SerializableEntity(Serializable ser, boolean bufferize) throws IOException { super(); if (ser == null) { throw new IllegalArgumentException("Source object may not be null"); } if (bufferize) { createBytes(ser); } else { this.objRef = ser; } } private void createBytes(Serializable ser) throws IOException { ByteArrayOutputStream baos = new ByteArrayOutputStream(); ObjectOutputStream out = new ObjectOutputStream(baos); out.writeObject(ser); out.flush(); this.objSer = baos.toByteArray(); } public InputStream getContent() throws IOException, IllegalStateException { if (this.objSer == null) { createBytes(this.objRef); } return new ByteArrayInputStream(this.objSer); } public long getContentLength() { if (this.objSer == null) { return -1; } else { return this.objSer.length; } } public boolean isRepeatable() { return true; } public boolean isStreaming() { return this.objSer == null; } public void writeTo(OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } if (this.objSer == null) { ObjectOutputStream out = new ObjectOutputStream(outstream); out.writeObject(this.objRef); out.flush(); } else { outstream.write(this.objSer); outstream.flush(); } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; /** * A self contained, repeatable entity that obtains its content from a file. * * @since 4.0 */ public class FileEntity extends AbstractHttpEntity implements Cloneable { protected final File file; public FileEntity(final File file, final String contentType) { super(); if (file == null) { throw new IllegalArgumentException("File may not be null"); } this.file = file; setContentType(contentType); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.file.length(); } public InputStream getContent() throws IOException { return new FileInputStream(this.file); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = new FileInputStream(this.file); try { byte[] tmp = new byte[4096]; int l; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } outstream.flush(); } finally { instream.close(); } } /** * Tells that this entity is not streaming. * * @return <code>false</code> */ public boolean isStreaming() { return false; } public Object clone() throws CloneNotSupportedException { // File instance is considered immutable // No need to make a copy of it return super.clone(); } } // class FileEntity
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.IOException; import java.io.OutputStream; /** * An abstract entity content producer. *<p>Content producers are expected to be able to produce their * content multiple times</p> * * @since 4.0 */ public interface ContentProducer { void writeTo(OutputStream outstream) throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; /** * Represents a strategy to determine length of the enclosed content entity * based on properties of the HTTP message. * * @since 4.0 */ public interface ContentLengthStrategy { public static final int IDENTITY = -1; public static final int CHUNKED = -2; /** * Returns length of the given message in bytes. The returned value * must be a non-negative number, {@link #IDENTITY} if the end of the * message will be delimited by the end of connection, or {@link #CHUNKED} * if the message is chunk coded * * @param message * @return content length, {@link #IDENTITY}, or {@link #CHUNKED} * * @throws HttpException in case of HTTP protocol violation */ long determineLength(HttpMessage message) throws HttpException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.util.EntityUtils; /** * A wrapping entity that buffers it content if necessary. * The buffered entity is always repeatable. * If the wrapped entity is repeatable itself, calls are passed through. * If the wrapped entity is not repeatable, the content is read into a * buffer once and provided from there as often as required. * * @since 4.0 */ public class BufferedHttpEntity extends HttpEntityWrapper { private final byte[] buffer; /** * Creates a new buffered entity wrapper. * * @param entity the entity to wrap, not null * @throws IllegalArgumentException if wrapped is null */ public BufferedHttpEntity(final HttpEntity entity) throws IOException { super(entity); if (!entity.isRepeatable() || entity.getContentLength() < 0) { this.buffer = EntityUtils.toByteArray(entity); } else { this.buffer = null; } } public long getContentLength() { if (this.buffer != null) { return this.buffer.length; } else { return wrappedEntity.getContentLength(); } } public InputStream getContent() throws IOException { if (this.buffer != null) { return new ByteArrayInputStream(this.buffer); } else { return wrappedEntity.getContent(); } } /** * Tells that this entity does not have to be chunked. * * @return <code>false</code> */ public boolean isChunked() { return (buffer == null) && wrappedEntity.isChunked(); } /** * Tells that this entity is repeatable. * * @return <code>true</code> */ public boolean isRepeatable() { return true; } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } if (this.buffer != null) { outstream.write(this.buffer); } else { wrappedEntity.writeTo(outstream); } } // non-javadoc, see interface HttpEntity public boolean isStreaming() { return (buffer == null) && wrappedEntity.isStreaming(); } } // class BufferedHttpEntity
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * Signals a parse error. * Parse errors when receiving a message will typically trigger * {@link ProtocolException}. Parse errors that do not occur during * protocol execution may be handled differently. * This is an unchecked exception, since there are cases where * the data to be parsed has been generated and is therefore * known to be parseable. * * @since 4.0 */ public class ParseException extends RuntimeException { private static final long serialVersionUID = -7288819855864183578L; /** * Creates a {@link ParseException} without details. */ public ParseException() { super(); } /** * Creates a {@link ParseException} with a detail message. * * @param message the exception detail message, or <code>null</code> */ public ParseException(String message) { super(message); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.util.Iterator; /** * A type-safe iterator for {@link Header} objects. * * @since 4.0 */ public interface HeaderIterator extends Iterator { /** * Indicates whether there is another header in this iteration. * * @return <code>true</code> if there is another header, * <code>false</code> otherwise */ boolean hasNext(); /** * Obtains the next header from this iteration. * This method should only be called while {@link #hasNext hasNext} * is true. * * @return the next header in this iteration */ Header nextHeader(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; /** * A server-side HTTP connection, which can be used for receiving * requests and sending responses. * * @since 4.0 */ public interface HttpServerConnection extends HttpConnection { /** * Receives the request line and all headers available from this connection. * The caller should examine the returned request and decide if to receive a * request entity as well. * * @return a new HttpRequest object whose request line and headers are * initialized. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ HttpRequest receiveRequestHeader() throws HttpException, IOException; /** * Receives the next request entity available from this connection and attaches it to * an existing request. * @param request the request to attach the entity to. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void receiveRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException; /** * Sends the response line and headers of a response over this connection. * @param response the response whose headers to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendResponseHeader(HttpResponse response) throws HttpException, IOException; /** * Sends the response entity of a response over this connection. * @param response the response whose entity to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendResponseEntity(HttpResponse response) throws HttpException, IOException; /** * Sends all pending buffered data over this connection. * @throws IOException in case of an I/O error */ void flush() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * Signals a truncated chunk in a chunked stream. * * @since 4.1 */ public class TruncatedChunkException extends MalformedChunkCodingException { private static final long serialVersionUID = -23506263930279460L; /** * Creates a TruncatedChunkException with the specified detail message. * * @param message The exception detail message */ public TruncatedChunkException(final String message) { super(message); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import org.apache.ogt.http.util.CharArrayBuffer; /** * An HTTP header which is already formatted. * For example when headers are received, the original formatting * can be preserved. This allows for the header to be sent without * another formatting step. * * @since 4.0 */ public interface FormattedHeader extends Header { /** * Obtains the buffer with the formatted header. * The returned buffer MUST NOT be modified. * * @return the formatted header, in a buffer that must not be modified */ CharArrayBuffer getBuffer(); /** * Obtains the start of the header value in the {@link #getBuffer buffer}. * By accessing the value in the buffer, creation of a temporary string * can be avoided. * * @return index of the first character of the header value * in the buffer returned by {@link #getBuffer getBuffer}. */ int getValuePos(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * Represents an HTTP header field. * * <p>The HTTP header fields follow the same generic format as * that given in Section 3.1 of RFC 822. Each header field consists * of a name followed by a colon (":") and the field value. Field names * are case-insensitive. The field value MAY be preceded by any amount * of LWS, though a single SP is preferred. * *<pre> * message-header = field-name ":" [ field-value ] * field-name = token * field-value = *( field-content | LWS ) * field-content = &lt;the OCTETs making up the field-value * and consisting of either *TEXT or combinations * of token, separators, and quoted-string&gt; *</pre> * * @since 4.0 */ public interface Header { /** * Get the name of the Header. * * @return the name of the Header, never {@code null} */ String getName(); /** * Get the value of the Header. * * @return the value of the Header, may be {@code null} */ String getValue(); /** * Parses the value. * * @return an array of {@link HeaderElement} entries, may be empty, but is never {@code null} * @throws ParseException */ HeaderElement[] getElements() throws ParseException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.Serializable; /** * Represents an HTTP version. HTTP uses a "major.minor" numbering * scheme to indicate versions of the protocol. * <p> * The version of an HTTP message is indicated by an HTTP-Version field * in the first line of the message. * </p> * <pre> * HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT * </pre> * * @since 4.0 */ public final class HttpVersion extends ProtocolVersion implements Serializable { private static final long serialVersionUID = -5856653513894415344L; /** The protocol name. */ public static final String HTTP = "HTTP"; /** HTTP protocol version 0.9 */ public static final HttpVersion HTTP_0_9 = new HttpVersion(0, 9); /** HTTP protocol version 1.0 */ public static final HttpVersion HTTP_1_0 = new HttpVersion(1, 0); /** HTTP protocol version 1.1 */ public static final HttpVersion HTTP_1_1 = new HttpVersion(1, 1); /** * Create an HTTP protocol version designator. * * @param major the major version number of the HTTP protocol * @param minor the minor version number of the HTTP protocol * * @throws IllegalArgumentException if either major or minor version number is negative */ public HttpVersion(int major, int minor) { super(HTTP, major, minor); } /** * Obtains a specific HTTP version. * * @param major the major version * @param minor the minor version * * @return an instance of {@link HttpVersion} with the argument version */ public ProtocolVersion forVersion(int major, int minor) { if ((major == this.major) && (minor == this.minor)) { return this; } if (major == 1) { if (minor == 0) { return HTTP_1_0; } if (minor == 1) { return HTTP_1_1; } } if ((major == 0) && (minor == 9)) { return HTTP_0_9; } // argument checking is done in the constructor return new HttpVersion(major, minor); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.util.Locale; /** * Interface for obtaining reason phrases for HTTP status codes. * * @since 4.0 */ public interface ReasonPhraseCatalog { /** * Obtains the reason phrase for a status code. * The optional context allows for catalogs that detect * the language for the reason phrase. * * @param status the status code, in the range 100-599 * @param loc the preferred locale for the reason phrase * * @return the reason phrase, or <code>null</code> if unknown */ public String getReason(int status, Locale loc); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; /** * Signals that the connection has been closed unexpectedly. * * @since 4.0 */ public class ConnectionClosedException extends IOException { private static final long serialVersionUID = 617550366255636674L; /** * Creates a new ConnectionClosedException with the specified detail message. * * @param message The exception detail message */ public ConnectionClosedException(final String message) { super(message); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * Constants enumerating the HTTP headers. All headers defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and RFC2518 * (WebDAV) are listed. * * @since 4.1 */ public final class HttpHeaders { private HttpHeaders() { } /** RFC 2616 (HTTP/1.1) Section 14.1 */ public static final String ACCEPT = "Accept"; /** RFC 2616 (HTTP/1.1) Section 14.2 */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** RFC 2616 (HTTP/1.1) Section 14.3 */ public static final String ACCEPT_ENCODING = "Accept-Encoding"; /** RFC 2616 (HTTP/1.1) Section 14.4 */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** RFC 2616 (HTTP/1.1) Section 14.5 */ public static final String ACCEPT_RANGES = "Accept-Ranges"; /** RFC 2616 (HTTP/1.1) Section 14.6 */ public static final String AGE = "Age"; /** RFC 1945 (HTTP/1.0) Section 10.1, RFC 2616 (HTTP/1.1) Section 14.7 */ public static final String ALLOW = "Allow"; /** RFC 1945 (HTTP/1.0) Section 10.2, RFC 2616 (HTTP/1.1) Section 14.8 */ public static final String AUTHORIZATION = "Authorization"; /** RFC 2616 (HTTP/1.1) Section 14.9 */ public static final String CACHE_CONTROL = "Cache-Control"; /** RFC 2616 (HTTP/1.1) Section 14.10 */ public static final String CONNECTION = "Connection"; /** RFC 1945 (HTTP/1.0) Section 10.3, RFC 2616 (HTTP/1.1) Section 14.11 */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** RFC 2616 (HTTP/1.1) Section 14.12 */ public static final String CONTENT_LANGUAGE = "Content-Language"; /** RFC 1945 (HTTP/1.0) Section 10.4, RFC 2616 (HTTP/1.1) Section 14.13 */ public static final String CONTENT_LENGTH = "Content-Length"; /** RFC 2616 (HTTP/1.1) Section 14.14 */ public static final String CONTENT_LOCATION = "Content-Location"; /** RFC 2616 (HTTP/1.1) Section 14.15 */ public static final String CONTENT_MD5 = "Content-MD5"; /** RFC 2616 (HTTP/1.1) Section 14.16 */ public static final String CONTENT_RANGE = "Content-Range"; /** RFC 1945 (HTTP/1.0) Section 10.5, RFC 2616 (HTTP/1.1) Section 14.17 */ public static final String CONTENT_TYPE = "Content-Type"; /** RFC 1945 (HTTP/1.0) Section 10.6, RFC 2616 (HTTP/1.1) Section 14.18 */ public static final String DATE = "Date"; /** RFC 2518 (WevDAV) Section 9.1 */ public static final String DAV = "Dav"; /** RFC 2518 (WevDAV) Section 9.2 */ public static final String DEPTH = "Depth"; /** RFC 2518 (WevDAV) Section 9.3 */ public static final String DESTINATION = "Destination"; /** RFC 2616 (HTTP/1.1) Section 14.19 */ public static final String ETAG = "ETag"; /** RFC 2616 (HTTP/1.1) Section 14.20 */ public static final String EXPECT = "Expect"; /** RFC 1945 (HTTP/1.0) Section 10.7, RFC 2616 (HTTP/1.1) Section 14.21 */ public static final String EXPIRES = "Expires"; /** RFC 1945 (HTTP/1.0) Section 10.8, RFC 2616 (HTTP/1.1) Section 14.22 */ public static final String FROM = "From"; /** RFC 2616 (HTTP/1.1) Section 14.23 */ public static final String HOST = "Host"; /** RFC 2518 (WevDAV) Section 9.4 */ public static final String IF = "If"; /** RFC 2616 (HTTP/1.1) Section 14.24 */ public static final String IF_MATCH = "If-Match"; /** RFC 1945 (HTTP/1.0) Section 10.9, RFC 2616 (HTTP/1.1) Section 14.25 */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** RFC 2616 (HTTP/1.1) Section 14.26 */ public static final String IF_NONE_MATCH = "If-None-Match"; /** RFC 2616 (HTTP/1.1) Section 14.27 */ public static final String IF_RANGE = "If-Range"; /** RFC 2616 (HTTP/1.1) Section 14.28 */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** RFC 1945 (HTTP/1.0) Section 10.10, RFC 2616 (HTTP/1.1) Section 14.29 */ public static final String LAST_MODIFIED = "Last-Modified"; /** RFC 1945 (HTTP/1.0) Section 10.11, RFC 2616 (HTTP/1.1) Section 14.30 */ public static final String LOCATION = "Location"; /** RFC 2518 (WevDAV) Section 9.5 */ public static final String LOCK_TOKEN = "Lock-Token"; /** RFC 2616 (HTTP/1.1) Section 14.31 */ public static final String MAX_FORWARDS = "Max-Forwards"; /** RFC 2518 (WevDAV) Section 9.6 */ public static final String OVERWRITE = "Overwrite"; /** RFC 1945 (HTTP/1.0) Section 10.12, RFC 2616 (HTTP/1.1) Section 14.32 */ public static final String PRAGMA = "Pragma"; /** RFC 2616 (HTTP/1.1) Section 14.33 */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** RFC 2616 (HTTP/1.1) Section 14.34 */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** RFC 2616 (HTTP/1.1) Section 14.35 */ public static final String RANGE = "Range"; /** RFC 1945 (HTTP/1.0) Section 10.13, RFC 2616 (HTTP/1.1) Section 14.36 */ public static final String REFERER = "Referer"; /** RFC 2616 (HTTP/1.1) Section 14.37 */ public static final String RETRY_AFTER = "Retry-After"; /** RFC 1945 (HTTP/1.0) Section 10.14, RFC 2616 (HTTP/1.1) Section 14.38 */ public static final String SERVER = "Server"; /** RFC 2518 (WevDAV) Section 9.7 */ public static final String STATUS_URI = "Status-URI"; /** RFC 2616 (HTTP/1.1) Section 14.39 */ public static final String TE = "TE"; /** RFC 2518 (WevDAV) Section 9.8 */ public static final String TIMEOUT = "Timeout"; /** RFC 2616 (HTTP/1.1) Section 14.40 */ public static final String TRAILER = "Trailer"; /** RFC 2616 (HTTP/1.1) Section 14.41 */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** RFC 2616 (HTTP/1.1) Section 14.42 */ public static final String UPGRADE = "Upgrade"; /** RFC 1945 (HTTP/1.0) Section 10.15, RFC 2616 (HTTP/1.1) Section 14.43 */ public static final String USER_AGENT = "User-Agent"; /** RFC 2616 (HTTP/1.1) Section 14.44 */ public static final String VARY = "Vary"; /** RFC 2616 (HTTP/1.1) Section 14.45 */ public static final String VIA = "Via"; /** RFC 2616 (HTTP/1.1) Section 14.46 */ public static final String WARNING = "Warning"; /** RFC 1945 (HTTP/1.0) Section 10.16, RFC 2616 (HTTP/1.1) Section 14.47 */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * The Request-Line begins with a method token, followed by the * Request-URI and the protocol version, and ending with CRLF. The * elements are separated by SP characters. No CR or LF is allowed * except in the final CRLF sequence. * <pre> * Request-Line = Method SP Request-URI SP HTTP-Version CRLF * </pre> * * @since 4.0 */ public interface RequestLine { String getMethod(); ProtocolVersion getProtocolVersion(); String getUri(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for formatting elements of the HEAD section of an HTTP message. * This is the complement to {@link LineParser}. * There are individual methods for formatting a request line, a * status line, or a header line. The formatting does <i>not</i> include the * trailing line break sequence CR-LF. * Instances of this interface are expected to be stateless and thread-safe. * * <p> * The formatted lines are returned in memory, the formatter does not depend * on any specific IO mechanism. * In order to avoid unnecessary creation of temporary objects, * a buffer can be passed as argument to all formatting methods. * The implementation may or may not actually use that buffer for formatting. * If it is used, the buffer will first be cleared by the * <code>formatXXX</code> methods. * The argument buffer can always be re-used after the call. The buffer * returned as the result, if it is different from the argument buffer, * MUST NOT be modified. * </p> * * @since 4.0 */ public interface LineFormatter { /** * Formats a protocol version. * This method does <i>not</i> follow the general contract for * <code>buffer</code> arguments. * It does <i>not</i> clear the argument buffer, but appends instead. * The returned buffer can always be modified by the caller. * Because of these differing conventions, it is not named * <code>formatProtocolVersion</code>. * * @param buffer a buffer to which to append, or <code>null</code> * @param version the protocol version to format * * @return a buffer with the formatted protocol version appended. * The caller is allowed to modify the result buffer. * If the <code>buffer</code> argument is not <code>null</code>, * the returned buffer is the argument buffer. */ CharArrayBuffer appendProtocolVersion(CharArrayBuffer buffer, ProtocolVersion version); /** * Formats a request line. * * @param buffer a buffer available for formatting, or * <code>null</code>. * The buffer will be cleared before use. * @param reqline the request line to format * * @return the formatted request line */ CharArrayBuffer formatRequestLine(CharArrayBuffer buffer, RequestLine reqline); /** * Formats a status line. * * @param buffer a buffer available for formatting, or * <code>null</code>. * The buffer will be cleared before use. * @param statline the status line to format * * @return the formatted status line * * @throws org.apache.ogt.http.ParseException in case of a parse error */ CharArrayBuffer formatStatusLine(CharArrayBuffer buffer, StatusLine statline); /** * Formats a header. * Due to header continuation, the result may be multiple lines. * In order to generate well-formed HTTP, the lines in the result * must be separated by the HTTP line break sequence CR-LF. * There is <i>no</i> trailing CR-LF in the result. * <br/> * See the class comment for details about the buffer argument. * * @param buffer a buffer available for formatting, or * <code>null</code>. * The buffer will be cleared before use. * @param header the header to format * * @return a buffer holding the formatted header, never <code>null</code>. * The returned buffer may be different from the argument buffer. * * @throws org.apache.ogt.http.ParseException in case of a parse error */ CharArrayBuffer formatHeader(CharArrayBuffer buffer, Header header); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.util.NoSuchElementException; import org.apache.ogt.http.FormattedHeader; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HeaderElementIterator; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.util.CharArrayBuffer; /** * Basic implementation of a {@link HeaderElementIterator}. * * @since 4.0 */ public class BasicHeaderElementIterator implements HeaderElementIterator { private final HeaderIterator headerIt; private final HeaderValueParser parser; private HeaderElement currentElement = null; private CharArrayBuffer buffer = null; private ParserCursor cursor = null; /** * Creates a new instance of BasicHeaderElementIterator */ public BasicHeaderElementIterator( final HeaderIterator headerIterator, final HeaderValueParser parser) { if (headerIterator == null) { throw new IllegalArgumentException("Header iterator may not be null"); } if (parser == null) { throw new IllegalArgumentException("Parser may not be null"); } this.headerIt = headerIterator; this.parser = parser; } public BasicHeaderElementIterator(final HeaderIterator headerIterator) { this(headerIterator, BasicHeaderValueParser.DEFAULT); } private void bufferHeaderValue() { this.cursor = null; this.buffer = null; while (this.headerIt.hasNext()) { Header h = this.headerIt.nextHeader(); if (h instanceof FormattedHeader) { this.buffer = ((FormattedHeader) h).getBuffer(); this.cursor = new ParserCursor(0, this.buffer.length()); this.cursor.updatePos(((FormattedHeader) h).getValuePos()); break; } else { String value = h.getValue(); if (value != null) { this.buffer = new CharArrayBuffer(value.length()); this.buffer.append(value); this.cursor = new ParserCursor(0, this.buffer.length()); break; } } } } private void parseNextElement() { // loop while there are headers left to parse while (this.headerIt.hasNext() || this.cursor != null) { if (this.cursor == null || this.cursor.atEnd()) { // get next header value bufferHeaderValue(); } // Anything buffered? if (this.cursor != null) { // loop while there is data in the buffer while (!this.cursor.atEnd()) { HeaderElement e = this.parser.parseHeaderElement(this.buffer, this.cursor); if (!(e.getName().length() == 0 && e.getValue() == null)) { // Found something this.currentElement = e; return; } } // if at the end of the buffer if (this.cursor.atEnd()) { // discard it this.cursor = null; this.buffer = null; } } } } public boolean hasNext() { if (this.currentElement == null) { parseNextElement(); } return this.currentElement != null; } public HeaderElement nextElement() throws NoSuchElementException { if (this.currentElement == null) { parseNextElement(); } if (this.currentElement == null) { throw new NoSuchElementException("No more header elements available"); } HeaderElement element = this.currentElement; this.currentElement = null; return element; } public final Object next() throws NoSuchElementException { return nextElement(); } public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException("Remove not supported"); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpVersion; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.CharArrayBuffer; /** * Basic parser for lines in the head section of an HTTP message. * There are individual methods for parsing a request line, a * status line, or a header line. * The lines to parse are passed in memory, the parser does not depend * on any specific IO mechanism. * Instances of this class are stateless and thread-safe. * Derived classes MUST maintain these properties. * * <p> * Note: This class was created by refactoring parsing code located in * various other classes. The author tags from those other classes have * been replicated here, although the association with the parsing code * taken from there has not been traced. * </p> * * @since 4.0 */ public class BasicLineParser implements LineParser { /** * A default instance of this class, for use as default or fallback. * Note that {@link BasicLineParser} is not a singleton, there can * be many instances of the class itself and of derived classes. * The instance here provides non-customized, default behavior. */ public final static BasicLineParser DEFAULT = new BasicLineParser(); /** * A version of the protocol to parse. * The version is typically not relevant, but the protocol name. */ protected final ProtocolVersion protocol; /** * Creates a new line parser for the given HTTP-like protocol. * * @param proto a version of the protocol to parse, or * <code>null</code> for HTTP. The actual version * is not relevant, only the protocol name. */ public BasicLineParser(ProtocolVersion proto) { if (proto == null) { proto = HttpVersion.HTTP_1_1; } this.protocol = proto; } /** * Creates a new line parser for HTTP. */ public BasicLineParser() { this(null); } public final static ProtocolVersion parseProtocolVersion(String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null."); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseProtocolVersion(buffer, cursor); } // non-javadoc, see interface LineParser public ProtocolVersion parseProtocolVersion(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } final String protoname = this.protocol.getProtocol(); final int protolength = protoname.length(); int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); skipWhitespace(buffer, cursor); int i = cursor.getPos(); // long enough for "HTTP/1.1"? if (i + protolength + 4 > indexTo) { throw new ParseException ("Not a valid protocol version: " + buffer.substring(indexFrom, indexTo)); } // check the protocol name and slash boolean ok = true; for (int j=0; ok && (j<protolength); j++) { ok = (buffer.charAt(i+j) == protoname.charAt(j)); } if (ok) { ok = (buffer.charAt(i+protolength) == '/'); } if (!ok) { throw new ParseException ("Not a valid protocol version: " + buffer.substring(indexFrom, indexTo)); } i += protolength+1; int period = buffer.indexOf('.', i, indexTo); if (period == -1) { throw new ParseException ("Invalid protocol version number: " + buffer.substring(indexFrom, indexTo)); } int major; try { major = Integer.parseInt(buffer.substringTrimmed(i, period)); } catch (NumberFormatException e) { throw new ParseException ("Invalid protocol major version number: " + buffer.substring(indexFrom, indexTo)); } i = period + 1; int blank = buffer.indexOf(' ', i, indexTo); if (blank == -1) { blank = indexTo; } int minor; try { minor = Integer.parseInt(buffer.substringTrimmed(i, blank)); } catch (NumberFormatException e) { throw new ParseException( "Invalid protocol minor version number: " + buffer.substring(indexFrom, indexTo)); } cursor.updatePos(blank); return createProtocolVersion(major, minor); } // parseProtocolVersion /** * Creates a protocol version. * Called from {@link #parseProtocolVersion}. * * @param major the major version number, for example 1 in HTTP/1.0 * @param minor the minor version number, for example 0 in HTTP/1.0 * * @return the protocol version */ protected ProtocolVersion createProtocolVersion(int major, int minor) { return protocol.forVersion(major, minor); } // non-javadoc, see interface LineParser public boolean hasProtocolVersion(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int index = cursor.getPos(); final String protoname = this.protocol.getProtocol(); final int protolength = protoname.length(); if (buffer.length() < protolength+4) return false; // not long enough for "HTTP/1.1" if (index < 0) { // end of line, no tolerance for trailing whitespace // this works only for single-digit major and minor version index = buffer.length() -4 -protolength; } else if (index == 0) { // beginning of line, tolerate leading whitespace while ((index < buffer.length()) && HTTP.isWhitespace(buffer.charAt(index))) { index++; } } // else within line, don't tolerate whitespace if (index + protolength + 4 > buffer.length()) return false; // just check protocol name and slash, no need to analyse the version boolean ok = true; for (int j=0; ok && (j<protolength); j++) { ok = (buffer.charAt(index+j) == protoname.charAt(j)); } if (ok) { ok = (buffer.charAt(index+protolength) == '/'); } return ok; } public final static RequestLine parseRequestLine(final String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null."); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseRequestLine(buffer, cursor); } /** * Parses a request line. * * @param buffer a buffer holding the line to parse * * @return the parsed request line * * @throws ParseException in case of a parse error */ public RequestLine parseRequestLine(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); try { skipWhitespace(buffer, cursor); int i = cursor.getPos(); int blank = buffer.indexOf(' ', i, indexTo); if (blank < 0) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } String method = buffer.substringTrimmed(i, blank); cursor.updatePos(blank); skipWhitespace(buffer, cursor); i = cursor.getPos(); blank = buffer.indexOf(' ', i, indexTo); if (blank < 0) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } String uri = buffer.substringTrimmed(i, blank); cursor.updatePos(blank); ProtocolVersion ver = parseProtocolVersion(buffer, cursor); skipWhitespace(buffer, cursor); if (!cursor.atEnd()) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } return createRequestLine(method, uri, ver); } catch (IndexOutOfBoundsException e) { throw new ParseException("Invalid request line: " + buffer.substring(indexFrom, indexTo)); } } // parseRequestLine /** * Instantiates a new request line. * Called from {@link #parseRequestLine}. * * @param method the request method * @param uri the requested URI * @param ver the protocol version * * @return a new status line with the given data */ protected RequestLine createRequestLine(final String method, final String uri, final ProtocolVersion ver) { return new BasicRequestLine(method, uri, ver); } public final static StatusLine parseStatusLine(final String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null."); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseStatusLine(buffer, cursor); } // non-javadoc, see interface LineParser public StatusLine parseStatusLine(final CharArrayBuffer buffer, final ParserCursor cursor) throws ParseException { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); try { // handle the HTTP-Version ProtocolVersion ver = parseProtocolVersion(buffer, cursor); // handle the Status-Code skipWhitespace(buffer, cursor); int i = cursor.getPos(); int blank = buffer.indexOf(' ', i, indexTo); if (blank < 0) { blank = indexTo; } int statusCode = 0; String s = buffer.substringTrimmed(i, blank); for (int j = 0; j < s.length(); j++) { if (!Character.isDigit(s.charAt(j))) { throw new ParseException( "Status line contains invalid status code: " + buffer.substring(indexFrom, indexTo)); } } try { statusCode = Integer.parseInt(s); } catch (NumberFormatException e) { throw new ParseException( "Status line contains invalid status code: " + buffer.substring(indexFrom, indexTo)); } //handle the Reason-Phrase i = blank; String reasonPhrase = null; if (i < indexTo) { reasonPhrase = buffer.substringTrimmed(i, indexTo); } else { reasonPhrase = ""; } return createStatusLine(ver, statusCode, reasonPhrase); } catch (IndexOutOfBoundsException e) { throw new ParseException("Invalid status line: " + buffer.substring(indexFrom, indexTo)); } } // parseStatusLine /** * Instantiates a new status line. * Called from {@link #parseStatusLine}. * * @param ver the protocol version * @param status the status code * @param reason the reason phrase * * @return a new status line with the given data */ protected StatusLine createStatusLine(final ProtocolVersion ver, final int status, final String reason) { return new BasicStatusLine(ver, status, reason); } public final static Header parseHeader(final String value, LineParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicLineParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); return parser.parseHeader(buffer); } // non-javadoc, see interface LineParser public Header parseHeader(CharArrayBuffer buffer) throws ParseException { // the actual parser code is in the constructor of BufferedHeader return new BufferedHeader(buffer); } /** * Helper to skip whitespace. */ protected void skipWhitespace(final CharArrayBuffer buffer, final ParserCursor cursor) { int pos = cursor.getPos(); int indexTo = cursor.getUpperBound(); while ((pos < indexTo) && HTTP.isWhitespace(buffer.charAt(pos))) { pos++; } cursor.updatePos(pos); } } // class BasicLineParser
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.FormattedHeader; import org.apache.ogt.http.Header; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for formatting elements of the HEAD section of an HTTP message. * This is the complement to {@link LineParser}. * There are individual methods for formatting a request line, a * status line, or a header line. The formatting does <i>not</i> include the * trailing line break sequence CR-LF. * The formatted lines are returned in memory, the formatter does not depend * on any specific IO mechanism. * Instances of this interface are expected to be stateless and thread-safe. * * @since 4.0 */ public class BasicLineFormatter implements LineFormatter { /** * A default instance of this class, for use as default or fallback. * Note that {@link BasicLineFormatter} is not a singleton, there can * be many instances of the class itself and of derived classes. * The instance here provides non-customized, default behavior. */ public final static BasicLineFormatter DEFAULT = new BasicLineFormatter(); // public default constructor /** * Obtains a buffer for formatting. * * @param buffer a buffer already available, or <code>null</code> * * @return the cleared argument buffer if there is one, or * a new empty buffer that can be used for formatting */ protected CharArrayBuffer initBuffer(CharArrayBuffer buffer) { if (buffer != null) { buffer.clear(); } else { buffer = new CharArrayBuffer(64); } return buffer; } /** * Formats a protocol version. * * @param version the protocol version to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted protocol version */ public final static String formatProtocolVersion(final ProtocolVersion version, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.appendProtocolVersion(null, version).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer appendProtocolVersion(final CharArrayBuffer buffer, final ProtocolVersion version) { if (version == null) { throw new IllegalArgumentException ("Protocol version may not be null"); } // can't use initBuffer, that would clear the argument! CharArrayBuffer result = buffer; final int len = estimateProtocolVersionLen(version); if (result == null) { result = new CharArrayBuffer(len); } else { result.ensureCapacity(len); } result.append(version.getProtocol()); result.append('/'); result.append(Integer.toString(version.getMajor())); result.append('.'); result.append(Integer.toString(version.getMinor())); return result; } /** * Guesses the length of a formatted protocol version. * Needed to guess the length of a formatted request or status line. * * @param version the protocol version to format, or <code>null</code> * * @return the estimated length of the formatted protocol version, * in characters */ protected int estimateProtocolVersionLen(final ProtocolVersion version) { return version.getProtocol().length() + 4; // room for "HTTP/1.1" } /** * Formats a request line. * * @param reqline the request line to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted request line */ public final static String formatRequestLine(final RequestLine reqline, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.formatRequestLine(null, reqline).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer formatRequestLine(CharArrayBuffer buffer, RequestLine reqline) { if (reqline == null) { throw new IllegalArgumentException ("Request line may not be null"); } CharArrayBuffer result = initBuffer(buffer); doFormatRequestLine(result, reqline); return result; } /** * Actually formats a request line. * Called from {@link #formatRequestLine}. * * @param buffer the empty buffer into which to format, * never <code>null</code> * @param reqline the request line to format, never <code>null</code> */ protected void doFormatRequestLine(final CharArrayBuffer buffer, final RequestLine reqline) { final String method = reqline.getMethod(); final String uri = reqline.getUri(); // room for "GET /index.html HTTP/1.1" int len = method.length() + 1 + uri.length() + 1 + estimateProtocolVersionLen(reqline.getProtocolVersion()); buffer.ensureCapacity(len); buffer.append(method); buffer.append(' '); buffer.append(uri); buffer.append(' '); appendProtocolVersion(buffer, reqline.getProtocolVersion()); } /** * Formats a status line. * * @param statline the status line to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted status line */ public final static String formatStatusLine(final StatusLine statline, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.formatStatusLine(null, statline).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer formatStatusLine(final CharArrayBuffer buffer, final StatusLine statline) { if (statline == null) { throw new IllegalArgumentException ("Status line may not be null"); } CharArrayBuffer result = initBuffer(buffer); doFormatStatusLine(result, statline); return result; } /** * Actually formats a status line. * Called from {@link #formatStatusLine}. * * @param buffer the empty buffer into which to format, * never <code>null</code> * @param statline the status line to format, never <code>null</code> */ protected void doFormatStatusLine(final CharArrayBuffer buffer, final StatusLine statline) { int len = estimateProtocolVersionLen(statline.getProtocolVersion()) + 1 + 3 + 1; // room for "HTTP/1.1 200 " final String reason = statline.getReasonPhrase(); if (reason != null) { len += reason.length(); } buffer.ensureCapacity(len); appendProtocolVersion(buffer, statline.getProtocolVersion()); buffer.append(' '); buffer.append(Integer.toString(statline.getStatusCode())); buffer.append(' '); // keep whitespace even if reason phrase is empty if (reason != null) { buffer.append(reason); } } /** * Formats a header. * * @param header the header to format * @param formatter the formatter to use, or * <code>null</code> for the * {@link #DEFAULT default} * * @return the formatted header */ public final static String formatHeader(final Header header, LineFormatter formatter) { if (formatter == null) formatter = BasicLineFormatter.DEFAULT; return formatter.formatHeader(null, header).toString(); } // non-javadoc, see interface LineFormatter public CharArrayBuffer formatHeader(CharArrayBuffer buffer, Header header) { if (header == null) { throw new IllegalArgumentException ("Header may not be null"); } CharArrayBuffer result = null; if (header instanceof FormattedHeader) { // If the header is backed by a buffer, re-use the buffer result = ((FormattedHeader)header).getBuffer(); } else { result = initBuffer(buffer); doFormatHeader(result, header); } return result; } // formatHeader /** * Actually formats a header. * Called from {@link #formatHeader}. * * @param buffer the empty buffer into which to format, * never <code>null</code> * @param header the header to format, never <code>null</code> */ protected void doFormatHeader(final CharArrayBuffer buffer, final Header header) { final String name = header.getName(); final String value = header.getValue(); int len = name.length() + 2; if (value != null) { len += value.length(); } buffer.ensureCapacity(len); buffer.append(name); buffer.append(": "); if (value != null) { buffer.append(value); } } } // class BasicLineFormatter
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for parsing header values into elements. * Instances of this interface are expected to be stateless and thread-safe. * * @since 4.0 */ public interface HeaderValueParser { /** * Parses a header value into elements. * Parse errors are indicated as <code>RuntimeException</code>. * <p> * Some HTTP headers (such as the set-cookie header) have values that * can be decomposed into multiple elements. In order to be processed * by this parser, such headers must be in the following form: * </p> * <pre> * header = [ element ] *( "," [ element ] ) * element = name [ "=" [ value ] ] *( ";" [ param ] ) * param = name [ "=" [ value ] ] * * name = token * value = ( token | quoted-string ) * * token = 1*&lt;any char except "=", ",", ";", &lt;"&gt; and * white space&gt; * quoted-string = &lt;"&gt; *( text | quoted-char ) &lt;"&gt; * text = any char except &lt;"&gt; * quoted-char = "\" char * </pre> * <p> * Any amount of white space is allowed between any part of the * header, element or param and is ignored. A missing value in any * element or param will be stored as the empty {@link String}; * if the "=" is also missing <var>null</var> will be stored instead. * </p> * * @param buffer buffer holding the header value to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return an array holding all elements of the header value * * @throws ParseException in case of a parse error */ HeaderElement[] parseElements( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a single header element. * A header element consist of a semicolon-separate list * of name=value definitions. * * @param buffer buffer holding the element to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed element * * @throws ParseException in case of a parse error */ HeaderElement parseHeaderElement( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a list of name-value pairs. * These lists are used to specify parameters to a header element. * Parse errors are indicated as <code>ParseException</code>. * * @param buffer buffer holding the name-value list to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return an array holding all items of the name-value list * * @throws ParseException in case of a parse error */ NameValuePair[] parseParameters( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a name=value specification, where the = and value are optional. * * @param buffer the buffer holding the name-value pair to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the name-value pair, where the value is <code>null</code> * if no value is specified */ NameValuePair parseNameValuePair( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.HttpRequest; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.params.HttpParams; import org.apache.ogt.http.params.HttpProtocolParams; /** * Basic implementation of {@link HttpRequest}. * <p> * The following parameters can be used to customize the behavior of this class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#PROTOCOL_VERSION}</li> * </ul> * * @since 4.0 */ public class BasicHttpRequest extends AbstractHttpMessage implements HttpRequest { private final String method; private final String uri; private RequestLine requestline; /** * Creates an instance of this class using the given request method * and URI. The HTTP protocol version will be obtained from the * {@link HttpParams} instance associated with the object. * The initialization will be deferred * until {@link #getRequestLine()} is accessed for the first time. * * @param method request method. * @param uri request URI. */ public BasicHttpRequest(final String method, final String uri) { super(); if (method == null) { throw new IllegalArgumentException("Method name may not be null"); } if (uri == null) { throw new IllegalArgumentException("Request URI may not be null"); } this.method = method; this.uri = uri; this.requestline = null; } /** * Creates an instance of this class using the given request method, URI * and the HTTP protocol version. * * @param method request method. * @param uri request URI. * @param ver HTTP protocol version. */ public BasicHttpRequest(final String method, final String uri, final ProtocolVersion ver) { this(new BasicRequestLine(method, uri, ver)); } /** * Creates an instance of this class using the given request line. * * @param requestline request line. */ public BasicHttpRequest(final RequestLine requestline) { super(); if (requestline == null) { throw new IllegalArgumentException("Request line may not be null"); } this.requestline = requestline; this.method = requestline.getMethod(); this.uri = requestline.getUri(); } /** * Returns the HTTP protocol version to be used for this request. If an * HTTP protocol version was not explicitly set at the construction time, * this method will obtain it from the {@link HttpParams} instance * associated with the object. * * @see #BasicHttpRequest(String, String) */ public ProtocolVersion getProtocolVersion() { return getRequestLine().getProtocolVersion(); } /** * Returns the request line of this request. If an HTTP protocol version * was not explicitly set at the construction time, this method will obtain * it from the {@link HttpParams} instance associated with the object. * * @see #BasicHttpRequest(String, String) */ public RequestLine getRequestLine() { if (this.requestline == null) { ProtocolVersion ver = HttpProtocolParams.getVersion(getParams()); this.requestline = new BasicRequestLine(this.method, this.uri, ver); } return this.requestline; } public String toString() { return this.method + " " + this.uri + " " + this.headergroup; } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.io.Serializable; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.StatusLine; /** * Basic implementation of {@link StatusLine} * * @version $Id: BasicStatusLine.java 986952 2010-08-18 21:24:55Z olegk $ * * @since 4.0 */ public class BasicStatusLine implements StatusLine, Cloneable, Serializable { private static final long serialVersionUID = -2443303766890459269L; // ----------------------------------------------------- Instance Variables /** The protocol version. */ private final ProtocolVersion protoVersion; /** The status code. */ private final int statusCode; /** The reason phrase. */ private final String reasonPhrase; // ----------------------------------------------------------- Constructors /** * Creates a new status line with the given version, status, and reason. * * @param version the protocol version of the response * @param statusCode the status code of the response * @param reasonPhrase the reason phrase to the status code, or * <code>null</code> */ public BasicStatusLine(final ProtocolVersion version, int statusCode, final String reasonPhrase) { super(); if (version == null) { throw new IllegalArgumentException ("Protocol version may not be null."); } if (statusCode < 0) { throw new IllegalArgumentException ("Status code may not be negative."); } this.protoVersion = version; this.statusCode = statusCode; this.reasonPhrase = reasonPhrase; } // --------------------------------------------------------- Public Methods public int getStatusCode() { return this.statusCode; } public ProtocolVersion getProtocolVersion() { return this.protoVersion; } public String getReasonPhrase() { return this.reasonPhrase; } public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.DEFAULT .formatStatusLine(null, this).toString(); } public Object clone() throws CloneNotSupportedException { return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.util.NoSuchElementException; import org.apache.ogt.http.HeaderIterator; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.TokenIterator; /** * Basic implementation of a {@link TokenIterator}. * This implementation parses <tt>#token<tt> sequences as * defined by RFC 2616, section 2. * It extends that definition somewhat beyond US-ASCII. * * @since 4.0 */ public class BasicTokenIterator implements TokenIterator { /** The HTTP separator characters. Defined in RFC 2616, section 2.2. */ // the order of the characters here is adjusted to put the // most likely candidates at the beginning of the collection public final static String HTTP_SEPARATORS = " ,;=()<>@:\\\"/[]?{}\t"; /** The iterator from which to obtain the next header. */ protected final HeaderIterator headerIt; /** * The value of the current header. * This is the header value that includes {@link #currentToken}. * Undefined if the iteration is over. */ protected String currentHeader; /** * The token to be returned by the next call to {@link #currentToken}. * <code>null</code> if the iteration is over. */ protected String currentToken; /** * The position after {@link #currentToken} in {@link #currentHeader}. * Undefined if the iteration is over. */ protected int searchPos; /** * Creates a new instance of {@link BasicTokenIterator}. * * @param headerIterator the iterator for the headers to tokenize */ public BasicTokenIterator(final HeaderIterator headerIterator) { if (headerIterator == null) { throw new IllegalArgumentException ("Header iterator must not be null."); } this.headerIt = headerIterator; this.searchPos = findNext(-1); } // non-javadoc, see interface TokenIterator public boolean hasNext() { return (this.currentToken != null); } /** * Obtains the next token from this iteration. * * @return the next token in this iteration * * @throws NoSuchElementException if the iteration is already over * @throws ParseException if an invalid header value is encountered */ public String nextToken() throws NoSuchElementException, ParseException { if (this.currentToken == null) { throw new NoSuchElementException("Iteration already finished."); } final String result = this.currentToken; // updates currentToken, may trigger ParseException: this.searchPos = findNext(this.searchPos); return result; } /** * Returns the next token. * Same as {@link #nextToken}, but with generic return type. * * @return the next token in this iteration * * @throws NoSuchElementException if there are no more tokens * @throws ParseException if an invalid header value is encountered */ public final Object next() throws NoSuchElementException, ParseException { return nextToken(); } /** * Removing tokens is not supported. * * @throws UnsupportedOperationException always */ public final void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException ("Removing tokens is not supported."); } /** * Determines the next token. * If found, the token is stored in {@link #currentToken}. * The return value indicates the position after the token * in {@link #currentHeader}. If necessary, the next header * will be obtained from {@link #headerIt}. * If not found, {@link #currentToken} is set to <code>null</code>. * * @param from the position in the current header at which to * start the search, -1 to search in the first header * * @return the position after the found token in the current header, or * negative if there was no next token * * @throws ParseException if an invalid header value is encountered */ protected int findNext(int from) throws ParseException { if (from < 0) { // called from the constructor, initialize the first header if (!this.headerIt.hasNext()) { return -1; } this.currentHeader = this.headerIt.nextHeader().getValue(); from = 0; } else { // called after a token, make sure there is a separator from = findTokenSeparator(from); } int start = findTokenStart(from); if (start < 0) { this.currentToken = null; return -1; // nothing found } int end = findTokenEnd(start); this.currentToken = createToken(this.currentHeader, start, end); return end; } /** * Creates a new token to be returned. * Called from {@link #findNext findNext} after the token is identified. * The default implementation simply calls * {@link java.lang.String#substring String.substring}. * <br/> * If header values are significantly longer than tokens, and some * tokens are permanently referenced by the application, there can * be problems with garbage collection. A substring will hold a * reference to the full characters of the original string and * therefore occupies more memory than might be expected. * To avoid this, override this method and create a new string * instead of a substring. * * @param value the full header value from which to create a token * @param start the index of the first token character * @param end the index after the last token character * * @return a string representing the token identified by the arguments */ protected String createToken(String value, int start, int end) { return value.substring(start, end); } /** * Determines the starting position of the next token. * This method will iterate over headers if necessary. * * @param from the position in the current header at which to * start the search * * @return the position of the token start in the current header, * negative if no token start could be found */ protected int findTokenStart(int from) { if (from < 0) { throw new IllegalArgumentException ("Search position must not be negative: " + from); } boolean found = false; while (!found && (this.currentHeader != null)) { final int to = this.currentHeader.length(); while (!found && (from < to)) { final char ch = this.currentHeader.charAt(from); if (isTokenSeparator(ch) || isWhitespace(ch)) { // whitspace and token separators are skipped from++; } else if (isTokenChar(this.currentHeader.charAt(from))) { // found the start of a token found = true; } else { throw new ParseException ("Invalid character before token (pos " + from + "): " + this.currentHeader); } } if (!found) { if (this.headerIt.hasNext()) { this.currentHeader = this.headerIt.nextHeader().getValue(); from = 0; } else { this.currentHeader = null; } } } // while headers return found ? from : -1; } /** * Determines the position of the next token separator. * Because of multi-header joining rules, the end of a * header value is a token separator. This method does * therefore not need to iterate over headers. * * @param from the position in the current header at which to * start the search * * @return the position of a token separator in the current header, * or at the end * * @throws ParseException * if a new token is found before a token separator. * RFC 2616, section 2.1 explicitly requires a comma between * tokens for <tt>#</tt>. */ protected int findTokenSeparator(int from) { if (from < 0) { throw new IllegalArgumentException ("Search position must not be negative: " + from); } boolean found = false; final int to = this.currentHeader.length(); while (!found && (from < to)) { final char ch = this.currentHeader.charAt(from); if (isTokenSeparator(ch)) { found = true; } else if (isWhitespace(ch)) { from++; } else if (isTokenChar(ch)) { throw new ParseException ("Tokens without separator (pos " + from + "): " + this.currentHeader); } else { throw new ParseException ("Invalid character after token (pos " + from + "): " + this.currentHeader); } } return from; } /** * Determines the ending position of the current token. * This method will not leave the current header value, * since the end of the header value is a token boundary. * * @param from the position of the first character of the token * * @return the position after the last character of the token. * The behavior is undefined if <code>from</code> does not * point to a token character in the current header value. */ protected int findTokenEnd(int from) { if (from < 0) { throw new IllegalArgumentException ("Token start position must not be negative: " + from); } final int to = this.currentHeader.length(); int end = from+1; while ((end < to) && isTokenChar(this.currentHeader.charAt(end))) { end++; } return end; } /** * Checks whether a character is a token separator. * RFC 2616, section 2.1 defines comma as the separator for * <tt>#token</tt> sequences. The end of a header value will * also separate tokens, but that is not a character check. * * @param ch the character to check * * @return <code>true</code> if the character is a token separator, * <code>false</code> otherwise */ protected boolean isTokenSeparator(char ch) { return (ch == ','); } /** * Checks whether a character is a whitespace character. * RFC 2616, section 2.2 defines space and horizontal tab as whitespace. * The optional preceeding line break is irrelevant, since header * continuation is handled transparently when parsing messages. * * @param ch the character to check * * @return <code>true</code> if the character is whitespace, * <code>false</code> otherwise */ protected boolean isWhitespace(char ch) { // we do not use Character.isWhitspace(ch) here, since that allows // many control characters which are not whitespace as per RFC 2616 return ((ch == '\t') || Character.isSpaceChar(ch)); } /** * Checks whether a character is a valid token character. * Whitespace, control characters, and HTTP separators are not * valid token characters. The HTTP specification (RFC 2616, section 2.2) * defines tokens only for the US-ASCII character set, this * method extends the definition to other character sets. * * @param ch the character to check * * @return <code>true</code> if the character is a valid token start, * <code>false</code> otherwise */ protected boolean isTokenChar(char ch) { // common sense extension of ALPHA + DIGIT if (Character.isLetterOrDigit(ch)) return true; // common sense extension of CTL if (Character.isISOControl(ch)) return false; // no common sense extension for this if (isHttpSeparator(ch)) return false; // RFC 2616, section 2.2 defines a token character as // "any CHAR except CTLs or separators". The controls // and separators are included in the checks above. // This will yield unexpected results for Unicode format characters. // If that is a problem, overwrite isHttpSeparator(char) to filter // out the false positives. return true; } /** * Checks whether a character is an HTTP separator. * The implementation in this class checks only for the HTTP separators * defined in RFC 2616, section 2.2. If you need to detect other * separators beyond the US-ASCII character set, override this method. * * @param ch the character to check * * @return <code>true</code> if the character is an HTTP separator */ protected boolean isHttpSeparator(char ch) { return (HTTP_SEPARATORS.indexOf(ch) >= 0); } } // class BasicTokenIterator
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.util.NoSuchElementException; import org.apache.ogt.http.Header; import org.apache.ogt.http.HeaderIterator; /** * Basic implementation of a {@link HeaderIterator}. * * @since 4.0 */ public class BasicHeaderIterator implements HeaderIterator { /** * An array of headers to iterate over. * Not all elements of this array are necessarily part of the iteration. * This array will never be modified by the iterator. * Derived implementations are expected to adhere to this restriction. */ protected final Header[] allHeaders; /** * The position of the next header in {@link #allHeaders allHeaders}. * Negative if the iteration is over. */ protected int currentIndex; /** * The header name to filter by. * <code>null</code> to iterate over all headers in the array. */ protected String headerName; /** * Creates a new header iterator. * * @param headers an array of headers over which to iterate * @param name the name of the headers over which to iterate, or * <code>null</code> for any */ public BasicHeaderIterator(Header[] headers, String name) { if (headers == null) { throw new IllegalArgumentException ("Header array must not be null."); } this.allHeaders = headers; this.headerName = name; this.currentIndex = findNext(-1); } /** * Determines the index of the next header. * * @param from one less than the index to consider first, * -1 to search for the first header * * @return the index of the next header that matches the filter name, * or negative if there are no more headers */ protected int findNext(int from) { if (from < -1) return -1; final int to = this.allHeaders.length-1; boolean found = false; while (!found && (from < to)) { from++; found = filterHeader(from); } return found ? from : -1; } /** * Checks whether a header is part of the iteration. * * @param index the index of the header to check * * @return <code>true</code> if the header should be part of the * iteration, <code>false</code> to skip */ protected boolean filterHeader(int index) { return (this.headerName == null) || this.headerName.equalsIgnoreCase(this.allHeaders[index].getName()); } // non-javadoc, see interface HeaderIterator public boolean hasNext() { return (this.currentIndex >= 0); } /** * Obtains the next header from this iteration. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ public Header nextHeader() throws NoSuchElementException { final int current = this.currentIndex; if (current < 0) { throw new NoSuchElementException("Iteration already finished."); } this.currentIndex = findNext(current); return this.allHeaders[current]; } /** * Returns the next header. * Same as {@link #nextHeader nextHeader}, but not type-safe. * * @return the next header in this iteration * * @throws NoSuchElementException if there are no more headers */ public final Object next() throws NoSuchElementException { return nextHeader(); } /** * Removing headers is not supported. * * @throws UnsupportedOperationException always */ public void remove() throws UnsupportedOperationException { throw new UnsupportedOperationException ("Removing headers is not supported."); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.io.Serializable; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; /** * Basic implementation of {@link RequestLine}. * * @since 4.0 */ public class BasicRequestLine implements RequestLine, Cloneable, Serializable { private static final long serialVersionUID = 2810581718468737193L; private final ProtocolVersion protoversion; private final String method; private final String uri; public BasicRequestLine(final String method, final String uri, final ProtocolVersion version) { super(); if (method == null) { throw new IllegalArgumentException ("Method must not be null."); } if (uri == null) { throw new IllegalArgumentException ("URI must not be null."); } if (version == null) { throw new IllegalArgumentException ("Protocol version must not be null."); } this.method = method; this.uri = uri; this.protoversion = version; } public String getMethod() { return this.method; } public ProtocolVersion getProtocolVersion() { return this.protoversion; } public String getUri() { return this.uri; } public String toString() { // no need for non-default formatting in toString() return BasicLineFormatter.DEFAULT .formatRequestLine(null, this).toString(); } public Object clone() throws CloneNotSupportedException { return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.HttpEntityEnclosingRequest; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.protocol.HTTP; /** * Basic implementation of {@link HttpEntityEnclosingRequest}. * * @since 4.0 */ public class BasicHttpEntityEnclosingRequest extends BasicHttpRequest implements HttpEntityEnclosingRequest { private HttpEntity entity; public BasicHttpEntityEnclosingRequest(final String method, final String uri) { super(method, uri); } public BasicHttpEntityEnclosingRequest(final String method, final String uri, final ProtocolVersion ver) { super(method, uri, ver); } public BasicHttpEntityEnclosingRequest(final RequestLine requestline) { super(requestline); } public HttpEntity getEntity() { return this.entity; } public void setEntity(final HttpEntity entity) { this.entity = entity; } public boolean expectContinue() { Header expect = getFirstHeader(HTTP.EXPECT_DIRECTIVE); return expect != null && HTTP.EXPECT_CONTINUE.equalsIgnoreCase(expect.getValue()); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import org.apache.ogt.http.Header; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.ProtocolVersion; import org.apache.ogt.http.RequestLine; import org.apache.ogt.http.StatusLine; import org.apache.ogt.http.util.CharArrayBuffer; /** * Interface for parsing lines in the HEAD section of an HTTP message. * There are individual methods for parsing a request line, a * status line, or a header line. * The lines to parse are passed in memory, the parser does not depend * on any specific IO mechanism. * Instances of this interface are expected to be stateless and thread-safe. * * @since 4.0 */ public interface LineParser { /** * Parses the textual representation of a protocol version. * This is needed for parsing request lines (last element) * as well as status lines (first element). * * @param buffer a buffer holding the protocol version to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed protocol version * * @throws ParseException in case of a parse error */ ProtocolVersion parseProtocolVersion( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Checks whether there likely is a protocol version in a line. * This method implements a <i>heuristic</i> to check for a * likely protocol version specification. It does <i>not</i> * guarantee that {@link #parseProtocolVersion} would not * detect a parse error. * This can be used to detect garbage lines before a request * or status line. * * @param buffer a buffer holding the line to inspect * @param cursor the cursor at which to check for a protocol version, or * negative for "end of line". Whether the check tolerates * whitespace before or after the protocol version is * implementation dependent. * * @return <code>true</code> if there is a protocol version at the * argument index (possibly ignoring whitespace), * <code>false</code> otherwise */ boolean hasProtocolVersion( CharArrayBuffer buffer, ParserCursor cursor); /** * Parses a request line. * * @param buffer a buffer holding the line to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed request line * * @throws ParseException in case of a parse error */ RequestLine parseRequestLine( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Parses a status line. * * @param buffer a buffer holding the line to parse * @param cursor the parser cursor containing the current position and * the bounds within the buffer for the parsing operation * * @return the parsed status line * * @throws ParseException in case of a parse error */ StatusLine parseStatusLine( CharArrayBuffer buffer, ParserCursor cursor) throws ParseException; /** * Creates a header from a line. * The full header line is expected here. Header continuation lines * must be joined by the caller before invoking this method. * * @param buffer a buffer holding the full header line. * This buffer MUST NOT be re-used afterwards, since * the returned object may reference the contents later. * * @return the header in the argument buffer. * The returned object MAY be a wrapper for the argument buffer. * The argument buffer MUST NOT be re-used or changed afterwards. * * @throws ParseException in case of a parse error */ Header parseHeader(CharArrayBuffer buffer) throws ParseException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.message; import java.util.List; import java.util.ArrayList; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.protocol.HTTP; import org.apache.ogt.http.util.CharArrayBuffer; /** * Basic implementation for parsing header values into elements. * Instances of this class are stateless and thread-safe. * Derived classes are expected to maintain these properties. * * @since 4.0 */ public class BasicHeaderValueParser implements HeaderValueParser { /** * A default instance of this class, for use as default or fallback. * Note that {@link BasicHeaderValueParser} is not a singleton, there * can be many instances of the class itself and of derived classes. * The instance here provides non-customized, default behavior. */ public final static BasicHeaderValueParser DEFAULT = new BasicHeaderValueParser(); private final static char PARAM_DELIMITER = ';'; private final static char ELEM_DELIMITER = ','; private final static char[] ALL_DELIMITERS = new char[] { PARAM_DELIMITER, ELEM_DELIMITER }; // public default constructor /** * Parses elements with the given parser. * * @param value the header value to parse * @param parser the parser to use, or <code>null</code> for default * * @return array holding the header elements, never <code>null</code> */ public final static HeaderElement[] parseElements(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseElements(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public HeaderElement[] parseElements(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } List elements = new ArrayList(); while (!cursor.atEnd()) { HeaderElement element = parseHeaderElement(buffer, cursor); if (!(element.getName().length() == 0 && element.getValue() == null)) { elements.add(element); } } return (HeaderElement[]) elements.toArray(new HeaderElement[elements.size()]); } /** * Parses an element with the given parser. * * @param value the header element to parse * @param parser the parser to use, or <code>null</code> for default * * @return the parsed header element */ public final static HeaderElement parseHeaderElement(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseHeaderElement(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public HeaderElement parseHeaderElement(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } NameValuePair nvp = parseNameValuePair(buffer, cursor); NameValuePair[] params = null; if (!cursor.atEnd()) { char ch = buffer.charAt(cursor.getPos() - 1); if (ch != ELEM_DELIMITER) { params = parseParameters(buffer, cursor); } } return createHeaderElement(nvp.getName(), nvp.getValue(), params); } /** * Creates a header element. * Called from {@link #parseHeaderElement}. * * @return a header element representing the argument */ protected HeaderElement createHeaderElement( final String name, final String value, final NameValuePair[] params) { return new BasicHeaderElement(name, value, params); } /** * Parses parameters with the given parser. * * @param value the parameter list to parse * @param parser the parser to use, or <code>null</code> for default * * @return array holding the parameters, never <code>null</code> */ public final static NameValuePair[] parseParameters(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseParameters(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public NameValuePair[] parseParameters(final CharArrayBuffer buffer, final ParserCursor cursor) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } int pos = cursor.getPos(); int indexTo = cursor.getUpperBound(); while (pos < indexTo) { char ch = buffer.charAt(pos); if (HTTP.isWhitespace(ch)) { pos++; } else { break; } } cursor.updatePos(pos); if (cursor.atEnd()) { return new NameValuePair[] {}; } List params = new ArrayList(); while (!cursor.atEnd()) { NameValuePair param = parseNameValuePair(buffer, cursor); params.add(param); char ch = buffer.charAt(cursor.getPos() - 1); if (ch == ELEM_DELIMITER) { break; } } return (NameValuePair[]) params.toArray(new NameValuePair[params.size()]); } /** * Parses a name-value-pair with the given parser. * * @param value the NVP to parse * @param parser the parser to use, or <code>null</code> for default * * @return the parsed name-value pair */ public final static NameValuePair parseNameValuePair(final String value, HeaderValueParser parser) throws ParseException { if (value == null) { throw new IllegalArgumentException ("Value to parse may not be null"); } if (parser == null) parser = BasicHeaderValueParser.DEFAULT; CharArrayBuffer buffer = new CharArrayBuffer(value.length()); buffer.append(value); ParserCursor cursor = new ParserCursor(0, value.length()); return parser.parseNameValuePair(buffer, cursor); } // non-javadoc, see interface HeaderValueParser public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor) { return parseNameValuePair(buffer, cursor, ALL_DELIMITERS); } private static boolean isOneOf(final char ch, final char[] chs) { if (chs != null) { for (int i = 0; i < chs.length; i++) { if (ch == chs[i]) { return true; } } } return false; } public NameValuePair parseNameValuePair(final CharArrayBuffer buffer, final ParserCursor cursor, final char[] delimiters) { if (buffer == null) { throw new IllegalArgumentException("Char array buffer may not be null"); } if (cursor == null) { throw new IllegalArgumentException("Parser cursor may not be null"); } boolean terminated = false; int pos = cursor.getPos(); int indexFrom = cursor.getPos(); int indexTo = cursor.getUpperBound(); // Find name String name = null; while (pos < indexTo) { char ch = buffer.charAt(pos); if (ch == '=') { break; } if (isOneOf(ch, delimiters)) { terminated = true; break; } pos++; } if (pos == indexTo) { terminated = true; name = buffer.substringTrimmed(indexFrom, indexTo); } else { name = buffer.substringTrimmed(indexFrom, pos); pos++; } if (terminated) { cursor.updatePos(pos); return createNameValuePair(name, null); } // Find value String value = null; int i1 = pos; boolean qouted = false; boolean escaped = false; while (pos < indexTo) { char ch = buffer.charAt(pos); if (ch == '"' && !escaped) { qouted = !qouted; } if (!qouted && !escaped && isOneOf(ch, delimiters)) { terminated = true; break; } if (escaped) { escaped = false; } else { escaped = qouted && ch == '\\'; } pos++; } int i2 = pos; // Trim leading white spaces while (i1 < i2 && (HTTP.isWhitespace(buffer.charAt(i1)))) { i1++; } // Trim trailing white spaces while ((i2 > i1) && (HTTP.isWhitespace(buffer.charAt(i2 - 1)))) { i2--; } // Strip away quotes if necessary if (((i2 - i1) >= 2) && (buffer.charAt(i1) == '"') && (buffer.charAt(i2 - 1) == '"')) { i1++; i2--; } value = buffer.substring(i1, i2); if (terminated) { pos++; } cursor.updatePos(pos); return createNameValuePair(name, value); } /** * Creates a name-value pair. * Called from {@link #parseNameValuePair}. * * @param name the name * @param value the value, or <code>null</code> * * @return a name-value pair representing the arguments */ protected NameValuePair createNameValuePair(final String name, final String value) { return new BasicNameValuePair(name, value); } }
Java