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.sip; import org.apache.http.FormattedHeader; import org.apache.http.HeaderElement; import org.apache.http.ParseException; import org.apache.http.util.CharArrayBuffer; import org.apache.http.message.ParserCursor; import org.apache.http.message.BasicHeaderValueParser; /** * Represents a SIP (or HTTP) header field parsed 'on demand'. * The name of the header will be parsed and mapped immediately, * the value only when accessed * * */ public class BufferedCompactHeader implements CompactHeader, FormattedHeader, Cloneable { /** The full header name. */ private final String fullName; /** The compact header name, if there is one. */ private final String compactName; /** * The buffer containing the entire header line. */ private final CharArrayBuffer buffer; /** * The beginning of the header value in the buffer */ private final int valuePos; /** * Creates a new header from a buffer. * The name of the header will be parsed and mapped immediately, * the value only if it is accessed. * * @param buffer the buffer containing the header to represent * @param mapper the header name mapper, or <code>null</code> for the * {@link BasicCompactHeaderMapper#DEFAULT default} * * @throws ParseException in case of a parse error */ public BufferedCompactHeader(final CharArrayBuffer buffer, CompactHeaderMapper mapper) throws ParseException { super(); if (buffer == null) { throw new IllegalArgumentException ("Char array buffer may not be null"); } final int colon = buffer.indexOf(':'); if (colon == -1) { throw new ParseException ("Missing colon after header name.\n" + buffer.toString()); } final String name = buffer.substringTrimmed(0, colon); if (name.length() == 0) { throw new ParseException ("Missing header name.\n" + buffer.toString()); } if (mapper == null) mapper = BasicCompactHeaderMapper.DEFAULT; final String altname = mapper.getAlternateName(name); String fname = name; String cname = altname; if ((altname != null) && (name.length() < altname.length())) { // the header uses the compact name fname = altname; cname = name; } this.fullName = fname; this.compactName = cname; this.buffer = buffer; this.valuePos = colon + 1; } // non-javadoc, see interface Header public String getName() { return this.fullName; } // non-javadoc, see interface CompactHeader public String getCompactName() { return this.compactName; } // non-javadoc, see interface Header public String getValue() { return this.buffer.substringTrimmed(this.valuePos, this.buffer.length()); } // non-javadoc, see interface Header public HeaderElement[] getElements() throws ParseException { ParserCursor cursor = new ParserCursor(0, this.buffer.length()); cursor.updatePos(this.valuePos); return BasicHeaderValueParser.DEFAULT .parseElements(this.buffer, cursor); } // non-javadoc, see interface BufferedHeader public int getValuePos() { return this.valuePos; } // non-javadoc, see interface BufferedHeader public CharArrayBuffer getBuffer() { return this.buffer; } @Override public String toString() { return this.buffer.toString(); } @Override public Object clone() throws CloneNotSupportedException { // buffer is considered immutable // no need to make a copy of it 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.http.contrib.sip; import org.apache.http.message.BasicHeader; /** * Represents a SIP (or HTTP) header field with optional compact name. * * */ public class BasicCompactHeader extends BasicHeader implements CompactHeader { private static final long serialVersionUID = -8275767773930430518L; /** The compact name, if there is one. */ private final String compact; /** * Constructor with names and value. * * @param fullname the full header name * @param compactname the compact header name, or <code>null</code> * @param value the header value */ public BasicCompactHeader(final String fullname, final String compactname, final String value) { super(fullname, value); if ((compactname != null) && (compactname.length() >= fullname.length())) { throw new IllegalArgumentException ("Compact name must be shorter than full name. " + compactname + " -> " + fullname); } this.compact = compactname; } // non-javadoc, see interface CompactHeader public String getCompactName() { return this.compact; } /** * Creates a compact header with automatic lookup. * * @param name the header name, either full or compact * @param value the header value * @param mapper the header name mapper, or <code>null</code> for the * {@link BasicCompactHeaderMapper#DEFAULT default} */ public static BasicCompactHeader newHeader(final String name, final String value, CompactHeaderMapper mapper) { if (name == null) { throw new IllegalArgumentException ("The name must not be null."); } // value will be checked by constructor later if (mapper == null) mapper = BasicCompactHeaderMapper.DEFAULT; final String altname = mapper.getAlternateName(name); String fname = name; String cname = altname; if ((altname != null) && (name.length() < altname.length())) { // we were called with the compact name fname = altname; cname = name; } return new BasicCompactHeader(fname, cname, value); } // we might want a toString method that includes the short name, if defined // default cloning implementation is fine }
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.sip; import org.apache.http.HttpException; /** * Signals that an SIP exception has occurred. * This is for protocol errors specific to SIP, * as opposed to protocol errors shared with HTTP. * * */ public class SipException extends HttpException { private static final long serialVersionUID = 337592534308025800L; /** * Creates a new SipException with a <tt>null</tt> detail message. */ public SipException() { super(); } /** * Creates a new SipException with the specified detail message. * * @param message the exception detail message */ public SipException(final String message) { super(message); } /** * Creates a new SipException 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 SipException(final String message, final Throwable cause) { super(message, 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.http.contrib.sip; /** * A mapper between full and compact header names. * RFC 3261 (SIP/2.0), section 7.3.3 specifies that some header field * names have an abbreviated form which is equivalent to the full name. * All compact header names defined for SIP are registered at * <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a>. * <br/> * While all compact names defined so far are single-character names, * RFC 3261 does not mandate that. This interface therefore allows for * strings as the compact name. * * */ public interface CompactHeaderMapper { /** * Obtains the compact name for the given full name. * * @param fullname the header name for which to look up the compact form * * @return the compact form of the argument header name, or * <code>null</code> if there is none */ String getCompactName(String fullname) ; /** * Obtains the full name for the given compact name. * * @param compactname the compact name for which to look up the full name * * @return the full name of the argument compact header name, or * <code>null</code> if there is none */ String getFullName(String compactname) ; /** * Obtains the alternate name for the given header name. * This performs a lookup in both directions, if necessary. * <br/> * If the returned name is shorter than the argument name, * the argument was a full header name and the result is * the compact name. * If the returned name is longer than the argument name, * the argument was a compact header name and the result * is the full name. * If the returned name has the same length as the argument name, * somebody didn't understand the concept of a <i>compact form</i> * when defining the mapping. You should expect malfunctioning * applications in this case. * * @param name the header name to map, either a full or compact name * * @return the alternate header name, or * <code>null</code> if there is none */ String getAlternateName(String name) ; }
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.sip; import java.util.Map; import java.util.HashMap; import java.util.Collections; /** * Basic implementation of a {@link CompactHeaderMapper}. * Header names are assumed to be case insensitive. * * */ public class BasicCompactHeaderMapper implements CompactHeaderMapper { /** * The map from compact names to full names. * Keys are converted to lower case, values may be mixed case. */ protected Map<String,String> mapCompactToFull; /** * The map from full names to compact names. * Keys are converted to lower case, values may be mixed case. */ protected Map<String,String> mapFullToCompact; /** * The default mapper. * This mapper is initialized with the compact header names defined at * <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a> * on 2008-01-02. */ // see below for static initialization public final static CompactHeaderMapper DEFAULT; /** * Creates a new header mapper with an empty mapping. */ public BasicCompactHeaderMapper() { createMaps(); } /** * Initializes the two maps. * The default implementation here creates an empty hash map for * each attribute that is <code>null</code>. * Derived implementations may choose to instantiate other * map implementations, or to populate the maps by default. * In the latter case, it is the responsibility of the dervied class * to guarantee consistent mappings in both directions. */ protected void createMaps() { if (mapCompactToFull == null) { mapCompactToFull = new HashMap<String,String>(); } if (mapFullToCompact == null) { mapFullToCompact = new HashMap<String,String>(); } } /** * Adds a header name mapping. * * @param compact the compact name of the header * @param full the full name of the header */ public void addMapping(final String compact, final String full) { if (compact == null) { throw new IllegalArgumentException ("The compact name must not be null."); } if (full == null) { throw new IllegalArgumentException ("The full name must not be null."); } if (compact.length() >= full.length()) { throw new IllegalArgumentException ("The compact name must be shorter than the full name. " + compact + " -> " + full); } mapCompactToFull.put(compact.toLowerCase(), full); mapFullToCompact.put(full.toLowerCase(), compact); } /** * Switches this mapper to read-only mode. * Subsequent invocations of {@link #addMapping addMapping} * will trigger an exception. * <br/> * The implementation here should be called only once. * It replaces the internal maps with unmodifiable ones. */ protected void makeReadOnly() { mapCompactToFull = Collections.unmodifiableMap(mapCompactToFull); mapFullToCompact = Collections.unmodifiableMap(mapFullToCompact); } // non-javadoc, see interface CompactHeaderMapper public String getCompactName(final String fullname) { if (fullname == null) { throw new IllegalArgumentException ("The full name must not be null."); } return mapFullToCompact.get(fullname.toLowerCase()); } // non-javadoc, see interface CompactHeaderMapper public String getFullName(final String compactname) { if (compactname == null) { throw new IllegalArgumentException ("The compact name must not be null."); } return mapCompactToFull.get(compactname.toLowerCase()); } // non-javadoc, see interface CompactHeaderMapper public String getAlternateName(final String name) { if (name == null) { throw new IllegalArgumentException ("The name must not be null."); } final String namelc = name.toLowerCase(); String result = null; // to minimize lookups, use a heuristic to determine the direction boolean iscompact = name.length() < 2; if (iscompact) { result = mapCompactToFull.get(namelc); } if (result == null) { result = mapFullToCompact.get(namelc); } if ((result == null) && !iscompact) { result = mapCompactToFull.get(namelc); } return result; } // initializes the default mapper and switches it to read-only mode static { BasicCompactHeaderMapper chm = new BasicCompactHeaderMapper(); chm.addMapping("a", "Accept-Contact"); chm.addMapping("u", "Allow-Events"); chm.addMapping("i", "Call-ID"); chm.addMapping("m", "Contact"); chm.addMapping("e", "Content-Encoding"); chm.addMapping("l", "Content-Length"); chm.addMapping("c", "Content-Type"); chm.addMapping("o", "Event"); chm.addMapping("f", "From"); chm.addMapping("y", "Identity"); chm.addMapping("n", "Identity-Info"); chm.addMapping("r", "Refer-To"); chm.addMapping("b", "Referred-By"); chm.addMapping("j", "Reject-Contact"); chm.addMapping("d", "Request-Disposition"); chm.addMapping("x", "Session-Expires"); chm.addMapping("s", "Subject"); chm.addMapping("k", "Supported"); chm.addMapping("t", "To"); chm.addMapping("v", "Via"); chm.makeReadOnly(); DEFAULT = chm; } }
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.sip; /** * Constants enumerating the SIP status codes. * All status codes registered at * <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a> * on 2007-12-30 are listed. * The defining RFCs include RFC 3261 (SIP/2.0), * RFC 3265 (SIP-Specific Event Notification), * RFC 4412 (Communications Resource Priority for SIP), * RFC 4474 (Enhancements for Authenticated Identity Management in SIP), * and others. * * */ public interface SipStatus { // --- 1xx Informational --- /** <tt>100 Trying</tt>. RFC 3261, section 21.1.1. */ public static final int SC_CONTINUE = 100; /** <tt>180 Ringing</tt>. RFC 3261, section 21.1.2. */ public static final int SC_RINGING = 180; /** <tt>181 Call Is Being Forwarded</tt>. RFC 3261, section 21.1.3. */ public static final int SC_CALL_IS_BEING_FORWARDED = 181; /** <tt>182 Queued</tt>. RFC 3261, section 21.1.4. */ public static final int SC_QUEUED = 182; /** <tt>183 Session Progress</tt>. RFC 3261, section 21.1.5. */ public static final int SC_SESSION_PROGRESS = 183; // --- 2xx Successful --- /** <tt>200 OK</tt>. RFC 3261, section 21.2.1. */ public static final int SC_OK = 200; /** <tt>202 Accepted</tt>. RFC 3265, section 6.4. */ public static final int SC_ACCEPTED = 202; // --- 3xx Redirection --- /** <tt>300 Multiple Choices</tt>. RFC 3261, section 21.3.1. */ public static final int SC_MULTIPLE_CHOICES = 300; /** <tt>301 Moved Permanently</tt>. RFC 3261, section 21.3.2. */ public static final int SC_MOVED_PERMANENTLY = 301; /** <tt>302 Moved Temporarily</tt>. RFC 3261, section 21.3.3. */ public static final int SC_MOVED_TEMPORARILY = 302; /** <tt>305 Use Proxy</tt>. RFC 3261, section 21.3.4. */ public static final int SC_USE_PROXY = 305; /** <tt>380 Alternative Service</tt>. RFC 3261, section 21.3.5. */ public static final int SC_ALTERNATIVE_SERVICE = 380; // --- 4xx Request Failure --- /** <tt>400 Bad Request</tt>. RFC 3261, section 21.4.1. */ public static final int SC_BAD_REQUEST = 400; /** <tt>401 Unauthorized</tt>. RFC 3261, section 21.4.2. */ public static final int SC_UNAUTHORIZED = 401; /** <tt>402 Payment Required</tt>. RFC 3261, section 21.4.3. */ public static final int SC_PAYMENT_REQUIRED = 402; /** <tt>403 Forbidden</tt>. RFC 3261, section 21.4.4. */ public static final int SC_FORBIDDEN = 403; /** <tt>404 Not Found</tt>. RFC 3261, section 21.4.5. */ public static final int SC_NOT_FOUND = 404; /** <tt>405 Method Not Allowed</tt>. RFC 3261, section 21.4.6. */ public static final int SC_METHOD_NOT_ALLOWED = 405; /** <tt>406 Not Acceptable</tt>. RFC 3261, section 21.4.7. */ public static final int SC_NOT_ACCEPTABLE = 406; /** * <tt>407 Proxy Authentication Required</tt>. * RFC 3261, section 21.4.8. */ public static final int SC_PROXY_AUTHENTICATION_REQUIRED = 407; /** <tt>408 Request Timeout</tt>. RFC 3261, section 21.4.9. */ public static final int SC_REQUEST_TIMEOUT = 408; /** <tt>410 Gone</tt>. RFC 3261, section 21.4.10. */ public static final int SC_GONE = 410; /** <tt>412 Conditional Request Failed</tt>. RFC 3903, section 11.2.1. */ public static final int SC_CONDITIONAL_REQUEST_FAILED = 412; /** <tt>413 Request Entity Too Large</tt>. RFC 3261, section 21.4.11. */ public static final int SC_REQUEST_ENTITY_TOO_LARGE = 413; /** <tt>414 Request-URI Too Long</tt>. RFC 3261, section 21.4.12. */ public static final int SC_REQUEST_URI_TOO_LONG = 414; /** <tt>415 Unsupported Media Type</tt>. RFC 3261, section 21.4.13. */ public static final int SC_UNSUPPORTED_MEDIA_TYPE = 415; /** <tt>416 Unsupported URI Scheme</tt>. RFC 3261, section 21.4.14. */ public static final int SC_UNSUPPORTED_URI_SCHEME = 416; /** <tt>417 Unknown Resource-Priority</tt>. RFC 4412, section 12.4. */ public static final int SC_UNKNOWN_RESOURCE_PRIORITY = 417; /** <tt>420 Bad Extension</tt>. RFC 3261, section 21.4.15. */ public static final int SC_BAD_EXTENSION = 420; /** <tt>421 Extension Required</tt>. RFC 3261, section 21.4.16. */ public static final int SC_EXTENSION_REQUIRED = 421; /** <tt>422 Session Interval Too Small</tt>. RFC 4028, chapter 6. */ public static final int SC_SESSION_INTERVAL_TOO_SMALL = 422; /** <tt>423 Interval Too Brief</tt>. RFC 3261, section 21.4.17. */ public static final int SC_INTERVAL_TOO_BRIEF = 423; /** <tt>428 Use Identity Header</tt>. RFC 4474, section 14.2. */ public static final int SC_USE_IDENTITY_HEADER = 428; /** <tt>429 Provide Referrer Identity</tt>. RFC 3892, chapter 5. */ public static final int SC_PROVIDE_REFERRER_IDENTITY = 429; /** <tt>433 Anonymity Disallowed</tt>. RFC 5079, chapter 5. */ public static final int SC_ANONYMITY_DISALLOWED = 433; /** <tt>436 Bad Identity-Info</tt>. RFC 4474, section 14.3. */ public static final int SC_BAD_IDENTITY_INFO = 436; /** <tt>437 Unsupported Certificate</tt>. RFC 4474, section 14.4. */ public static final int SC_UNSUPPORTED_CERTIFICATE = 437; /** <tt>438 Invalid Identity Header</tt>. RFC 4474, section 14.5. */ public static final int SC_INVALID_IDENTITY_HEADER = 438; /** <tt>480 Temporarily Unavailable</tt>. RFC 3261, section 21.4.18. */ public static final int SC_TEMPORARILY_UNAVAILABLE = 480; /** * <tt>481 Call/Transaction Does Not Exist</tt>. * RFC 3261, section 21.4.19. */ public static final int SC_CALL_TRANSACTION_DOES_NOT_EXIST = 481; /** <tt>482 Loop Detected</tt>. RFC 3261, section 21.4.20. */ public static final int SC_LOOP_DETECTED = 482; /** <tt>483 Too Many Hops</tt>. RFC 3261, section 21.4.21. */ public static final int SC_TOO_MANY_HOPS = 483; /** <tt>484 Address Incomplete</tt>. RFC 3261, section 21.4.22. */ public static final int SC_ADDRESS_INCOMPLETE = 484; /** <tt>485 Ambiguous</tt>. RFC 3261, section 21.4.23. */ public static final int SC_AMBIGUOUS = 485; /** <tt>486 Busy Here</tt>. RFC 3261, section 21.4.24. */ public static final int SC_BUSY_HERE = 486; /** <tt>487 Request Terminated</tt>. RFC 3261, section 21.4.25. */ public static final int SC_REQUEST_TERMINATED = 487; /** <tt>488 Not Acceptable Here</tt>. RFC 3261, section 21.4.26. */ public static final int SC_NOT_ACCEPTABLE_HERE = 488; /** <tt>489 Bad Event</tt>. RFC 3265, section 6.4. */ public static final int SC_BAD_EVENT = 489; /** <tt>491 Request Pending</tt>. RFC 3261, section 21.4.27. */ public static final int SC_REQUEST_PENDING = 491; /** <tt>493 Undecipherable</tt>. RFC 3261, section 21.4.28. */ public static final int SC_UNDECIPHERABLE = 493; /** <tt>494 Security Agreement Required</tt>. RFC 3329, section 6.4. */ public static final int SC_SECURITY_AGREEMENT_REQUIRED = 494; // --- 5xx Server Failure --- /** <tt>500 Server Internal Error</tt>. RFC 3261, section 21.5.1. */ public static final int SC_SERVER_INTERNAL_ERROR = 500; /** <tt>501 Not Implemented</tt>. RFC 3261, section 21.5.2. */ public static final int SC_NOT_IMPLEMENTED = 501; /** <tt>502 Bad Gateway</tt>. RFC 3261, section 21.5.3. */ public static final int SC_BAD_GATEWAY = 502; /** <tt>503 Service Unavailable</tt>. RFC 3261, section 21.5.4. */ public static final int SC_SERVICE_UNAVAILABLE = 503; /** <tt>504 Server Time-out</tt>. RFC 3261, section 21.5.5. */ public static final int SC_SERVER_TIMEOUT = 504; /** <tt>505 Version Not Supported</tt>. RFC 3261, section 21.5.6. */ public static final int SC_VERSION_NOT_SUPPORTED = 505; /** <tt>513 Message Too Large</tt>. RFC 3261, section 21.5.7. */ public static final int SC_MESSAGE_TOO_LARGE = 513; /** <tt>580 Precondition Failure</tt>. RFC 3312, chapter 8. */ public static final int SC_PRECONDITION_FAILURE = 580; // --- 6xx Global Failures --- /** <tt>600 Busy Everywhere</tt>. RFC 3261, section 21.6.1. */ public static final int SC_BUSY_EVERYWHERE = 600; /** <tt>603 Decline</tt>. RFC 3261, section 21.6.2. */ public static final int SC_DECLINE = 603; /** <tt>604 Does Not Exist Anywhere</tt>. RFC 3261, section 21.6.3. */ public static final int SC_DOES_NOT_EXIST_ANYWHERE = 604; /** * <tt>606 Not Acceptable</tt>. RFC 3261, section 21.6.4. * Status codes 606 and 406 both indicate "Not Acceptable", * but we can only define one constant with that name in this interface. * 406 is specific to an endpoint, while 606 is global and * indicates that the callee will not find the request acceptable * on any endpoint. */ public static final int SC_NOT_ACCEPTABLE_ANYWHERE = 606; }
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.sip; import org.apache.http.Header; import org.apache.http.ParseException; import org.apache.http.util.CharArrayBuffer; import org.apache.http.message.BasicLineParser; /** * Basic parser for lines in the head section of an SIP message. * * */ public class BasicSipLineParser extends BasicLineParser { /** The header name mapper to use, never <code>null</code>. */ protected final CompactHeaderMapper mapper; /** * A default instance of this class, for use as default or fallback. */ public final static BasicSipLineParser DEFAULT = new BasicSipLineParser(null); /** * Creates a new line parser for SIP protocol. * * @param mapper the header name mapper, or <code>null</code> for the * {@link BasicCompactHeaderMapper#DEFAULT default} */ public BasicSipLineParser(CompactHeaderMapper mapper) { super(SipVersion.SIP_2_0); this.mapper = (mapper != null) ? mapper : BasicCompactHeaderMapper.DEFAULT; } // non-javadoc, see interface LineParser @Override public Header parseHeader(CharArrayBuffer buffer) throws ParseException { // the actual parser code is in the constructor of BufferedHeader return new BufferedCompactHeader(buffer, mapper); } }
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.sip; import java.io.Serializable; import org.apache.http.ProtocolVersion; /** * Represents an SIP version, as specified in RFC 3261. * * */ public final class SipVersion extends ProtocolVersion implements Serializable { private static final long serialVersionUID = 6112302080954348220L; /** The protocol name. */ public static final String SIP = "SIP"; /** SIP protocol version 2.0 */ public static final SipVersion SIP_2_0 = new SipVersion(2, 0); /** * Create a SIP protocol version designator. * * @param major the major version number of the SIP protocol * @param minor the minor version number of the SIP protocol * * @throws IllegalArgumentException * if either major or minor version number is negative */ public SipVersion(int major, int minor) { super(SIP, major, minor); } /** * Obtains a specific SIP version. * * @param major the major version * @param minor the minor version * * @return an instance of {@link SipVersion} with the argument version */ @Override public ProtocolVersion forVersion(int major, int minor) { if ((major == this.major) && (minor == this.minor)) { return this; } if ((major == 2) && (minor == 0)) { return SIP_2_0; } // argument checking is done in the constructor return new SipVersion(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.http.contrib.sip; import java.util.Locale; import java.util.Map; import java.util.HashMap; import org.apache.http.ReasonPhraseCatalog; /** * English reason phrases for SIP status codes. * All status codes defined in {@link SipStatus} are supported. * See <a href="http://www.iana.org/assignments/sip-parameters"> * http://www.iana.org/assignments/sip-parameters * </a> * for a full list of registered SIP status codes and the defining RFCs. * * */ public class EnglishSipReasonPhraseCatalog implements ReasonPhraseCatalog { // static map with english reason phrases defined below /** * The default instance of this catalog. * This catalog is thread safe, so there typically * is no need to create other instances. */ public final static EnglishSipReasonPhraseCatalog INSTANCE = new EnglishSipReasonPhraseCatalog(); /** * Restricted default constructor, for derived classes. * If you need an instance of this class, use {@link #INSTANCE INSTANCE}. */ protected EnglishSipReasonPhraseCatalog() { // no body } /** * Obtains the reason phrase for a status code. * * @param status the status code, in the range 100-699 * @param loc ignored * * @return the reason phrase, or <code>null</code> */ public String getReason(int status, Locale loc) { if ((status < 100) || (status >= 700)) { throw new IllegalArgumentException ("Unknown category for status code " + status + "."); } // Unlike HTTP status codes, those for SIP are not compact // in each category. We therefore use a map for lookup. return REASON_PHRASES.get(Integer.valueOf(status)); } /** * Reason phrases lookup table. * Since this attribute is private and never exposed, * we don't need to turn it into an unmodifiable map. */ // see below for static initialization private static final Map<Integer,String> REASON_PHRASES = new HashMap<Integer,String>(); /** * Stores the given reason phrase, by status code. * Helper method to initialize the static lookup map. * * @param status the status code for which to define the phrase * @param reason the reason phrase for this status code */ private static void setReason(int status, String reason) { REASON_PHRASES.put(Integer.valueOf(status), reason); } // ----------------------------------------------------- Static Initializer /** Set up status code to "reason phrase" map. */ static { // --- 1xx Informational --- setReason(SipStatus.SC_CONTINUE, "Trying"); setReason(SipStatus.SC_RINGING, "Ringing"); setReason(SipStatus.SC_CALL_IS_BEING_FORWARDED, "Call Is Being Forwarded"); setReason(SipStatus.SC_QUEUED, "Queued"); setReason(SipStatus.SC_SESSION_PROGRESS, "Session Progress"); // --- 2xx Successful --- setReason(SipStatus.SC_OK, "OK"); setReason(SipStatus.SC_ACCEPTED, "Accepted"); // --- 3xx Redirection --- setReason(SipStatus.SC_MULTIPLE_CHOICES, "Multiple Choices"); setReason(SipStatus.SC_MOVED_PERMANENTLY, "Moved Permanently"); setReason(SipStatus.SC_MOVED_TEMPORARILY, "Moved Temporarily"); setReason(SipStatus.SC_USE_PROXY, "Use Proxy"); setReason(SipStatus.SC_ALTERNATIVE_SERVICE, "Alternative Service"); // --- 4xx Request Failure --- setReason(SipStatus.SC_BAD_REQUEST, "Bad Request"); setReason(SipStatus.SC_UNAUTHORIZED, "Unauthorized"); setReason(SipStatus.SC_PAYMENT_REQUIRED, "Payment Required"); setReason(SipStatus.SC_FORBIDDEN, "Forbidden"); setReason(SipStatus.SC_NOT_FOUND, "Not Found"); setReason(SipStatus.SC_METHOD_NOT_ALLOWED, "Method Not Allowed"); setReason(SipStatus.SC_NOT_ACCEPTABLE, "Not Acceptable"); setReason(SipStatus.SC_PROXY_AUTHENTICATION_REQUIRED, "Proxy Authentication Required"); setReason(SipStatus.SC_REQUEST_TIMEOUT, "Request Timeout"); setReason(SipStatus.SC_GONE, "Gone"); setReason(SipStatus.SC_CONDITIONAL_REQUEST_FAILED, "Conditional Request Failed"); setReason(SipStatus.SC_REQUEST_ENTITY_TOO_LARGE, "Request Entity Too Large"); setReason(SipStatus.SC_REQUEST_URI_TOO_LONG, "Request-URI Too Long"); setReason(SipStatus.SC_UNSUPPORTED_MEDIA_TYPE, "Unsupported Media Type"); setReason(SipStatus.SC_UNSUPPORTED_URI_SCHEME, "Unsupported URI Scheme"); setReason(SipStatus.SC_UNKNOWN_RESOURCE_PRIORITY, "Unknown Resource-Priority"); setReason(SipStatus.SC_BAD_EXTENSION, "Bad Extension"); setReason(SipStatus.SC_EXTENSION_REQUIRED, "Extension Required"); setReason(SipStatus.SC_SESSION_INTERVAL_TOO_SMALL, "Session Interval Too Small"); setReason(SipStatus.SC_INTERVAL_TOO_BRIEF, "Interval Too Brief"); setReason(SipStatus.SC_USE_IDENTITY_HEADER, "Use Identity Header"); setReason(SipStatus.SC_PROVIDE_REFERRER_IDENTITY, "Provide Referrer Identity"); setReason(SipStatus.SC_ANONYMITY_DISALLOWED, "Anonymity Disallowed"); setReason(SipStatus.SC_BAD_IDENTITY_INFO, "Bad Identity-Info"); setReason(SipStatus.SC_UNSUPPORTED_CERTIFICATE, "Unsupported Certificate"); setReason(SipStatus.SC_INVALID_IDENTITY_HEADER, "Invalid Identity Header"); setReason(SipStatus.SC_TEMPORARILY_UNAVAILABLE, "Temporarily Unavailable"); setReason(SipStatus.SC_CALL_TRANSACTION_DOES_NOT_EXIST, "Call/Transaction Does Not Exist"); setReason(SipStatus.SC_LOOP_DETECTED, "Loop Detected"); setReason(SipStatus.SC_TOO_MANY_HOPS, "Too Many Hops"); setReason(SipStatus.SC_ADDRESS_INCOMPLETE, "Address Incomplete"); setReason(SipStatus.SC_AMBIGUOUS, "Ambiguous"); setReason(SipStatus.SC_BUSY_HERE, "Busy Here"); setReason(SipStatus.SC_REQUEST_TERMINATED, "Request Terminated"); setReason(SipStatus.SC_NOT_ACCEPTABLE_HERE, "Not Acceptable Here"); setReason(SipStatus.SC_BAD_EVENT, "Bad Event"); setReason(SipStatus.SC_REQUEST_PENDING, "Request Pending"); setReason(SipStatus.SC_UNDECIPHERABLE, "Undecipherable"); setReason(SipStatus.SC_SECURITY_AGREEMENT_REQUIRED, "Security Agreement Required"); // --- 5xx Server Failure --- setReason(SipStatus.SC_SERVER_INTERNAL_ERROR, "Server Internal Error"); setReason(SipStatus.SC_NOT_IMPLEMENTED, "Not Implemented"); setReason(SipStatus.SC_BAD_GATEWAY, "Bad Gateway"); setReason(SipStatus.SC_SERVICE_UNAVAILABLE, "Service Unavailable"); setReason(SipStatus.SC_SERVER_TIMEOUT, "Server Time-out"); setReason(SipStatus.SC_VERSION_NOT_SUPPORTED, "Version Not Supported"); setReason(SipStatus.SC_MESSAGE_TOO_LARGE, "Message Too Large"); setReason(SipStatus.SC_PRECONDITION_FAILURE, "Precondition Failure"); // --- 6xx Global Failures --- setReason(SipStatus.SC_BUSY_EVERYWHERE, "Busy Everywhere"); setReason(SipStatus.SC_DECLINE, "Decline"); setReason(SipStatus.SC_DOES_NOT_EXIST_ANYWHERE, "Does Not Exist Anywhere"); setReason(SipStatus.SC_NOT_ACCEPTABLE_ANYWHERE, "Not Acceptable"); } // static initializer }
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.logging; import org.apache.http.impl.nio.DefaultClientIOEventDispatch; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpClientIOTarget; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpParams; public class LoggingClientIOEventDispatch extends DefaultClientIOEventDispatch { public LoggingClientIOEventDispatch( final NHttpClientHandler handler, final HttpParams params) { super(new LoggingNHttpClientHandler(handler), params); } @Override protected NHttpClientIOTarget createConnection(final IOSession session) { return new LoggingNHttpClientConnection( new LoggingIOSession(session, "client"), createHttpResponseFactory(), this.allocator, this.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.contrib.logging; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseFactory; import org.apache.http.impl.nio.DefaultNHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.params.HttpParams; public class LoggingNHttpClientConnection extends DefaultNHttpClientConnection { private final Log log; private final Log headerlog; public LoggingNHttpClientConnection( final IOSession session, final HttpResponseFactory responseFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(session, responseFactory, allocator, params); this.log = LogFactory.getLog(getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } @Override public void close() throws IOException { this.log.debug("Close connection"); super.close(); } @Override public void shutdown() throws IOException { this.log.debug("Shutdown connection"); super.shutdown(); } @Override public void submitRequest(final HttpRequest request) throws IOException, HttpException { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + this + ": " + request.getRequestLine().toString()); } super.submitRequest(request); } @Override public void consumeInput(final NHttpClientHandler handler) { this.log.debug("Consume input"); super.consumeInput(handler); } @Override public void produceOutput(final NHttpClientHandler handler) { this.log.debug("Produce output"); super.produceOutput(handler); } @Override protected NHttpMessageWriter<HttpRequest> createRequestWriter( final SessionOutputBuffer buffer, final HttpParams params) { return new LoggingNHttpMessageWriter( super.createRequestWriter(buffer, params)); } @Override protected NHttpMessageParser<HttpResponse> createResponseParser( final SessionInputBuffer buffer, final HttpResponseFactory responseFactory, final HttpParams params) { return new LoggingNHttpMessageParser( super.createResponseParser(buffer, responseFactory, params)); } class LoggingNHttpMessageWriter implements NHttpMessageWriter<HttpRequest> { private final NHttpMessageWriter<HttpRequest> writer; public LoggingNHttpMessageWriter(final NHttpMessageWriter<HttpRequest> writer) { super(); this.writer = writer; } public void reset() { this.writer.reset(); } public void write(final HttpRequest message) throws IOException, HttpException { if (message != null && headerlog.isDebugEnabled()) { headerlog.debug(">> " + message.getRequestLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug(">> " + headers[i].toString()); } } this.writer.write(message); } } class LoggingNHttpMessageParser implements NHttpMessageParser<HttpResponse> { private final NHttpMessageParser<HttpResponse> parser; public LoggingNHttpMessageParser(final NHttpMessageParser<HttpResponse> parser) { super(); this.parser = parser; } public void reset() { this.parser.reset(); } public int fillBuffer(final ReadableByteChannel channel) throws IOException { return this.parser.fillBuffer(channel); } public HttpResponse parse() throws IOException, HttpException { HttpResponse message = this.parser.parse(); if (message != null && headerlog.isDebugEnabled()) { headerlog.debug("<< " + message.getStatusLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug("<< " + headers[i].toString()); } } return 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.http.contrib.logging; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpResponse; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpClientConnection; import org.apache.http.nio.NHttpClientHandler; /** * Decorator class intended to transparently extend an {@link NHttpClientHandler} * with basic event logging capabilities using Commons Logging. * */ public class LoggingNHttpClientHandler implements NHttpClientHandler { private final Log log; private final Log headerlog; private final NHttpClientHandler handler; public LoggingNHttpClientHandler(final NHttpClientHandler handler) { super(); if (handler == null) { throw new IllegalArgumentException("HTTP client handler may not be null"); } this.handler = handler; this.log = LogFactory.getLog(handler.getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } public void connected(final NHttpClientConnection conn, final Object attachment) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Connected (" + attachment + ")"); } this.handler.connected(conn, attachment); } public void closed(final NHttpClientConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Closed"); } this.handler.closed(conn); } public void exception(final NHttpClientConnection conn, final IOException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void exception(final NHttpClientConnection conn, final HttpException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void requestReady(final NHttpClientConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Request ready"); } this.handler.requestReady(conn); } public void outputReady(final NHttpClientConnection conn, final ContentEncoder encoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Output ready"); } this.handler.outputReady(conn, encoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content encoder " + encoder); } } public void responseReceived(final NHttpClientConnection conn) { HttpResponse response = conn.getHttpResponse(); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": " + response.getStatusLine()); } this.handler.responseReceived(conn); if (this.headerlog.isDebugEnabled()) { this.headerlog.debug("<< " + response.getStatusLine().toString()); Header[] headers = response.getAllHeaders(); for (int i = 0; i < headers.length; i++) { this.headerlog.debug("<< " + headers[i].toString()); } } } public void inputReady(final NHttpClientConnection conn, final ContentDecoder decoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Input ready"); } this.handler.inputReady(conn, decoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content decoder " + decoder); } } public void timeout(final NHttpClientConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Timeout"); } this.handler.timeout(conn); } }
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.logging; import java.io.IOException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.NHttpServerConnection; import org.apache.http.nio.NHttpServiceHandler; /** * Decorator class intended to transparently extend an {@link NHttpServiceHandler} * with basic event logging capabilities using Commons Logging. * */ public class LoggingNHttpServiceHandler implements NHttpServiceHandler { private final Log log; private final Log headerlog; private final NHttpServiceHandler handler; public LoggingNHttpServiceHandler(final NHttpServiceHandler handler) { super(); if (handler == null) { throw new IllegalArgumentException("HTTP service handler may not be null"); } this.handler = handler; this.log = LogFactory.getLog(handler.getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } public void connected(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Connected"); } this.handler.connected(conn); } public void closed(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Closed"); } this.handler.closed(conn); } public void exception(final NHttpServerConnection conn, final IOException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void exception(final NHttpServerConnection conn, final HttpException ex) { this.log.error("HTTP connection " + conn + ": " + ex.getMessage(), ex); this.handler.exception(conn, ex); } public void requestReceived(final NHttpServerConnection conn) { HttpRequest request = conn.getHttpRequest(); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": " + request.getRequestLine()); } this.handler.requestReceived(conn); if (this.headerlog.isDebugEnabled()) { this.headerlog.debug(">> " + request.getRequestLine().toString()); Header[] headers = request.getAllHeaders(); for (int i = 0; i < headers.length; i++) { this.headerlog.debug(">> " + headers[i].toString()); } } } public void outputReady(final NHttpServerConnection conn, final ContentEncoder encoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Output ready"); } this.handler.outputReady(conn, encoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content encoder " + encoder); } } public void responseReady(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Response ready"); } this.handler.responseReady(conn); } public void inputReady(final NHttpServerConnection conn, final ContentDecoder decoder) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Input ready"); } this.handler.inputReady(conn, decoder); if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Content decoder " + decoder); } } public void timeout(final NHttpServerConnection conn) { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + conn + ": Timeout"); } this.handler.timeout(conn); } }
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.logging; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.Header; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpRequestFactory; import org.apache.http.HttpResponse; import org.apache.http.impl.nio.DefaultNHttpServerConnection; import org.apache.http.nio.NHttpMessageParser; import org.apache.http.nio.NHttpMessageWriter; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionInputBuffer; import org.apache.http.nio.reactor.SessionOutputBuffer; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.params.HttpParams; public class LoggingNHttpServerConnection extends DefaultNHttpServerConnection { private final Log log; private final Log headerlog; public LoggingNHttpServerConnection( final IOSession session, final HttpRequestFactory requestFactory, final ByteBufferAllocator allocator, final HttpParams params) { super(session, requestFactory, allocator, params); this.log = LogFactory.getLog(getClass()); this.headerlog = LogFactory.getLog("org.apache.http.headers"); } @Override public void close() throws IOException { this.log.debug("Close connection"); super.close(); } @Override public void shutdown() throws IOException { this.log.debug("Shutdown connection"); super.shutdown(); } @Override public void submitResponse(final HttpResponse response) throws IOException, HttpException { if (this.log.isDebugEnabled()) { this.log.debug("HTTP connection " + this + ": " + response.getStatusLine().toString()); } super.submitResponse(response); } @Override public void consumeInput(final NHttpServiceHandler handler) { this.log.debug("Consume input"); super.consumeInput(handler); } @Override public void produceOutput(final NHttpServiceHandler handler) { this.log.debug("Produce output"); super.produceOutput(handler); } @Override protected NHttpMessageWriter<HttpResponse> createResponseWriter( final SessionOutputBuffer buffer, final HttpParams params) { return new LoggingNHttpMessageWriter( super.createResponseWriter(buffer, params)); } @Override protected NHttpMessageParser<HttpRequest> createRequestParser( final SessionInputBuffer buffer, final HttpRequestFactory requestFactory, final HttpParams params) { return new LoggingNHttpMessageParser( super.createRequestParser(buffer, requestFactory, params)); } class LoggingNHttpMessageWriter implements NHttpMessageWriter<HttpResponse> { private final NHttpMessageWriter<HttpResponse> writer; public LoggingNHttpMessageWriter(final NHttpMessageWriter<HttpResponse> writer) { super(); this.writer = writer; } public void reset() { this.writer.reset(); } public void write(final HttpResponse message) throws IOException, HttpException { if (message != null && headerlog.isDebugEnabled()) { headerlog.debug("<< " + message.getStatusLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug("<< " + headers[i].toString()); } } this.writer.write(message); } } class LoggingNHttpMessageParser implements NHttpMessageParser<HttpRequest> { private final NHttpMessageParser<HttpRequest> parser; public LoggingNHttpMessageParser(final NHttpMessageParser<HttpRequest> parser) { super(); this.parser = parser; } public void reset() { this.parser.reset(); } public int fillBuffer(final ReadableByteChannel channel) throws IOException { return this.parser.fillBuffer(channel); } public HttpRequest parse() throws IOException, HttpException { HttpRequest message = this.parser.parse(); if (message != null && headerlog.isDebugEnabled()) { headerlog.debug(">> " + message.getRequestLine().toString()); Header[] headers = message.getAllHeaders(); for (int i = 0; i < headers.length; i++) { headerlog.debug(">> " + headers[i].toString()); } } return 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.http.contrib.logging; import org.apache.http.impl.nio.DefaultServerIOEventDispatch; import org.apache.http.nio.NHttpServerIOTarget; import org.apache.http.nio.NHttpServiceHandler; import org.apache.http.nio.reactor.IOSession; import org.apache.http.params.HttpParams; public class LoggingServerIOEventDispatch extends DefaultServerIOEventDispatch { public LoggingServerIOEventDispatch( final NHttpServiceHandler handler, final HttpParams params) { super(new LoggingNHttpServiceHandler(handler), params); } @Override protected NHttpServerIOTarget createConnection(final IOSession session) { return new LoggingNHttpServerConnection( new LoggingIOSession(session, "server"), createHttpRequestFactory(), this.allocator, this.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.contrib.logging; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.ByteChannel; import java.nio.channels.SelectionKey; import java.util.concurrent.atomic.AtomicLong; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.http.nio.reactor.IOSession; import org.apache.http.nio.reactor.SessionBufferStatus; /** * Decorator class intended to transparently extend an {@link IOSession} * with basic event logging capabilities using Commons Logging. * */ public class LoggingIOSession implements IOSession { private static AtomicLong COUNT = new AtomicLong(0); private final Log log; private final Wire wirelog; private final IOSession session; private final ByteChannel channel; private final String id; public LoggingIOSession(final IOSession session, final String id) { super(); if (session == null) { throw new IllegalArgumentException("I/O session may not be null"); } this.session = session; this.channel = new LoggingByteChannel(); this.id = id + "-" + COUNT.incrementAndGet(); this.log = LogFactory.getLog(session.getClass()); this.wirelog = new Wire(LogFactory.getLog("org.apache.http.wire")); } public ByteChannel channel() { return this.channel; } public SocketAddress getLocalAddress() { return this.session.getLocalAddress(); } public SocketAddress getRemoteAddress() { return this.session.getRemoteAddress(); } public int getEventMask() { return this.session.getEventMask(); } private static String formatOps(int ops) { StringBuffer buffer = new StringBuffer(6); buffer.append('['); if ((ops & SelectionKey.OP_READ) > 0) { buffer.append('r'); } if ((ops & SelectionKey.OP_WRITE) > 0) { buffer.append('w'); } if ((ops & SelectionKey.OP_ACCEPT) > 0) { buffer.append('a'); } if ((ops & SelectionKey.OP_CONNECT) > 0) { buffer.append('c'); } buffer.append(']'); return buffer.toString(); } public void setEventMask(int ops) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set event mask " + formatOps(ops)); } this.session.setEventMask(ops); } public void setEvent(int op) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set event " + formatOps(op)); } this.session.setEvent(op); } public void clearEvent(int op) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Clear event " + formatOps(op)); } this.session.clearEvent(op); } public void close() { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Close"); } this.session.close(); } public int getStatus() { return this.session.getStatus(); } public boolean isClosed() { return this.session.isClosed(); } public void shutdown() { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Shutdown"); } this.session.shutdown(); } public int getSocketTimeout() { return this.session.getSocketTimeout(); } public void setSocketTimeout(int timeout) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set timeout " + timeout); } this.session.setSocketTimeout(timeout); } public void setBufferStatus(final SessionBufferStatus status) { this.session.setBufferStatus(status); } public boolean hasBufferedInput() { return this.session.hasBufferedInput(); } public boolean hasBufferedOutput() { return this.session.hasBufferedOutput(); } public Object getAttribute(final String name) { return this.session.getAttribute(name); } public void setAttribute(final String name, final Object obj) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Set attribute " + name); } this.session.setAttribute(name, obj); } public Object removeAttribute(final String name) { if (this.log.isDebugEnabled()) { this.log.debug("I/O session " + this.id + " " + this.session + ": Remove attribute " + name); } return this.session.removeAttribute(name); } class LoggingByteChannel implements ByteChannel { public int read(final ByteBuffer dst) throws IOException { int bytesRead = session.channel().read(dst); if (log.isDebugEnabled()) { log.debug("I/O session " + id + " " + session + ": " + bytesRead + " bytes read"); } if (bytesRead > 0 && wirelog.isEnabled()) { ByteBuffer b = dst.duplicate(); int p = b.position(); b.limit(p); b.position(p - bytesRead); wirelog.input(b); } return bytesRead; } public int write(final ByteBuffer src) throws IOException { int byteWritten = session.channel().write(src); if (log.isDebugEnabled()) { log.debug("I/O session " + id + " " + session + ": " + byteWritten + " bytes written"); } if (byteWritten > 0 && wirelog.isEnabled()) { ByteBuffer b = src.duplicate(); int p = b.position(); b.limit(p); b.position(p - byteWritten); wirelog.output(b); } return byteWritten; } public void close() throws IOException { if (log.isDebugEnabled()) { log.debug("I/O session " + id + " " + session + ": Channel close"); } session.channel().close(); } public boolean isOpen() { return session.channel().isOpen(); } } }
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.logging; import java.nio.ByteBuffer; import org.apache.commons.logging.Log; class Wire { private final Log log; public Wire(final Log log) { super(); this.log = log; } private void wire(final String header, final byte[] b, int pos, int off) { StringBuilder buffer = new StringBuilder(); for (int i = 0; i < off; i++) { int ch = b[pos + i]; if (ch == 13) { buffer.append("[\\r]"); } else if (ch == 10) { buffer.append("[\\n]\""); buffer.insert(0, "\""); buffer.insert(0, header); this.log.debug(buffer.toString()); buffer.setLength(0); } else if ((ch < 32) || (ch > 127)) { buffer.append("[0x"); buffer.append(Integer.toHexString(ch)); buffer.append("]"); } else { buffer.append((char) ch); } } if (buffer.length() > 0) { buffer.append('\"'); buffer.insert(0, '\"'); buffer.insert(0, header); this.log.debug(buffer.toString()); } } public boolean isEnabled() { return this.log.isDebugEnabled(); } public void output(final byte[] b, int pos, int off) { wire("<< ", b, pos, off); } public void input(final byte[] b, int pos, int off) { wire(">> ", b, pos, off); } public void output(byte[] b) { output(b, 0, b.length); } public void input(byte[] b) { input(b, 0, b.length); } public void output(int b) { output(new byte[] {(byte) b}); } public void input(int b) { input(new byte[] {(byte) b}); } public void output(final ByteBuffer b) { if (b.hasArray()) { output(b.array(), b.arrayOffset() + b.position(), b.remaining()); } else { byte[] tmp = new byte[b.remaining()]; b.get(tmp); output(tmp); } } public void input(final ByteBuffer b) { if (b.hasArray()) { input(b.array(), b.arrayOffset() + b.position(), b.remaining()); } else { byte[] tmp = new byte[b.remaining()]; b.get(tmp); input(tmp); } } }
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 java.io.InputStream; import java.io.OutputStream; import java.util.zip.GZIPOutputStream; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.message.BasicHeader; import org.apache.http.protocol.HTTP; /** * Wrapping entity that compresses content when {@link #writeTo writing}. * * * @since 4.0 */ public class GzipCompressingEntity extends HttpEntityWrapper { private static final String GZIP_CODEC = "gzip"; public GzipCompressingEntity(final HttpEntity entity) { super(entity); } @Override public Header getContentEncoding() { return new BasicHeader(HTTP.CONTENT_ENCODING, GZIP_CODEC); } @Override public long getContentLength() { return -1; } @Override public boolean isChunked() { // force content chunking return true; } @Override public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } GZIPOutputStream gzip = new GZIPOutputStream(outstream); InputStream in = wrappedEntity.getContent(); byte[] tmp = new byte[2048]; int l; while ((l = in.read(tmp)) != -1) { gzip.write(tmp, 0, l); } gzip.close(); } } // class GzipCompressingEntity
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 java.io.InputStream; import java.util.zip.GZIPInputStream; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; /** * Wrapping entity that decompresses {@link #getContent content}. * * * @since 4.0 */ public class GzipDecompressingEntity extends HttpEntityWrapper { public GzipDecompressingEntity(final HttpEntity entity) { super(entity); } @Override public InputStream getContent() throws IOException, IllegalStateException { // the wrapped entity's getContent() decides about repeatability InputStream wrappedin = wrappedEntity.getContent(); return new GZIPInputStream(wrappedin); } @Override public long getContentLength() { // length of ungzipped content not known in advance return -1; } } // class GzipDecompressingEntity
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.Header; import org.apache.http.HeaderElement; import org.apache.http.HttpEntity; import org.apache.http.HttpException; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.HttpResponseInterceptor; import org.apache.http.protocol.HttpContext; import org.apache.http.protocol.ExecutionContext; /** * Server-side interceptor to handle Gzip-encoded responses. * * * @since 4.0 */ public class ResponseGzipCompress implements HttpResponseInterceptor { private static final String ACCEPT_ENCODING = "Accept-Encoding"; 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) { HttpRequest request = (HttpRequest) context.getAttribute(ExecutionContext.HTTP_REQUEST); Header aeheader = request.getFirstHeader(ACCEPT_ENCODING); if (aeheader != null) { HeaderElement[] codecs = aeheader.getElements(); for (int i = 0; i < codecs.length; i++) { if (codecs[i].getName().equalsIgnoreCase(GZIP_CODEC)) { response.setEntity(new GzipCompressingEntity(entity)); 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.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