code
stringlengths 1
2.01M
| repo_name
stringlengths 3
62
| path
stringlengths 1
267
| language
stringclasses 231
values | license
stringclasses 13
values | size
int64 1
2.01M
|
|---|---|---|---|---|---|
/*
* ====================================================================
* 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.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* Output stream that writes data without any transformation. The end of
* the content entity is demarcated by closing the underlying connection
* (EOF condition). Entities transferred using this input stream can be of
* unlimited length.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, the stream will be marked as closed and no further
* output will be permitted.
*
* @since 4.0
*/
public class IdentityOutputStream extends OutputStream {
/**
* Wrapped session output buffer.
*/
private final SessionOutputBuffer out;
/** True if the stream is closed. */
private boolean closed = false;
public IdentityOutputStream(final SessionOutputBuffer out) {
super();
if (out == null) {
throw new IllegalArgumentException("Session output buffer may not be null");
}
this.out = out;
}
/**
* <p>Does not close the underlying socket output.</p>
*
* @throws IOException If an I/O problem occurs.
*/
public void close() throws IOException {
if (!this.closed) {
this.closed = true;
this.out.flush();
}
}
public void flush() throws IOException {
this.out.flush();
}
public void write(byte[] b, int off, int len) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
this.out.write(b, off, len);
}
public void write(byte[] b) throws IOException {
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
this.out.write(b);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/IdentityOutputStream.java
|
Java
|
gpl3
| 3,137
|
/*
* ====================================================================
* 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.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.util.ByteArrayBuffer;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract base class for session output buffers that stream data to
* an arbitrary {@link OutputStream}. This class buffers small chunks of
* output data in an internal byte array for optimal output performance.
* <p>
* {@link #writeLine(CharArrayBuffer)} and {@link #writeLine(String)} methods
* of this class use CR-LF as a line delimiter.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}</li>
* </ul>
* <p>
*
* @since 4.0
*/
public abstract class AbstractSessionOutputBuffer implements SessionOutputBuffer, BufferInfo {
private static final byte[] CRLF = new byte[] {HTTP.CR, HTTP.LF};
private OutputStream outstream;
private ByteArrayBuffer buffer;
private String charset = HTTP.US_ASCII;
private boolean ascii = true;
private int minChunkLimit = 512;
private HttpTransportMetricsImpl metrics;
/**
* Initializes this session output buffer.
*
* @param outstream the destination output stream.
* @param buffersize the size of the internal buffer.
* @param params HTTP parameters.
*/
protected void init(final OutputStream outstream, int buffersize, final HttpParams params) {
if (outstream == null) {
throw new IllegalArgumentException("Input stream may not be null");
}
if (buffersize <= 0) {
throw new IllegalArgumentException("Buffer size may not be negative or zero");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.outstream = outstream;
this.buffer = new ByteArrayBuffer(buffersize);
this.charset = HttpProtocolParams.getHttpElementCharset(params);
this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII)
|| this.charset.equalsIgnoreCase(HTTP.ASCII);
this.minChunkLimit = params.getIntParameter(CoreConnectionPNames.MIN_CHUNK_LIMIT, 512);
this.metrics = createTransportMetrics();
}
/**
* @since 4.1
*/
protected HttpTransportMetricsImpl createTransportMetrics() {
return new HttpTransportMetricsImpl();
}
/**
* @since 4.`1
*/
public int capacity() {
return this.buffer.capacity();
}
/**
* @since 4.1
*/
public int length() {
return this.buffer.length();
}
/**
* @since 4.1
*/
public int available() {
return capacity() - length();
}
protected void flushBuffer() throws IOException {
int len = this.buffer.length();
if (len > 0) {
this.outstream.write(this.buffer.buffer(), 0, len);
this.buffer.clear();
this.metrics.incrementBytesTransferred(len);
}
}
public void flush() throws IOException {
flushBuffer();
this.outstream.flush();
}
public void write(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return;
}
// Do not want to buffer large-ish chunks
// if the byte array is larger then MIN_CHUNK_LIMIT
// write it directly to the output stream
if (len > this.minChunkLimit || len > this.buffer.capacity()) {
// flush the buffer
flushBuffer();
// write directly to the out stream
this.outstream.write(b, off, len);
this.metrics.incrementBytesTransferred(len);
} else {
// Do not let the buffer grow unnecessarily
int freecapacity = this.buffer.capacity() - this.buffer.length();
if (len > freecapacity) {
// flush the buffer
flushBuffer();
}
// buffer
this.buffer.append(b, off, len);
}
}
public void write(final byte[] b) throws IOException {
if (b == null) {
return;
}
write(b, 0, b.length);
}
public void write(int b) throws IOException {
if (this.buffer.isFull()) {
flushBuffer();
}
this.buffer.append(b);
}
/**
* Writes characters from the specified string followed by a line delimiter
* to this session buffer.
* <p>
* This method uses CR-LF as a line delimiter.
*
* @param s the line.
* @exception IOException if an I/O error occurs.
*/
public void writeLine(final String s) throws IOException {
if (s == null) {
return;
}
if (s.length() > 0) {
write(s.getBytes(this.charset));
}
write(CRLF);
}
/**
* Writes characters from the specified char array followed by a line
* delimiter to this session buffer.
* <p>
* This method uses CR-LF as a line delimiter.
*
* @param s the buffer containing chars of the line.
* @exception IOException if an I/O error occurs.
*/
public void writeLine(final CharArrayBuffer s) throws IOException {
if (s == null) {
return;
}
if (this.ascii) {
int off = 0;
int remaining = s.length();
while (remaining > 0) {
int chunk = this.buffer.capacity() - this.buffer.length();
chunk = Math.min(chunk, remaining);
if (chunk > 0) {
this.buffer.append(s, off, chunk);
}
if (this.buffer.isFull()) {
flushBuffer();
}
off += chunk;
remaining -= chunk;
}
} else {
// This is VERY memory inefficient, BUT since non-ASCII charsets are
// NOT meant to be used anyway, there's no point optimizing it
byte[] tmp = s.toString().getBytes(this.charset);
write(tmp);
}
write(CRLF);
}
public HttpTransportMetrics getMetrics() {
return this.metrics;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/AbstractSessionOutputBuffer.java
|
Java
|
gpl3
| 7,925
|
/*
* ====================================================================
* 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.impl.io;
import java.io.IOException;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestFactory;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.RequestLine;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* HTTP request parser that obtain its input from an instance
* of {@link SessionInputBuffer}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class HttpRequestParser extends AbstractMessageParser {
private final HttpRequestFactory requestFactory;
private final CharArrayBuffer lineBuf;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param requestFactory the factory to use to create
* {@link HttpRequest}s.
* @param params HTTP parameters.
*/
public HttpRequestParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpRequestFactory requestFactory,
final HttpParams params) {
super(buffer, parser, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestFactory = requestFactory;
this.lineBuf = new CharArrayBuffer(128);
}
protected HttpMessage parseHead(
final SessionInputBuffer sessionBuffer)
throws IOException, HttpException, ParseException {
this.lineBuf.clear();
int i = sessionBuffer.readLine(this.lineBuf);
if (i == -1) {
throw new ConnectionClosedException("Client closed connection");
}
ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor);
return this.requestFactory.newHttpRequest(requestline);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/HttpRequestParser.java
|
Java
|
gpl3
| 3,696
|
/*
* ====================================================================
* 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.impl.io;
import org.apache.ogt.http.io.HttpTransportMetrics;
/**
* Default implementation of {@link HttpTransportMetrics}.
*
* @since 4.0
*/
public class HttpTransportMetricsImpl implements HttpTransportMetrics {
private long bytesTransferred = 0;
public HttpTransportMetricsImpl() {
super();
}
public long getBytesTransferred() {
return this.bytesTransferred;
}
public void setBytesTransferred(long count) {
this.bytesTransferred = count;
}
public void incrementBytesTransferred(long count) {
this.bytesTransferred += count;
}
public void reset() {
this.bytesTransferred = 0;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/HttpTransportMetricsImpl.java
|
Java
|
gpl3
| 1,891
|
/*
* ====================================================================
* 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.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.SessionInputBuffer;
/**
* Input stream that cuts off after a defined number of bytes. This class
* is used to receive content of HTTP messages where the end of the content
* entity is determined by the value of the <code>Content-Length header</code>.
* Entities transferred using this stream can be maximum {@link Long#MAX_VALUE}
* long.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, it will read until the "end" of its limit on
* close, which allows for the seamless execution of subsequent HTTP 1.1
* requests, while not requiring the client to remember to read the entire
* contents of the response.
*
*
* @since 4.0
*/
public class ContentLengthInputStream extends InputStream {
private static final int BUFFER_SIZE = 2048;
/**
* The maximum number of bytes that can be read from the stream. Subsequent
* read operations will return -1.
*/
private long contentLength;
/** The current position */
private long pos = 0;
/** True if the stream is closed. */
private boolean closed = false;
/**
* Wrapped input stream that all calls are delegated to.
*/
private SessionInputBuffer in = null;
/**
* Wraps a session input buffer and cuts off output after a defined number
* of bytes.
*
* @param in The session input buffer
* @param contentLength The maximum number of bytes that can be read from
* the stream. Subsequent read operations will return -1.
*/
public ContentLengthInputStream(final SessionInputBuffer in, long contentLength) {
super();
if (in == null) {
throw new IllegalArgumentException("Input stream may not be null");
}
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.in = in;
this.contentLength = contentLength;
}
/**
* <p>Reads until the end of the known length of content.</p>
*
* <p>Does not close the underlying socket input, but instead leaves it
* primed to parse the next response.</p>
* @throws IOException If an IO problem occurs.
*/
public void close() throws IOException {
if (!closed) {
try {
if (pos < contentLength) {
byte buffer[] = new byte[BUFFER_SIZE];
while (read(buffer) >= 0) {
}
}
} finally {
// close after above so that we don't throw an exception trying
// to read after closed!
closed = true;
}
}
}
public int available() throws IOException {
if (this.in instanceof BufferInfo) {
int len = ((BufferInfo) this.in).length();
return Math.min(len, (int) (this.contentLength - this.pos));
} else {
return 0;
}
}
/**
* Read the next byte from the stream
* @return The next byte or -1 if the end of stream has been reached.
* @throws IOException If an IO problem occurs
* @see java.io.InputStream#read()
*/
public int read() throws IOException {
if (closed) {
throw new IOException("Attempted read from closed stream.");
}
if (pos >= contentLength) {
return -1;
}
int b = this.in.read();
if (b == -1) {
if (pos < contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ contentLength + "; received: " + pos);
}
} else {
pos++;
}
return b;
}
/**
* Does standard {@link InputStream#read(byte[], int, int)} behavior, but
* also notifies the watcher when the contents have been consumed.
*
* @param b The byte array to fill.
* @param off Start filling at this position.
* @param len The number of bytes to attempt to read.
* @return The number of bytes read, or -1 if the end of content has been
* reached.
*
* @throws java.io.IOException Should an error occur on the wrapped stream.
*/
public int read (byte[] b, int off, int len) throws java.io.IOException {
if (closed) {
throw new IOException("Attempted read from closed stream.");
}
if (pos >= contentLength) {
return -1;
}
if (pos + len > contentLength) {
len = (int) (contentLength - pos);
}
int count = this.in.read(b, off, len);
if (count == -1 && pos < contentLength) {
throw new ConnectionClosedException(
"Premature end of Content-Length delimited message body (expected: "
+ contentLength + "; received: " + pos);
}
if (count > 0) {
pos += count;
}
return count;
}
/**
* Read more bytes from the stream.
* @param b The byte array to put the new data in.
* @return The number of bytes read into the buffer.
* @throws IOException If an IO problem occurs
* @see java.io.InputStream#read(byte[])
*/
public int read(byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Skips and discards a number of bytes from the input stream.
* @param n The number of bytes to skip.
* @return The actual number of bytes skipped. <= 0 if no bytes
* are skipped.
* @throws IOException If an error occurs while skipping bytes.
* @see InputStream#skip(long)
*/
public long skip(long n) throws IOException {
if (n <= 0) {
return 0;
}
byte[] buffer = new byte[BUFFER_SIZE];
// make sure we don't skip more bytes than are
// still available
long remaining = Math.min(n, this.contentLength - this.pos);
// skip and keep track of the bytes actually skipped
long count = 0;
while (remaining > 0) {
int l = read(buffer, 0, (int)Math.min(BUFFER_SIZE, remaining));
if (l == -1) {
break;
}
count += l;
remaining -= l;
}
return count;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/ContentLengthInputStream.java
|
Java
|
gpl3
| 7,804
|
/*
* ====================================================================
* 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.impl.io;
import java.io.IOException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.params.HttpParams;
/**
* HTTP response writer that serializes its output to an instance
* of {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public class HttpResponseWriter extends AbstractMessageWriter {
public HttpResponseWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
protected void writeHeadLine(final HttpMessage message)
throws IOException {
lineFormatter.formatStatusLine(this.lineBuf,
((HttpResponse) message).getStatusLine());
this.sessionBuffer.writeLine(this.lineBuf);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/HttpResponseWriter.java
|
Java
|
gpl3
| 2,166
|
/*
* ====================================================================
* 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.impl.io;
import java.io.IOException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.params.HttpParams;
/**
* HTTP request writer that serializes its output to an instance
* of {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public class HttpRequestWriter extends AbstractMessageWriter {
public HttpRequestWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super(buffer, formatter, params);
}
protected void writeHeadLine(final HttpMessage message)
throws IOException {
lineFormatter.formatRequestLine(this.lineBuf,
((HttpRequest) message).getRequestLine());
this.sessionBuffer.writeLine(this.lineBuf);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/HttpRequestWriter.java
|
Java
|
gpl3
| 2,161
|
/*
* ====================================================================
* 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.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.MalformedChunkCodingException;
import org.apache.ogt.http.TruncatedChunkException;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.ExceptionUtils;
/**
* Implements chunked transfer coding. The content is received in small chunks.
* Entities transferred using this input stream can be of unlimited length.
* After the stream is read to the end, it provides access to the trailers,
* if any.
* <p>
* Note that this class NEVER closes the underlying stream, even when close
* gets called. Instead, it will read until the "end" of its chunking on
* close, which allows for the seamless execution of subsequent HTTP 1.1
* requests, while not requiring the client to remember to read the entire
* contents of the response.
*
*
* @since 4.0
*
*/
public class ChunkedInputStream extends InputStream {
private static final int CHUNK_LEN = 1;
private static final int CHUNK_DATA = 2;
private static final int CHUNK_CRLF = 3;
private static final int BUFFER_SIZE = 2048;
/** The session input buffer */
private final SessionInputBuffer in;
private final CharArrayBuffer buffer;
private int state;
/** The chunk size */
private int chunkSize;
/** The current position within the current chunk */
private int pos;
/** True if we've reached the end of stream */
private boolean eof = false;
/** True if this stream is closed */
private boolean closed = false;
private Header[] footers = new Header[] {};
/**
* Wraps session input stream and reads chunk coded input.
*
* @param in The session input buffer
*/
public ChunkedInputStream(final SessionInputBuffer in) {
super();
if (in == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.in = in;
this.pos = 0;
this.buffer = new CharArrayBuffer(16);
this.state = CHUNK_LEN;
}
public int available() throws IOException {
if (this.in instanceof BufferInfo) {
int len = ((BufferInfo) this.in).length();
return Math.min(len, this.chunkSize - this.pos);
} else {
return 0;
}
}
/**
* <p> Returns all the data in a chunked stream in coalesced form. A chunk
* is followed by a CRLF. The method returns -1 as soon as a chunksize of 0
* is detected.</p>
*
* <p> Trailer headers are read automatically at the end of the stream and
* can be obtained with the getResponseFooters() method.</p>
*
* @return -1 of the end of the stream has been reached or the next data
* byte
* @throws IOException in case of an I/O error
*/
public int read() throws IOException {
if (this.closed) {
throw new IOException("Attempted read from closed stream.");
}
if (this.eof) {
return -1;
}
if (state != CHUNK_DATA) {
nextChunk();
if (this.eof) {
return -1;
}
}
int b = in.read();
if (b != -1) {
pos++;
if (pos >= chunkSize) {
state = CHUNK_CRLF;
}
}
return b;
}
/**
* Read some bytes from the stream.
* @param b The byte array that will hold the contents from the stream.
* @param off The offset into the byte array at which bytes will start to be
* placed.
* @param len the maximum number of bytes that can be returned.
* @return The number of bytes returned or -1 if the end of stream has been
* reached.
* @throws IOException in case of an I/O error
*/
public int read (byte[] b, int off, int len) throws IOException {
if (closed) {
throw new IOException("Attempted read from closed stream.");
}
if (eof) {
return -1;
}
if (state != CHUNK_DATA) {
nextChunk();
if (eof) {
return -1;
}
}
len = Math.min(len, chunkSize - pos);
int bytesRead = in.read(b, off, len);
if (bytesRead != -1) {
pos += bytesRead;
if (pos >= chunkSize) {
state = CHUNK_CRLF;
}
return bytesRead;
} else {
eof = true;
throw new TruncatedChunkException("Truncated chunk "
+ "( expected size: " + chunkSize
+ "; actual size: " + pos + ")");
}
}
/**
* Read some bytes from the stream.
* @param b The byte array that will hold the contents from the stream.
* @return The number of bytes returned or -1 if the end of stream has been
* reached.
* @throws IOException in case of an I/O error
*/
public int read (byte[] b) throws IOException {
return read(b, 0, b.length);
}
/**
* Read the next chunk.
* @throws IOException in case of an I/O error
*/
private void nextChunk() throws IOException {
chunkSize = getChunkSize();
if (chunkSize < 0) {
throw new MalformedChunkCodingException("Negative chunk size");
}
state = CHUNK_DATA;
pos = 0;
if (chunkSize == 0) {
eof = true;
parseTrailerHeaders();
}
}
/**
* Expects the stream to start with a chunksize in hex with optional
* comments after a semicolon. The line must end with a CRLF: "a3; some
* comment\r\n" Positions the stream at the start of the next line.
*
* @param in The new input stream.
* @param required <tt>true<tt/> if a valid chunk must be present,
* <tt>false<tt/> otherwise.
*
* @return the chunk size as integer
*
* @throws IOException when the chunk size could not be parsed
*/
private int getChunkSize() throws IOException {
int st = this.state;
switch (st) {
case CHUNK_CRLF:
this.buffer.clear();
int i = this.in.readLine(this.buffer);
if (i == -1) {
return 0;
}
if (!this.buffer.isEmpty()) {
throw new MalformedChunkCodingException(
"Unexpected content at the end of chunk");
}
state = CHUNK_LEN;
//$FALL-THROUGH$
case CHUNK_LEN:
this.buffer.clear();
i = this.in.readLine(this.buffer);
if (i == -1) {
return 0;
}
int separator = this.buffer.indexOf(';');
if (separator < 0) {
separator = this.buffer.length();
}
try {
return Integer.parseInt(this.buffer.substringTrimmed(0, separator), 16);
} catch (NumberFormatException e) {
throw new MalformedChunkCodingException("Bad chunk header");
}
default:
throw new IllegalStateException("Inconsistent codec state");
}
}
/**
* Reads and stores the Trailer headers.
* @throws IOException in case of an I/O error
*/
private void parseTrailerHeaders() throws IOException {
try {
this.footers = AbstractMessageParser.parseHeaders
(in, -1, -1, null);
} catch (HttpException e) {
IOException ioe = new MalformedChunkCodingException("Invalid footer: "
+ e.getMessage());
ExceptionUtils.initCause(ioe, e);
throw ioe;
}
}
/**
* Upon close, this reads the remainder of the chunked message,
* leaving the underlying socket at a position to start reading the
* next response without scanning.
* @throws IOException in case of an I/O error
*/
public void close() throws IOException {
if (!closed) {
try {
if (!eof) {
// read and discard the remainder of the message
byte buffer[] = new byte[BUFFER_SIZE];
while (read(buffer) >= 0) {
}
}
} finally {
eof = true;
closed = true;
}
}
}
public Header[] getFooters() {
return (Header[])this.footers.clone();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/ChunkedInputStream.java
|
Java
|
gpl3
| 9,948
|
/*
* ====================================================================
* 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.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.impl.io.SocketInputBuffer;
import org.apache.ogt.http.impl.io.SocketOutputBuffer;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Implementation of a server-side HTTP connection that can be bound to a
* network Socket in order to receive and transmit data.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public class SocketHttpServerConnection extends
AbstractHttpServerConnection implements HttpInetConnection {
private volatile boolean open;
private volatile Socket socket = null;
public SocketHttpServerConnection() {
super();
}
protected void assertNotOpen() {
if (this.open) {
throw new IllegalStateException("Connection is already open");
}
}
protected void assertOpen() {
if (!this.open) {
throw new IllegalStateException("Connection is not open");
}
}
/**
* @deprecated Use {@link #createSessionInputBuffer(Socket, int, HttpParams)}
*/
protected SessionInputBuffer createHttpDataReceiver(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return createSessionInputBuffer(socket, buffersize, params);
}
/**
* @deprecated Use {@link #createSessionOutputBuffer(Socket, int, HttpParams)}
*/
protected SessionOutputBuffer createHttpDataTransmitter(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return createSessionOutputBuffer(socket, buffersize, params);
}
/**
* Creates an instance of {@link SocketInputBuffer} to be used for
* receiving data from the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SessionInputBuffer} interface.
*
* @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session input buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionInputBuffer createSessionInputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketInputBuffer(socket, buffersize, params);
}
/**
* Creates an instance of {@link SessionOutputBuffer} to be used for
* sending data to the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SocketOutputBuffer} interface.
*
* @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session output buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionOutputBuffer createSessionOutputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketOutputBuffer(socket, buffersize, params);
}
/**
* Binds this connection to the given {@link Socket}. This socket will be
* used by the connection to send and receive data.
* <p>
* This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)}
* and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods
* to create session input / output buffers bound to this socket and then
* will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)}
* method to pass references to those buffers to the underlying HTTP message
* parser and formatter.
* <p>
* After this method's execution the connection status will be reported
* as open and the {@link #isOpen()} will return <code>true</code>.
*
* @param socket the socket.
* @param params HTTP parameters.
* @throws IOException in case of an I/O error.
*/
protected void bind(final Socket socket, final HttpParams params) throws IOException {
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.socket = socket;
int buffersize = HttpConnectionParams.getSocketBufferSize(params);
init(
createHttpDataReceiver(socket, buffersize, params),
createHttpDataTransmitter(socket, buffersize, params),
params);
this.open = true;
}
protected Socket getSocket() {
return this.socket;
}
public boolean isOpen() {
return this.open;
}
public InetAddress getLocalAddress() {
if (this.socket != null) {
return this.socket.getLocalAddress();
} else {
return null;
}
}
public int getLocalPort() {
if (this.socket != null) {
return this.socket.getLocalPort();
} else {
return -1;
}
}
public InetAddress getRemoteAddress() {
if (this.socket != null) {
return this.socket.getInetAddress();
} else {
return null;
}
}
public int getRemotePort() {
if (this.socket != null) {
return this.socket.getPort();
} else {
return -1;
}
}
public void setSocketTimeout(int timeout) {
assertOpen();
if (this.socket != null) {
try {
this.socket.setSoTimeout(timeout);
} catch (SocketException ignore) {
// It is not quite clear from the Sun's documentation if there are any
// other legitimate cases for a socket exception to be thrown when setting
// SO_TIMEOUT besides the socket being already closed
}
}
}
public int getSocketTimeout() {
if (this.socket != null) {
try {
return this.socket.getSoTimeout();
} catch (SocketException ignore) {
return -1;
}
} else {
return -1;
}
}
public void shutdown() throws IOException {
this.open = false;
Socket tmpsocket = this.socket;
if (tmpsocket != null) {
tmpsocket.close();
}
}
public void close() throws IOException {
if (!this.open) {
return;
}
this.open = false;
this.open = false;
Socket sock = this.socket;
try {
doFlush();
try {
try {
sock.shutdownOutput();
} catch (IOException ignore) {
}
try {
sock.shutdownInput();
} catch (IOException ignore) {
}
} catch (UnsupportedOperationException ignore) {
// if one isn't supported, the other one isn't either
}
} finally {
sock.close();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/SocketHttpServerConnection.java
|
Java
|
gpl3
| 9,427
|
/*
* ====================================================================
* 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.impl;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import org.apache.ogt.http.HttpInetConnection;
import org.apache.ogt.http.impl.io.SocketInputBuffer;
import org.apache.ogt.http.impl.io.SocketOutputBuffer;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Implementation of a client-side HTTP connection that can be bound to an
* arbitrary {@link Socket} for receiving data from and transmitting data to
* a remote server.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public class SocketHttpClientConnection
extends AbstractHttpClientConnection implements HttpInetConnection {
private volatile boolean open;
private volatile Socket socket = null;
public SocketHttpClientConnection() {
super();
}
protected void assertNotOpen() {
if (this.open) {
throw new IllegalStateException("Connection is already open");
}
}
protected void assertOpen() {
if (!this.open) {
throw new IllegalStateException("Connection is not open");
}
}
/**
* Creates an instance of {@link SocketInputBuffer} to be used for
* receiving data from the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SessionInputBuffer} interface.
*
* @see SocketInputBuffer#SocketInputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session input buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionInputBuffer createSessionInputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketInputBuffer(socket, buffersize, params);
}
/**
* Creates an instance of {@link SessionOutputBuffer} to be used for
* sending data to the given {@link Socket}.
* <p>
* This method can be overridden in a super class in order to provide
* a custom implementation of {@link SocketOutputBuffer} interface.
*
* @see SocketOutputBuffer#SocketOutputBuffer(Socket, int, HttpParams)
*
* @param socket the socket.
* @param buffersize the buffer size.
* @param params HTTP parameters.
* @return session output buffer.
* @throws IOException in case of an I/O error.
*/
protected SessionOutputBuffer createSessionOutputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
return new SocketOutputBuffer(socket, buffersize, params);
}
/**
* Binds this connection to the given {@link Socket}. This socket will be
* used by the connection to send and receive data.
* <p>
* This method will invoke {@link #createSessionInputBuffer(Socket, int, HttpParams)}
* and {@link #createSessionOutputBuffer(Socket, int, HttpParams)} methods
* to create session input / output buffers bound to this socket and then
* will invoke {@link #init(SessionInputBuffer, SessionOutputBuffer, HttpParams)}
* method to pass references to those buffers to the underlying HTTP message
* parser and formatter.
* <p>
* After this method's execution the connection status will be reported
* as open and the {@link #isOpen()} will return <code>true</code>.
*
* @param socket the socket.
* @param params HTTP parameters.
* @throws IOException in case of an I/O error.
*/
protected void bind(
final Socket socket,
final HttpParams params) throws IOException {
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.socket = socket;
int buffersize = HttpConnectionParams.getSocketBufferSize(params);
init(
createSessionInputBuffer(socket, buffersize, params),
createSessionOutputBuffer(socket, buffersize, params),
params);
this.open = true;
}
public boolean isOpen() {
return this.open;
}
protected Socket getSocket() {
return this.socket;
}
public InetAddress getLocalAddress() {
if (this.socket != null) {
return this.socket.getLocalAddress();
} else {
return null;
}
}
public int getLocalPort() {
if (this.socket != null) {
return this.socket.getLocalPort();
} else {
return -1;
}
}
public InetAddress getRemoteAddress() {
if (this.socket != null) {
return this.socket.getInetAddress();
} else {
return null;
}
}
public int getRemotePort() {
if (this.socket != null) {
return this.socket.getPort();
} else {
return -1;
}
}
public void setSocketTimeout(int timeout) {
assertOpen();
if (this.socket != null) {
try {
this.socket.setSoTimeout(timeout);
} catch (SocketException ignore) {
// It is not quite clear from the Sun's documentation if there are any
// other legitimate cases for a socket exception to be thrown when setting
// SO_TIMEOUT besides the socket being already closed
}
}
}
public int getSocketTimeout() {
if (this.socket != null) {
try {
return this.socket.getSoTimeout();
} catch (SocketException ignore) {
return -1;
}
} else {
return -1;
}
}
public void shutdown() throws IOException {
this.open = false;
Socket tmpsocket = this.socket;
if (tmpsocket != null) {
tmpsocket.close();
}
}
public void close() throws IOException {
if (!this.open) {
return;
}
this.open = false;
Socket sock = this.socket;
try {
doFlush();
try {
try {
sock.shutdownOutput();
} catch (IOException ignore) {
}
try {
sock.shutdownInput();
} catch (IOException ignore) {
}
} catch (UnsupportedOperationException ignore) {
// if one isn't supported, the other one isn't either
}
} finally {
sock.close();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/SocketHttpClientConnection.java
|
Java
|
gpl3
| 8,762
|
/*
* ====================================================================
* 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.impl;
import java.util.Locale;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.ReasonPhraseCatalog;
/**
* English reason phrases for HTTP status codes.
* All status codes defined in RFC1945 (HTTP/1.0), RFC2616 (HTTP/1.1), and
* RFC2518 (WebDAV) are supported.
*
* @since 4.0
*/
public class EnglishReasonPhraseCatalog implements ReasonPhraseCatalog {
// static array 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 EnglishReasonPhraseCatalog INSTANCE =
new EnglishReasonPhraseCatalog();
/**
* Restricted default constructor, for derived classes.
* If you need an instance of this class, use {@link #INSTANCE INSTANCE}.
*/
protected EnglishReasonPhraseCatalog() {
// no body
}
/**
* Obtains the reason phrase for a status code.
*
* @param status the status code, in the range 100-599
* @param loc ignored
*
* @return the reason phrase, or <code>null</code>
*/
public String getReason(int status, Locale loc) {
if ((status < 100) || (status >= 600)) {
throw new IllegalArgumentException
("Unknown category for status code " + status + ".");
}
final int category = status / 100;
final int subcode = status - 100*category;
String reason = null;
if (REASON_PHRASES[category].length > subcode)
reason = REASON_PHRASES[category][subcode];
return reason;
}
/** Reason phrases lookup table. */
private static final String[][] REASON_PHRASES = new String[][]{
null,
new String[3], // 1xx
new String[8], // 2xx
new String[8], // 3xx
new String[25], // 4xx
new String[8] // 5xx
};
/**
* Stores the given reason phrase, by status code.
* Helper method to initialize the static lookup table.
*
* @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) {
final int category = status / 100;
final int subcode = status - 100*category;
REASON_PHRASES[category][subcode] = reason;
}
// ----------------------------------------------------- Static Initializer
/** Set up status code to "reason phrase" map. */
static {
// HTTP 1.0 Server status codes -- see RFC 1945
setReason(HttpStatus.SC_OK,
"OK");
setReason(HttpStatus.SC_CREATED,
"Created");
setReason(HttpStatus.SC_ACCEPTED,
"Accepted");
setReason(HttpStatus.SC_NO_CONTENT,
"No Content");
setReason(HttpStatus.SC_MOVED_PERMANENTLY,
"Moved Permanently");
setReason(HttpStatus.SC_MOVED_TEMPORARILY,
"Moved Temporarily");
setReason(HttpStatus.SC_NOT_MODIFIED,
"Not Modified");
setReason(HttpStatus.SC_BAD_REQUEST,
"Bad Request");
setReason(HttpStatus.SC_UNAUTHORIZED,
"Unauthorized");
setReason(HttpStatus.SC_FORBIDDEN,
"Forbidden");
setReason(HttpStatus.SC_NOT_FOUND,
"Not Found");
setReason(HttpStatus.SC_INTERNAL_SERVER_ERROR,
"Internal Server Error");
setReason(HttpStatus.SC_NOT_IMPLEMENTED,
"Not Implemented");
setReason(HttpStatus.SC_BAD_GATEWAY,
"Bad Gateway");
setReason(HttpStatus.SC_SERVICE_UNAVAILABLE,
"Service Unavailable");
// HTTP 1.1 Server status codes -- see RFC 2048
setReason(HttpStatus.SC_CONTINUE,
"Continue");
setReason(HttpStatus.SC_TEMPORARY_REDIRECT,
"Temporary Redirect");
setReason(HttpStatus.SC_METHOD_NOT_ALLOWED,
"Method Not Allowed");
setReason(HttpStatus.SC_CONFLICT,
"Conflict");
setReason(HttpStatus.SC_PRECONDITION_FAILED,
"Precondition Failed");
setReason(HttpStatus.SC_REQUEST_TOO_LONG,
"Request Too Long");
setReason(HttpStatus.SC_REQUEST_URI_TOO_LONG,
"Request-URI Too Long");
setReason(HttpStatus.SC_UNSUPPORTED_MEDIA_TYPE,
"Unsupported Media Type");
setReason(HttpStatus.SC_MULTIPLE_CHOICES,
"Multiple Choices");
setReason(HttpStatus.SC_SEE_OTHER,
"See Other");
setReason(HttpStatus.SC_USE_PROXY,
"Use Proxy");
setReason(HttpStatus.SC_PAYMENT_REQUIRED,
"Payment Required");
setReason(HttpStatus.SC_NOT_ACCEPTABLE,
"Not Acceptable");
setReason(HttpStatus.SC_PROXY_AUTHENTICATION_REQUIRED,
"Proxy Authentication Required");
setReason(HttpStatus.SC_REQUEST_TIMEOUT,
"Request Timeout");
setReason(HttpStatus.SC_SWITCHING_PROTOCOLS,
"Switching Protocols");
setReason(HttpStatus.SC_NON_AUTHORITATIVE_INFORMATION,
"Non Authoritative Information");
setReason(HttpStatus.SC_RESET_CONTENT,
"Reset Content");
setReason(HttpStatus.SC_PARTIAL_CONTENT,
"Partial Content");
setReason(HttpStatus.SC_GATEWAY_TIMEOUT,
"Gateway Timeout");
setReason(HttpStatus.SC_HTTP_VERSION_NOT_SUPPORTED,
"Http Version Not Supported");
setReason(HttpStatus.SC_GONE,
"Gone");
setReason(HttpStatus.SC_LENGTH_REQUIRED,
"Length Required");
setReason(HttpStatus.SC_REQUESTED_RANGE_NOT_SATISFIABLE,
"Requested Range Not Satisfiable");
setReason(HttpStatus.SC_EXPECTATION_FAILED,
"Expectation Failed");
// WebDAV Server-specific status codes
setReason(HttpStatus.SC_PROCESSING,
"Processing");
setReason(HttpStatus.SC_MULTI_STATUS,
"Multi-Status");
setReason(HttpStatus.SC_UNPROCESSABLE_ENTITY,
"Unprocessable Entity");
setReason(HttpStatus.SC_INSUFFICIENT_SPACE_ON_RESOURCE,
"Insufficient Space On Resource");
setReason(HttpStatus.SC_METHOD_FAILURE,
"Method Failure");
setReason(HttpStatus.SC_LOCKED,
"Locked");
setReason(HttpStatus.SC_INSUFFICIENT_STORAGE,
"Insufficient Storage");
setReason(HttpStatus.SC_FAILED_DEPENDENCY,
"Failed Dependency");
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/EnglishReasonPhraseCatalog.java
|
Java
|
gpl3
| 8,176
|
/*
* ====================================================================
* 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.impl;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A strategy that never re-uses a connection.
*
* @since 4.0
*/
public class NoConnectionReuseStrategy implements ConnectionReuseStrategy {
// default constructor
// non-JavaDoc, see interface ConnectionReuseStrategy
public boolean keepAlive(final HttpResponse response, final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
if (context == null) {
throw new IllegalArgumentException("HTTP context may not be null");
}
return false;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/NoConnectionReuseStrategy.java
|
Java
|
gpl3
| 1,962
|
/*
* ====================================================================
* 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.impl;
import java.io.IOException;
import org.apache.ogt.http.HttpConnectionMetrics;
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.HttpRequestFactory;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.entity.EntityDeserializer;
import org.apache.ogt.http.impl.entity.EntitySerializer;
import org.apache.ogt.http.impl.entity.LaxContentLengthStrategy;
import org.apache.ogt.http.impl.entity.StrictContentLengthStrategy;
import org.apache.ogt.http.impl.io.HttpRequestParser;
import org.apache.ogt.http.impl.io.HttpResponseWriter;
import org.apache.ogt.http.io.EofSensor;
import org.apache.ogt.http.io.HttpMessageParser;
import org.apache.ogt.http.io.HttpMessageWriter;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.params.HttpParams;
/**
* Abstract server-side HTTP connection capable of transmitting and receiving
* data using arbitrary {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractHttpServerConnection implements HttpServerConnection {
private final EntitySerializer entityserializer;
private final EntityDeserializer entitydeserializer;
private SessionInputBuffer inbuffer = null;
private SessionOutputBuffer outbuffer = null;
private EofSensor eofSensor = null;
private HttpMessageParser requestParser = null;
private HttpMessageWriter responseWriter = null;
private HttpConnectionMetricsImpl metrics = null;
/**
* Creates an instance of this class.
* <p>
* This constructor will invoke {@link #createEntityDeserializer()}
* and {@link #createEntitySerializer()} methods in order to initialize
* HTTP entity serializer and deserializer implementations for this
* connection.
*/
public AbstractHttpServerConnection() {
super();
this.entityserializer = createEntitySerializer();
this.entitydeserializer = createEntityDeserializer();
}
/**
* Asserts if the connection is open.
*
* @throws IllegalStateException if the connection is not open.
*/
protected abstract void assertOpen() throws IllegalStateException;
/**
* Creates an instance of {@link EntityDeserializer} with the
* {@link LaxContentLengthStrategy} implementation to be used for
* de-serializing entities received over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntityDeserializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity deserializer
*/
protected EntityDeserializer createEntityDeserializer() {
return new EntityDeserializer(new LaxContentLengthStrategy());
}
/**
* Creates an instance of {@link EntitySerializer} with the
* {@link StrictContentLengthStrategy} implementation to be used for
* serializing HTTP entities sent over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntitySerializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity serialzier.
*/
protected EntitySerializer createEntitySerializer() {
return new EntitySerializer(new StrictContentLengthStrategy());
}
/**
* Creates an instance of {@link DefaultHttpRequestFactory} to be used
* for creating {@link HttpRequest} objects received by over this
* connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpRequestFactory} interface.
*
* @return HTTP request factory.
*/
protected HttpRequestFactory createHttpRequestFactory() {
return new DefaultHttpRequestFactory();
}
/**
* Creates an instance of {@link HttpMessageParser} to be used for parsing
* HTTP requests received over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageParser} interface or
* to pass a different implementation of {@link LineParser} to the
* the default implementation {@link HttpRequestParser}.
*
* @param buffer the session input buffer.
* @param requestFactory the HTTP request factory.
* @param params HTTP parameters.
* @return HTTP message parser.
*/
protected HttpMessageParser createRequestParser(
final SessionInputBuffer buffer,
final HttpRequestFactory requestFactory,
final HttpParams params) {
return new HttpRequestParser(buffer, null, requestFactory, params);
}
/**
* Creates an instance of {@link HttpMessageWriter} to be used for
* writing out HTTP responses sent over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageWriter} interface or
* to pass a different implementation of {@link LineFormatter} to the
* the default implementation {@link HttpResponseWriter}.
*
* @param buffer the session output buffer
* @param params HTTP parameters
* @return HTTP message writer
*/
protected HttpMessageWriter createResponseWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new HttpResponseWriter(buffer, null, params);
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
/**
* Initializes this connection object with {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} instances to be used for sending and
* receiving data. These session buffers can be bound to any arbitrary
* physical output medium.
* <p>
* This method will invoke {@link #createHttpRequestFactory},
* {@link #createRequestParser(SessionInputBuffer, HttpRequestFactory, HttpParams)}
* and {@link #createResponseWriter(SessionOutputBuffer, HttpParams)}
* methods to initialize HTTP request parser and response writer for this
* connection.
*
* @param inbuffer the session input buffer.
* @param outbuffer the session output buffer.
* @param params HTTP parameters.
*/
protected void init(
final SessionInputBuffer inbuffer,
final SessionOutputBuffer outbuffer,
final HttpParams params) {
if (inbuffer == null) {
throw new IllegalArgumentException("Input session buffer may not be null");
}
if (outbuffer == null) {
throw new IllegalArgumentException("Output session buffer may not be null");
}
this.inbuffer = inbuffer;
this.outbuffer = outbuffer;
if (inbuffer instanceof EofSensor) {
this.eofSensor = (EofSensor) inbuffer;
}
this.requestParser = createRequestParser(
inbuffer,
createHttpRequestFactory(),
params);
this.responseWriter = createResponseWriter(
outbuffer, params);
this.metrics = createConnectionMetrics(
inbuffer.getMetrics(),
outbuffer.getMetrics());
}
public HttpRequest receiveRequestHeader()
throws HttpException, IOException {
assertOpen();
HttpRequest request = (HttpRequest) this.requestParser.parse();
this.metrics.incrementRequestCount();
return request;
}
public void receiveRequestEntity(final HttpEntityEnclosingRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, request);
request.setEntity(entity);
}
protected void doFlush() throws IOException {
this.outbuffer.flush();
}
public void flush() throws IOException {
assertOpen();
doFlush();
}
public void sendResponseHeader(final HttpResponse response)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertOpen();
this.responseWriter.write(response);
if (response.getStatusLine().getStatusCode() >= 200) {
this.metrics.incrementResponseCount();
}
}
public void sendResponseEntity(final HttpResponse response)
throws HttpException, IOException {
if (response.getEntity() == null) {
return;
}
this.entityserializer.serialize(
this.outbuffer,
response,
response.getEntity());
}
protected boolean isEof() {
return this.eofSensor != null && this.eofSensor.isEof();
}
public boolean isStale() {
if (!isOpen()) {
return true;
}
if (isEof()) {
return true;
}
try {
this.inbuffer.isDataAvailable(1);
return isEof();
} catch (IOException ex) {
return true;
}
}
public HttpConnectionMetrics getMetrics() {
return this.metrics;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/AbstractHttpServerConnection.java
|
Java
|
gpl3
| 11,647
|
/*
* ====================================================================
* 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.impl;
import java.io.IOException;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpConnectionMetrics;
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.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.entity.EntityDeserializer;
import org.apache.ogt.http.impl.entity.EntitySerializer;
import org.apache.ogt.http.impl.entity.LaxContentLengthStrategy;
import org.apache.ogt.http.impl.entity.StrictContentLengthStrategy;
import org.apache.ogt.http.impl.io.HttpRequestWriter;
import org.apache.ogt.http.impl.io.HttpResponseParser;
import org.apache.ogt.http.io.EofSensor;
import org.apache.ogt.http.io.HttpMessageParser;
import org.apache.ogt.http.io.HttpMessageWriter;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.params.HttpParams;
/**
* Abstract client-side HTTP connection capable of transmitting and receiving
* data using arbitrary {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} implementations.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* </ul>
*
* @since 4.0
*/
public abstract class AbstractHttpClientConnection implements HttpClientConnection {
private final EntitySerializer entityserializer;
private final EntityDeserializer entitydeserializer;
private SessionInputBuffer inbuffer = null;
private SessionOutputBuffer outbuffer = null;
private EofSensor eofSensor = null;
private HttpMessageParser responseParser = null;
private HttpMessageWriter requestWriter = null;
private HttpConnectionMetricsImpl metrics = null;
/**
* Creates an instance of this class.
* <p>
* This constructor will invoke {@link #createEntityDeserializer()}
* and {@link #createEntitySerializer()} methods in order to initialize
* HTTP entity serializer and deserializer implementations for this
* connection.
*/
public AbstractHttpClientConnection() {
super();
this.entityserializer = createEntitySerializer();
this.entitydeserializer = createEntityDeserializer();
}
/**
* Asserts if the connection is open.
*
* @throws IllegalStateException if the connection is not open.
*/
protected abstract void assertOpen() throws IllegalStateException;
/**
* Creates an instance of {@link EntityDeserializer} with the
* {@link LaxContentLengthStrategy} implementation to be used for
* de-serializing entities received over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntityDeserializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity deserializer
*/
protected EntityDeserializer createEntityDeserializer() {
return new EntityDeserializer(new LaxContentLengthStrategy());
}
/**
* Creates an instance of {@link EntitySerializer} with the
* {@link StrictContentLengthStrategy} implementation to be used for
* serializing HTTP entities sent over this connection.
* <p>
* This method can be overridden in a super class in order to create
* instances of {@link EntitySerializer} using a custom
* {@link ContentLengthStrategy}.
*
* @return HTTP entity serialzier.
*/
protected EntitySerializer createEntitySerializer() {
return new EntitySerializer(new StrictContentLengthStrategy());
}
/**
* Creates an instance of {@link DefaultHttpResponseFactory} to be used
* for creating {@link HttpResponse} objects received by over this
* connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpResponseFactory} interface.
*
* @return HTTP response factory.
*/
protected HttpResponseFactory createHttpResponseFactory() {
return new DefaultHttpResponseFactory();
}
/**
* Creates an instance of {@link HttpMessageParser} to be used for parsing
* HTTP responses received over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageParser} interface or
* to pass a different implementation of {@link LineParser} to the
* the default implementation {@link HttpResponseParser}.
*
* @param buffer the session input buffer.
* @param responseFactory the HTTP response factory.
* @param params HTTP parameters.
* @return HTTP message parser.
*/
protected HttpMessageParser createResponseParser(
final SessionInputBuffer buffer,
final HttpResponseFactory responseFactory,
final HttpParams params) {
return new HttpResponseParser(buffer, null, responseFactory, params);
}
/**
* Creates an instance of {@link HttpMessageWriter} to be used for
* writing out HTTP requests sent over this connection.
* <p>
* This method can be overridden in a super class in order to provide
* a different implementation of the {@link HttpMessageWriter} interface or
* to pass a different implementation of {@link LineFormatter} to the
* the default implementation {@link HttpRequestWriter}.
*
* @param buffer the session output buffer
* @param params HTTP parameters
* @return HTTP message writer
*/
protected HttpMessageWriter createRequestWriter(
final SessionOutputBuffer buffer,
final HttpParams params) {
return new HttpRequestWriter(buffer, null, params);
}
/**
* @since 4.1
*/
protected HttpConnectionMetricsImpl createConnectionMetrics(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
return new HttpConnectionMetricsImpl(inTransportMetric, outTransportMetric);
}
/**
* Initializes this connection object with {@link SessionInputBuffer} and
* {@link SessionOutputBuffer} instances to be used for sending and
* receiving data. These session buffers can be bound to any arbitrary
* physical output medium.
* <p>
* This method will invoke {@link #createHttpResponseFactory()},
* {@link #createRequestWriter(SessionOutputBuffer, HttpParams)}
* and {@link #createResponseParser(SessionInputBuffer, HttpResponseFactory, HttpParams)}
* methods to initialize HTTP request writer and response parser for this
* connection.
*
* @param inbuffer the session input buffer.
* @param outbuffer the session output buffer.
* @param params HTTP parameters.
*/
protected void init(
final SessionInputBuffer inbuffer,
final SessionOutputBuffer outbuffer,
final HttpParams params) {
if (inbuffer == null) {
throw new IllegalArgumentException("Input session buffer may not be null");
}
if (outbuffer == null) {
throw new IllegalArgumentException("Output session buffer may not be null");
}
this.inbuffer = inbuffer;
this.outbuffer = outbuffer;
if (inbuffer instanceof EofSensor) {
this.eofSensor = (EofSensor) inbuffer;
}
this.responseParser = createResponseParser(
inbuffer,
createHttpResponseFactory(),
params);
this.requestWriter = createRequestWriter(
outbuffer, params);
this.metrics = createConnectionMetrics(
inbuffer.getMetrics(),
outbuffer.getMetrics());
}
public boolean isResponseAvailable(int timeout) throws IOException {
assertOpen();
return this.inbuffer.isDataAvailable(timeout);
}
public void sendRequestHeader(final HttpRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
this.requestWriter.write(request);
this.metrics.incrementRequestCount();
}
public void sendRequestEntity(final HttpEntityEnclosingRequest request)
throws HttpException, IOException {
if (request == null) {
throw new IllegalArgumentException("HTTP request may not be null");
}
assertOpen();
if (request.getEntity() == null) {
return;
}
this.entityserializer.serialize(
this.outbuffer,
request,
request.getEntity());
}
protected void doFlush() throws IOException {
this.outbuffer.flush();
}
public void flush() throws IOException {
assertOpen();
doFlush();
}
public HttpResponse receiveResponseHeader()
throws HttpException, IOException {
assertOpen();
HttpResponse response = (HttpResponse) this.responseParser.parse();
if (response.getStatusLine().getStatusCode() >= 200) {
this.metrics.incrementResponseCount();
}
return response;
}
public void receiveResponseEntity(final HttpResponse response)
throws HttpException, IOException {
if (response == null) {
throw new IllegalArgumentException("HTTP response may not be null");
}
assertOpen();
HttpEntity entity = this.entitydeserializer.deserialize(this.inbuffer, response);
response.setEntity(entity);
}
protected boolean isEof() {
return this.eofSensor != null && this.eofSensor.isEof();
}
public boolean isStale() {
if (!isOpen()) {
return true;
}
if (isEof()) {
return true;
}
try {
this.inbuffer.isDataAvailable(1);
return isEof();
} catch (IOException ex) {
return true;
}
}
public HttpConnectionMetrics getMetrics() {
return this.metrics;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/AbstractHttpClientConnection.java
|
Java
|
gpl3
| 11,965
|
/*
* ====================================================================
* 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.impl;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HeaderIterator;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.TokenIterator;
import org.apache.ogt.http.message.BasicTokenIterator;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default implementation of a strategy deciding about connection re-use.
* The default implementation first checks some basics, for example
* whether the connection is still open or whether the end of the
* request entity can be determined without closing the connection.
* If these checks pass, the tokens in the <code>Connection</code> header will
* be examined. In the absence of a <code>Connection</code> header, the
* non-standard but commonly used <code>Proxy-Connection</code> header takes
* it's role. A token <code>close</code> indicates that the connection cannot
* be reused. If there is no such token, a token <code>keep-alive</code>
* indicates that the connection should be re-used. If neither token is found,
* or if there are no <code>Connection</code> headers, the default policy for
* the HTTP version is applied. Since <code>HTTP/1.1</code>, connections are
* re-used by default. Up until <code>HTTP/1.0</code>, connections are not
* re-used by default.
*
* @since 4.0
*/
public class DefaultConnectionReuseStrategy implements ConnectionReuseStrategy {
public DefaultConnectionReuseStrategy() {
super();
}
// see interface ConnectionReuseStrategy
public boolean keepAlive(final HttpResponse response,
final HttpContext context) {
if (response == null) {
throw new IllegalArgumentException
("HTTP response may not be null.");
}
if (context == null) {
throw new IllegalArgumentException
("HTTP context may not be null.");
}
HttpConnection conn = (HttpConnection)
context.getAttribute(ExecutionContext.HTTP_CONNECTION);
if (conn != null && !conn.isOpen())
return false;
// do NOT check for stale connection, that is an expensive operation
// Check for a self-terminating entity. If the end of the entity will
// be indicated by closing the connection, there is no keep-alive.
HttpEntity entity = response.getEntity();
ProtocolVersion ver = response.getStatusLine().getProtocolVersion();
if (entity != null) {
if (entity.getContentLength() < 0) {
if (!entity.isChunked() ||
ver.lessEquals(HttpVersion.HTTP_1_0)) {
// if the content length is not known and is not chunk
// encoded, the connection cannot be reused
return false;
}
}
}
// Check for the "Connection" header. If that is absent, check for
// the "Proxy-Connection" header. The latter is an unspecified and
// broken but unfortunately common extension of HTTP.
HeaderIterator hit = response.headerIterator(HTTP.CONN_DIRECTIVE);
if (!hit.hasNext())
hit = response.headerIterator("Proxy-Connection");
// Experimental usage of the "Connection" header in HTTP/1.0 is
// documented in RFC 2068, section 19.7.1. A token "keep-alive" is
// used to indicate that the connection should be persistent.
// Note that the final specification of HTTP/1.1 in RFC 2616 does not
// include this information. Neither is the "Connection" header
// mentioned in RFC 1945, which informally describes HTTP/1.0.
//
// RFC 2616 specifies "close" as the only connection token with a
// specific meaning: it disables persistent connections.
//
// The "Proxy-Connection" header is not formally specified anywhere,
// but is commonly used to carry one token, "close" or "keep-alive".
// The "Connection" header, on the other hand, is defined as a
// sequence of tokens, where each token is a header name, and the
// token "close" has the above-mentioned additional meaning.
//
// To get through this mess, we treat the "Proxy-Connection" header
// in exactly the same way as the "Connection" header, but only if
// the latter is missing. We scan the sequence of tokens for both
// "close" and "keep-alive". As "close" is specified by RFC 2068,
// it takes precedence and indicates a non-persistent connection.
// If there is no "close" but a "keep-alive", we take the hint.
if (hit.hasNext()) {
try {
TokenIterator ti = createTokenIterator(hit);
boolean keepalive = false;
while (ti.hasNext()) {
final String token = ti.nextToken();
if (HTTP.CONN_CLOSE.equalsIgnoreCase(token)) {
return false;
} else if (HTTP.CONN_KEEP_ALIVE.equalsIgnoreCase(token)) {
// continue the loop, there may be a "close" afterwards
keepalive = true;
}
}
if (keepalive)
return true;
// neither "close" nor "keep-alive", use default policy
} catch (ParseException px) {
// invalid connection header means no persistent connection
// we don't have logging in HttpCore, so the exception is lost
return false;
}
}
// default since HTTP/1.1 is persistent, before it was non-persistent
return !ver.lessEquals(HttpVersion.HTTP_1_0);
}
/**
* Creates a token iterator from a header iterator.
* This method can be overridden to replace the implementation of
* the token iterator.
*
* @param hit the header iterator
*
* @return the token iterator
*/
protected TokenIterator createTokenIterator(HeaderIterator hit) {
return new BasicTokenIterator(hit);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/DefaultConnectionReuseStrategy.java
|
Java
|
gpl3
| 7,665
|
/*
* ====================================================================
* 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.impl;
import java.util.Locale;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.ReasonPhraseCatalog;
import org.apache.ogt.http.StatusLine;
import org.apache.ogt.http.impl.EnglishReasonPhraseCatalog;
import org.apache.ogt.http.message.BasicHttpResponse;
import org.apache.ogt.http.message.BasicStatusLine;
import org.apache.ogt.http.protocol.HttpContext;
/**
* Default factory for creating {@link HttpResponse} objects.
*
* @since 4.0
*/
public class DefaultHttpResponseFactory implements HttpResponseFactory {
/** The catalog for looking up reason phrases. */
protected final ReasonPhraseCatalog reasonCatalog;
/**
* Creates a new response factory with the given catalog.
*
* @param catalog the catalog of reason phrases
*/
public DefaultHttpResponseFactory(ReasonPhraseCatalog catalog) {
if (catalog == null) {
throw new IllegalArgumentException
("Reason phrase catalog must not be null.");
}
this.reasonCatalog = catalog;
}
/**
* Creates a new response factory with the default catalog.
* The default catalog is {@link EnglishReasonPhraseCatalog}.
*/
public DefaultHttpResponseFactory() {
this(EnglishReasonPhraseCatalog.INSTANCE);
}
// non-javadoc, see interface HttpResponseFactory
public HttpResponse newHttpResponse(final ProtocolVersion ver,
final int status,
HttpContext context) {
if (ver == null) {
throw new IllegalArgumentException("HTTP version may not be null");
}
final Locale loc = determineLocale(context);
final String reason = reasonCatalog.getReason(status, loc);
StatusLine statusline = new BasicStatusLine(ver, status, reason);
return new BasicHttpResponse(statusline, reasonCatalog, loc);
}
// non-javadoc, see interface HttpResponseFactory
public HttpResponse newHttpResponse(final StatusLine statusline,
HttpContext context) {
if (statusline == null) {
throw new IllegalArgumentException("Status line may not be null");
}
final Locale loc = determineLocale(context);
return new BasicHttpResponse(statusline, reasonCatalog, loc);
}
/**
* Determines the locale of the response.
* The implementation in this class always returns the default locale.
*
* @param context the context from which to determine the locale, or
* <code>null</code> to use the default locale
*
* @return the locale for the response, never <code>null</code>
*/
protected Locale determineLocale(HttpContext context) {
return Locale.getDefault();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/DefaultHttpResponseFactory.java
|
Java
|
gpl3
| 4,149
|
<html>
<head>
<!--
/*
* ====================================================================
* 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/>.
*
*/
-->
</head>
<body>
Default implementations for interfaces in
{@link org.apache.ogt.http.entity org.apache.ogt.http.entity} and provides utility
classes for serialization and deserialization of HTTP content entities.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/entity/package.html
|
HTML
|
gpl3
| 1,436
|
/*
* ====================================================================
* 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.impl.entity;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.io.ChunkedOutputStream;
import org.apache.ogt.http.impl.io.ContentLengthOutputStream;
import org.apache.ogt.http.impl.io.IdentityOutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* HTTP entity serializer.
* <p>
* This entity serializer currently supports "chunked" and "identitiy"
* transfer-coding and content length delimited content.
* <p>
* This class relies on a specific implementation of
* {@link ContentLengthStrategy} to determine the content length or transfer
* encoding of the entity.
* <p>
* This class writes out the content of {@link HttpEntity} to the data stream
* using a transfer coding based on properties on the HTTP message.
*
* @since 4.0
*/
public class EntitySerializer {
private final ContentLengthStrategy lenStrategy;
public EntitySerializer(final ContentLengthStrategy lenStrategy) {
super();
if (lenStrategy == null) {
throw new IllegalArgumentException("Content length strategy may not be null");
}
this.lenStrategy = lenStrategy;
}
/**
* Creates a transfer codec based on properties of the given HTTP message
* and returns {@link OutputStream} instance that transparently encodes
* output data as it is being written out to the output stream.
* <p>
* This method is called by the public
* {@link #serialize(SessionOutputBuffer, HttpMessage, HttpEntity)}.
*
* @param outbuffer the session output buffer.
* @param message the HTTP message.
* @return output stream.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
protected OutputStream doSerialize(
final SessionOutputBuffer outbuffer,
final HttpMessage message) throws HttpException, IOException {
long len = this.lenStrategy.determineLength(message);
if (len == ContentLengthStrategy.CHUNKED) {
return new ChunkedOutputStream(outbuffer);
} else if (len == ContentLengthStrategy.IDENTITY) {
return new IdentityOutputStream(outbuffer);
} else {
return new ContentLengthOutputStream(outbuffer, len);
}
}
/**
* Writes out the content of the given HTTP entity to the session output
* buffer based on properties of the given HTTP message.
*
* @param outbuffer the output session buffer.
* @param message the HTTP message.
* @param entity the HTTP entity to be written out.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
public void serialize(
final SessionOutputBuffer outbuffer,
final HttpMessage message,
final HttpEntity entity) throws HttpException, IOException {
if (outbuffer == null) {
throw new IllegalArgumentException("Session output buffer may not be null");
}
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
OutputStream outstream = doSerialize(outbuffer, message);
entity.writeTo(outstream);
outstream.close();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/entity/EntitySerializer.java
|
Java
|
gpl3
| 4,833
|
/*
* ====================================================================
* 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.impl.entity;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.protocol.HTTP;
/**
* The strict implementation of the content length strategy. This class
* will throw {@link ProtocolException} if it encounters an unsupported
* transfer encoding or a malformed <code>Content-Length</code> header
* value.
* <p>
* This class recognizes "chunked" and "identitiy" transfer-coding only.
*
* @since 4.0
*/
public class StrictContentLengthStrategy implements ContentLengthStrategy {
public StrictContentLengthStrategy() {
super();
}
public long determineLength(final HttpMessage message) throws HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
// Although Transfer-Encoding is specified as a list, in practice
// it is either missing or has the single value "chunked". So we
// treat it as a single-valued header here.
Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
if (transferEncodingHeader != null) {
String s = transferEncodingHeader.getValue();
if (HTTP.CHUNK_CODING.equalsIgnoreCase(s)) {
if (message.getProtocolVersion().lessEquals(HttpVersion.HTTP_1_0)) {
throw new ProtocolException(
"Chunked transfer encoding not allowed for " +
message.getProtocolVersion());
}
return CHUNKED;
} else if (HTTP.IDENTITY_CODING.equalsIgnoreCase(s)) {
return IDENTITY;
} else {
throw new ProtocolException(
"Unsupported transfer encoding: " + s);
}
} else if (contentLengthHeader != null) {
String s = contentLengthHeader.getValue();
try {
long len = Long.parseLong(s);
return len;
} catch (NumberFormatException e) {
throw new ProtocolException("Invalid content length: " + s);
}
} else {
return IDENTITY;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/entity/StrictContentLengthStrategy.java
|
Java
|
gpl3
| 3,697
|
/*
* ====================================================================
* 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.impl.entity;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.ProtocolException;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.protocol.HTTP;
/**
* The lax implementation of the content length strategy. This class will ignore
* unrecognized transfer encodings and malformed <code>Content-Length</code>
* header values if the {@link CoreProtocolPNames#STRICT_TRANSFER_ENCODING}
* parameter of the given message is not set or set to <code>false</code>.
* <p>
* This class recognizes "chunked" and "identitiy" transfer-coding only.
* <p>
* The following parameters can be used to customize the behavior of this class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#STRICT_TRANSFER_ENCODING}</li>
* </ul>
*
* @since 4.0
*/
public class LaxContentLengthStrategy implements ContentLengthStrategy {
public LaxContentLengthStrategy() {
super();
}
public long determineLength(final HttpMessage message) throws HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
HttpParams params = message.getParams();
boolean strict = params.isParameterTrue(CoreProtocolPNames.STRICT_TRANSFER_ENCODING);
Header transferEncodingHeader = message.getFirstHeader(HTTP.TRANSFER_ENCODING);
Header contentLengthHeader = message.getFirstHeader(HTTP.CONTENT_LEN);
// We use Transfer-Encoding if present and ignore Content-Length.
// RFC2616, 4.4 item number 3
if (transferEncodingHeader != null) {
HeaderElement[] encodings = null;
try {
encodings = transferEncodingHeader.getElements();
} catch (ParseException px) {
throw new ProtocolException
("Invalid Transfer-Encoding header value: " +
transferEncodingHeader, px);
}
if (strict) {
// Currently only chunk and identity are supported
for (int i = 0; i < encodings.length; i++) {
String encoding = encodings[i].getName();
if (encoding != null && encoding.length() > 0
&& !encoding.equalsIgnoreCase(HTTP.CHUNK_CODING)
&& !encoding.equalsIgnoreCase(HTTP.IDENTITY_CODING)) {
throw new ProtocolException("Unsupported transfer encoding: " + encoding);
}
}
}
// The chunked encoding must be the last one applied RFC2616, 14.41
int len = encodings.length;
if (HTTP.IDENTITY_CODING.equalsIgnoreCase(transferEncodingHeader.getValue())) {
return IDENTITY;
} else if ((len > 0) && (HTTP.CHUNK_CODING.equalsIgnoreCase(
encodings[len - 1].getName()))) {
return CHUNKED;
} else {
if (strict) {
throw new ProtocolException("Chunk-encoding must be the last one applied");
}
return IDENTITY;
}
} else if (contentLengthHeader != null) {
long contentlen = -1;
Header[] headers = message.getHeaders(HTTP.CONTENT_LEN);
if (strict && headers.length > 1) {
throw new ProtocolException("Multiple content length headers");
}
for (int i = headers.length - 1; i >= 0; i--) {
Header header = headers[i];
try {
contentlen = Long.parseLong(header.getValue());
break;
} catch (NumberFormatException e) {
if (strict) {
throw new ProtocolException("Invalid content length: " + header.getValue());
}
}
// See if we can have better luck with another header, if present
}
if (contentlen >= 0) {
return contentlen;
} else {
return IDENTITY;
}
} else {
return IDENTITY;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/entity/LaxContentLengthStrategy.java
|
Java
|
gpl3
| 5,688
|
/*
* ====================================================================
* 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.impl.entity;
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.HttpMessage;
import org.apache.ogt.http.entity.BasicHttpEntity;
import org.apache.ogt.http.entity.ContentLengthStrategy;
import org.apache.ogt.http.impl.io.ChunkedInputStream;
import org.apache.ogt.http.impl.io.ContentLengthInputStream;
import org.apache.ogt.http.impl.io.IdentityInputStream;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.protocol.HTTP;
/**
* HTTP entity deserializer.
* <p>
* This entity deserializer supports "chunked" and "identitiy" transfer-coding
* and content length delimited content.
* <p>
* This class relies on a specific implementation of
* {@link ContentLengthStrategy} to determine the content length or transfer
* encoding of the entity.
* <p>
* This class generates an instance of {@link HttpEntity} based on
* properties of the message. The content of the entity will be decoded
* transparently for the consumer.
*
* @since 4.0
*/
public class EntityDeserializer {
private final ContentLengthStrategy lenStrategy;
public EntityDeserializer(final ContentLengthStrategy lenStrategy) {
super();
if (lenStrategy == null) {
throw new IllegalArgumentException("Content length strategy may not be null");
}
this.lenStrategy = lenStrategy;
}
/**
* Creates a {@link BasicHttpEntity} based on properties of the given
* message. The content of the entity is created by wrapping
* {@link SessionInputBuffer} with a content decoder depending on the
* transfer mechanism used by the message.
* <p>
* This method is called by the public
* {@link #deserialize(SessionInputBuffer, HttpMessage)}.
*
* @param inbuffer the session input buffer.
* @param message the message.
* @return HTTP entity.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
protected BasicHttpEntity doDeserialize(
final SessionInputBuffer inbuffer,
final HttpMessage message) throws HttpException, IOException {
BasicHttpEntity entity = new BasicHttpEntity();
long len = this.lenStrategy.determineLength(message);
if (len == ContentLengthStrategy.CHUNKED) {
entity.setChunked(true);
entity.setContentLength(-1);
entity.setContent(new ChunkedInputStream(inbuffer));
} else if (len == ContentLengthStrategy.IDENTITY) {
entity.setChunked(false);
entity.setContentLength(-1);
entity.setContent(new IdentityInputStream(inbuffer));
} else {
entity.setChunked(false);
entity.setContentLength(len);
entity.setContent(new ContentLengthInputStream(inbuffer, len));
}
Header contentTypeHeader = message.getFirstHeader(HTTP.CONTENT_TYPE);
if (contentTypeHeader != null) {
entity.setContentType(contentTypeHeader);
}
Header contentEncodingHeader = message.getFirstHeader(HTTP.CONTENT_ENCODING);
if (contentEncodingHeader != null) {
entity.setContentEncoding(contentEncodingHeader);
}
return entity;
}
/**
* Creates an {@link HttpEntity} based on properties of the given message.
* The content of the entity is created by wrapping
* {@link SessionInputBuffer} with a content decoder depending on the
* transfer mechanism used by the message.
* <p>
* The content of the entity is NOT retrieved by this method.
*
* @param inbuffer the session input buffer.
* @param message the message.
* @return HTTP entity.
* @throws HttpException in case of HTTP protocol violation.
* @throws IOException in case of an I/O error.
*/
public HttpEntity deserialize(
final SessionInputBuffer inbuffer,
final HttpMessage message) throws HttpException, IOException {
if (inbuffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
return doDeserialize(inbuffer, message);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/entity/EntityDeserializer.java
|
Java
|
gpl3
| 5,638
|
/*
* ====================================================================
* 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.impl;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestFactory;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.RequestLine;
import org.apache.ogt.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.ogt.http.message.BasicHttpRequest;
/**
* Default factory for creating {@link HttpRequest} objects.
*
* @since 4.0
*/
public class DefaultHttpRequestFactory implements HttpRequestFactory {
private static final String[] RFC2616_COMMON_METHODS = {
"GET"
};
private static final String[] RFC2616_ENTITY_ENC_METHODS = {
"POST",
"PUT"
};
private static final String[] RFC2616_SPECIAL_METHODS = {
"HEAD",
"OPTIONS",
"DELETE",
"TRACE",
"CONNECT"
};
public DefaultHttpRequestFactory() {
super();
}
private static boolean isOneOf(final String[] methods, final String method) {
for (int i = 0; i < methods.length; i++) {
if (methods[i].equalsIgnoreCase(method)) {
return true;
}
}
return false;
}
public HttpRequest newHttpRequest(final RequestLine requestline)
throws MethodNotSupportedException {
if (requestline == null) {
throw new IllegalArgumentException("Request line may not be null");
}
String method = requestline.getMethod();
if (isOneOf(RFC2616_COMMON_METHODS, method)) {
return new BasicHttpRequest(requestline);
} else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
return new BasicHttpEntityEnclosingRequest(requestline);
} else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) {
return new BasicHttpRequest(requestline);
} else {
throw new MethodNotSupportedException(method + " method not supported");
}
}
public HttpRequest newHttpRequest(final String method, final String uri)
throws MethodNotSupportedException {
if (isOneOf(RFC2616_COMMON_METHODS, method)) {
return new BasicHttpRequest(method, uri);
} else if (isOneOf(RFC2616_ENTITY_ENC_METHODS, method)) {
return new BasicHttpEntityEnclosingRequest(method, uri);
} else if (isOneOf(RFC2616_SPECIAL_METHODS, method)) {
return new BasicHttpRequest(method, uri);
} else {
throw new MethodNotSupportedException(method
+ " method not supported");
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/DefaultHttpRequestFactory.java
|
Java
|
gpl3
| 3,764
|
/*
* ====================================================================
* 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.impl;
import java.util.HashMap;
import org.apache.ogt.http.HttpConnectionMetrics;
import org.apache.ogt.http.io.HttpTransportMetrics;
/**
* Default implementation of the {@link HttpConnectionMetrics} interface.
*
* @since 4.0
*/
public class HttpConnectionMetricsImpl implements HttpConnectionMetrics {
public static final String REQUEST_COUNT = "http.request-count";
public static final String RESPONSE_COUNT = "http.response-count";
public static final String SENT_BYTES_COUNT = "http.sent-bytes-count";
public static final String RECEIVED_BYTES_COUNT = "http.received-bytes-count";
private final HttpTransportMetrics inTransportMetric;
private final HttpTransportMetrics outTransportMetric;
private long requestCount = 0;
private long responseCount = 0;
/**
* The cache map for all metrics values.
*/
private HashMap metricsCache;
public HttpConnectionMetricsImpl(
final HttpTransportMetrics inTransportMetric,
final HttpTransportMetrics outTransportMetric) {
super();
this.inTransportMetric = inTransportMetric;
this.outTransportMetric = outTransportMetric;
}
/* ------------------ Public interface method -------------------------- */
public long getReceivedBytesCount() {
if (this.inTransportMetric != null) {
return this.inTransportMetric.getBytesTransferred();
} else {
return -1;
}
}
public long getSentBytesCount() {
if (this.outTransportMetric != null) {
return this.outTransportMetric.getBytesTransferred();
} else {
return -1;
}
}
public long getRequestCount() {
return this.requestCount;
}
public void incrementRequestCount() {
this.requestCount++;
}
public long getResponseCount() {
return this.responseCount;
}
public void incrementResponseCount() {
this.responseCount++;
}
public Object getMetric(final String metricName) {
Object value = null;
if (this.metricsCache != null) {
value = this.metricsCache.get(metricName);
}
if (value == null) {
if (REQUEST_COUNT.equals(metricName)) {
value = new Long(requestCount);
} else if (RESPONSE_COUNT.equals(metricName)) {
value = new Long(responseCount);
} else if (RECEIVED_BYTES_COUNT.equals(metricName)) {
if (this.inTransportMetric != null) {
return new Long(this.inTransportMetric.getBytesTransferred());
} else {
return null;
}
} else if (SENT_BYTES_COUNT.equals(metricName)) {
if (this.outTransportMetric != null) {
return new Long(this.outTransportMetric.getBytesTransferred());
} else {
return null;
}
}
}
return value;
}
public void setMetric(final String metricName, Object obj) {
if (this.metricsCache == null) {
this.metricsCache = new HashMap();
}
this.metricsCache.put(metricName, obj);
}
public void reset() {
if (this.outTransportMetric != null) {
this.outTransportMetric.reset();
}
if (this.inTransportMetric != null) {
this.inTransportMetric.reset();
}
this.requestCount = 0;
this.responseCount = 0;
this.metricsCache = null;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/HttpConnectionMetricsImpl.java
|
Java
|
gpl3
| 4,798
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* An HTTP header which is already formatted.
* For example when headers are received, the original formatting
* can be preserved. This allows for the header to be sent without
* another formatting step.
*
* @since 4.0
*/
public interface FormattedHeader extends Header {
/**
* Obtains the buffer with the formatted header.
* The returned buffer MUST NOT be modified.
*
* @return the formatted header, in a buffer that must not be modified
*/
CharArrayBuffer getBuffer();
/**
* Obtains the start of the header value in the {@link #getBuffer buffer}.
* By accessing the value in the buffer, creation of a temporary string
* can be avoided.
*
* @return index of the first character of the header value
* in the buffer returned by {@link #getBuffer getBuffer}.
*/
int getValuePos();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/FormattedHeader.java
|
Java
|
gpl3
| 2,147
|
/*
* ====================================================================
* 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);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpException.java
|
Java
|
gpl3
| 2,290
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.util.Locale;
/**
* Interface for obtaining reason phrases for HTTP status codes.
*
* @since 4.0
*/
public interface ReasonPhraseCatalog {
/**
* Obtains the reason phrase for a status code.
* The optional context allows for catalogs that detect
* the language for the reason phrase.
*
* @param status the status code, in the range 100-599
* @param loc the preferred locale for the reason phrase
*
* @return the reason phrase, or <code>null</code> if unknown
*/
public String getReason(int status, Locale loc);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ReasonPhraseCatalog.java
|
Java
|
gpl3
| 1,808
|
/*
* $Header: $
* ====================================================================
* 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 request with an entity.
*
* @since 4.0
*/
public interface HttpEntityEnclosingRequest extends HttpRequest {
/**
* Tells if this request should use the expect-continue handshake.
* The expect continue handshake gives the server a chance to decide
* whether to accept the entity enclosing request before the possibly
* lengthy entity is sent across the wire.
* @return true if the expect continue handshake should be used, false if
* not.
*/
boolean expectContinue();
/**
* Associates the entity with this request.
*
* @param entity the entity to send.
*/
void setEntity(HttpEntity entity);
/**
* Returns the entity associated with this request.
*
* @return entity
*/
HttpEntity getEntity();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpEntityEnclosingRequest.java
|
Java
|
gpl3
| 2,036
|
/*
* ====================================================================
* 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 that an HTTP protocol violation has occurred.
* For example a malformed status line or headers, a missing message body, etc.
*
*
* @since 4.0
*/
public class ProtocolException extends HttpException {
private static final long serialVersionUID = -2143571074341228994L;
/**
* Creates a new ProtocolException with a <tt>null</tt> detail message.
*/
public ProtocolException() {
super();
}
/**
* Creates a new ProtocolException with the specified detail message.
*
* @param message The exception detail message
*/
public ProtocolException(String message) {
super(message);
}
/**
* Creates a new ProtocolException 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 ProtocolException(String message, Throwable cause) {
super(message, cause);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ProtocolException.java
|
Java
|
gpl3
| 2,306
|
/*
* ====================================================================
* 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);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ParseException.java
|
Java
|
gpl3
| 2,090
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
/**
* Signals that the connection has been closed unexpectedly.
*
* @since 4.0
*/
public class ConnectionClosedException extends IOException {
private static final long serialVersionUID = 617550366255636674L;
/**
* Creates a new ConnectionClosedException with the specified detail message.
*
* @param message The exception detail message
*/
public ConnectionClosedException(final String message) {
super(message);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ConnectionClosedException.java
|
Java
|
gpl3
| 1,713
|
/*
* ====================================================================
* 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.
* <p>
* Protocol 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 HttpRequestInterceptor {
/**
* Processes a request.
* On the client side, this step is performed before the request is
* sent to the server. On the server side, this step is performed
* on incoming messages before the message body is evaluated.
*
* @param request the request to preprocess
* @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(HttpRequest request, HttpContext context)
throws HttpException, IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpRequestInterceptor.java
|
Java
|
gpl3
| 2,716
|
/*
* ====================================================================
* 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.util;
import java.io.Serializable;
/**
* A resizable byte array.
*
* @since 4.0
*/
public final class ByteArrayBuffer implements Serializable {
private static final long serialVersionUID = 4359112959524048036L;
private byte[] buffer;
private int len;
/**
* Creates an instance of {@link ByteArrayBuffer} with the given initial
* capacity.
*
* @param capacity the capacity
*/
public ByteArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
this.buffer = new byte[capacity];
}
private void expand(int newlen) {
byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, newlen)];
System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
this.buffer = newbuffer;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final byte[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int newlen = this.len + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newlen;
}
/**
* Appends <code>b</code> byte to this buffer. The capacity of the buffer
* is increased, if necessary, to accommodate the additional byte.
*
* @param b the byte to be appended.
*/
public void append(int b) {
int newlen = this.len + 1;
if (newlen > this.buffer.length) {
expand(newlen);
}
this.buffer[this.len] = (byte)b;
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased if necessary to accommodate all <code>len</code> chars.
* <p>
* The chars are converted to bytes using simple cast.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final char[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int oldlen = this.len;
int newlen = oldlen + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {
this.buffer[i2] = (byte) b[i1];
}
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* char array buffer starting at index <code>off</code>. The capacity
* of the buffer is increased if necessary to accommodate all
* <code>len</code> chars.
* <p>
* The chars are converted to bytes using simple cast.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final CharArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer(), off, len);
}
/**
* Clears content of the buffer. The underlying byte array is not resized.
*/
public void clear() {
this.len = 0;
}
/**
* Converts the content of this buffer to an array of bytes.
*
* @return byte array
*/
public byte[] toByteArray() {
byte[] b = new byte[this.len];
if (this.len > 0) {
System.arraycopy(this.buffer, 0, b, 0, this.len);
}
return b;
}
/**
* Returns the <code>byte</code> value in this buffer at the specified
* index. The index argument must be greater than or equal to
* <code>0</code>, and less than the length of this buffer.
*
* @param i the index of the desired byte value.
* @return the byte value at the specified index.
* @throws IndexOutOfBoundsException if <code>index</code> is
* negative or greater than or equal to {@link #length()}.
*/
public int byteAt(int i) {
return this.buffer[i];
}
/**
* Returns the current capacity. The capacity is the amount of storage
* available for newly appended bytes, beyond which an allocation
* will occur.
*
* @return the current capacity
*/
public int capacity() {
return this.buffer.length;
}
/**
* Returns the length of the buffer (byte count).
*
* @return the length of the buffer
*/
public int length() {
return this.len;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. If the <code>required</code>
* argument is non-positive, this method takes no action.
*
* @param required the minimum required capacity.
*
* @since 4.1
*/
public void ensureCapacity(int required) {
if (required <= 0) {
return;
}
int available = this.buffer.length - this.len;
if (required > available) {
expand(this.len + required);
}
}
/**
* Returns reference to the underlying byte array.
*
* @return the byte array.
*/
public byte[] buffer() {
return this.buffer;
}
/**
* Sets the length of the buffer. The new length value is expected to be
* less than the current capacity and greater than or equal to
* <code>0</code>.
*
* @param len the new length
* @throws IndexOutOfBoundsException if the
* <code>len</code> argument is greater than the current
* capacity of the buffer or less than <code>0</code>.
*/
public void setLength(int len) {
if (len < 0 || len > this.buffer.length) {
throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);
}
this.len = len;
}
/**
* Returns <code>true</code> if this buffer is empty, that is, its
* {@link #length()} is equal to <code>0</code>.
* @return <code>true</code> if this buffer is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return this.len == 0;
}
/**
* Returns <code>true</code> if this buffer is full, that is, its
* {@link #length()} is equal to its {@link #capacity()}.
* @return <code>true</code> if this buffer is full, <code>false</code>
* otherwise.
*/
public boolean isFull() {
return this.len == this.buffer.length;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified byte, starting the search at the specified
* <code>beginIndex</code> and finishing at <code>endIndex</code>.
* If no such byte occurs in this buffer within the specified bounds,
* <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>beginIndex</code> and
* <code>endIndex</code>. If <code>beginIndex</code> is negative,
* it has the same effect as if it were zero. If <code>endIndex</code> is
* greater than {@link #length()}, it has the same effect as if it were
* {@link #length()}. If the <code>beginIndex</code> is greater than
* the <code>endIndex</code>, <code>-1</code> is returned.
*
* @param b the byte to search for.
* @param beginIndex the index to start the search from.
* @param endIndex the index to finish the search at.
* @return the index of the first occurrence of the byte in the buffer
* within the given bounds, or <code>-1</code> if the byte does
* not occur.
*
* @since 4.1
*/
public int indexOf(byte b, int beginIndex, int endIndex) {
if (beginIndex < 0) {
beginIndex = 0;
}
if (endIndex > this.len) {
endIndex = this.len;
}
if (beginIndex > endIndex) {
return -1;
}
for (int i = beginIndex; i < endIndex; i++) {
if (this.buffer[i] == b) {
return i;
}
}
return -1;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified byte, starting the search at <code>0</code> and finishing
* at {@link #length()}. If no such byte occurs in this buffer within
* those bounds, <code>-1</code> is returned.
*
* @param b the byte to search for.
* @return the index of the first occurrence of the byte in the
* buffer, or <code>-1</code> if the byte does not occur.
*
* @since 4.1
*/
public int indexOf(byte b) {
return indexOf(b, 0, this.len);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/ByteArrayBuffer.java
|
Java
|
gpl3
| 11,788
|
<html>
<head>
<!--
/*
* ====================================================================
* 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/>.
*
*/
-->
</head>
<body>
Resizable
{@link org.apache.ogt.http.util.ByteArrayBuffer byte} and
{@link org.apache.ogt.http.util.CharArrayBuffer char} arrays
and various utility classes with static helper methods.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/package.html
|
HTML
|
gpl3
| 1,423
|
/*
* ====================================================================
* 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.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.protocol.HTTP;
/**
* Static helpers for dealing with {@link HttpEntity}s.
*
* @since 4.0
*/
public final class EntityUtils {
private EntityUtils() {
}
/**
* Ensures that the entity content is fully consumed and the content stream, if exists,
* is closed.
*
* @param entity
* @throws IOException if an error occurs reading the input stream
*
* @since 4.1
*/
public static void consume(final HttpEntity entity) throws IOException {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
}
/**
* Read the contents of an entity and return it as a byte array.
*
* @param entity
* @return byte array containing the entity content. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws IOException if an error occurs reading the input stream
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
*/
public static byte[] toByteArray(final HttpEntity entity) throws IOException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ByteArrayBuffer buffer = new ByteArrayBuffer(i);
byte[] tmp = new byte[4096];
int l;
while((l = instream.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toByteArray();
} finally {
instream.close();
}
}
/**
* Obtains character set of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*/
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
/**
* Obtains mime type of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*
* @since 4.1
*/
public static String getContentMimeType(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String mimeType = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
mimeType = values[0].getName();
}
}
return mimeType;
}
/**
* Get the entity content as a String, using the provided default character set
* if none is found in the entity.
* If defaultCharset is null, the default "ISO-8859-1" is used.
*
* @param entity must not be null
* @param defaultCharset character set to be applied if none found in the entity
* @return the entity content as a String. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
*/
public static String toString(
final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}
/**
* Read the contents of an entity and return it as a String.
* The content is converted using the character set from the entity (if any),
* failing that, "ISO-8859-1" is used.
*
* @param entity
* @return String containing the content.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
*/
public static String toString(final HttpEntity entity)
throws IOException, ParseException {
return toString(entity, null);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/EntityUtils.java
|
Java
|
gpl3
| 8,099
|
/*
* ====================================================================
* 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.util;
/**
* A set of utility methods to help produce consistent
* {@link Object#equals equals} and {@link Object#hashCode hashCode} methods.
*
*
* @since 4.0
*/
public final class LangUtils {
public static final int HASH_SEED = 17;
public static final int HASH_OFFSET = 37;
/** Disabled default constructor. */
private LangUtils() {
}
public static int hashCode(final int seed, final int hashcode) {
return seed * HASH_OFFSET + hashcode;
}
public static int hashCode(final int seed, final boolean b) {
return hashCode(seed, b ? 1 : 0);
}
public static int hashCode(final int seed, final Object obj) {
return hashCode(seed, obj != null ? obj.hashCode() : 0);
}
/**
* Check if two objects are equal.
*
* @param obj1 first object to compare, may be {@code null}
* @param obj2 second object to compare, may be {@code null}
* @return {@code true} if the objects are equal or both null
*/
public static boolean equals(final Object obj1, final Object obj2) {
return obj1 == null ? obj2 == null : obj1.equals(obj2);
}
/**
* Check if two object arrays are equal.
* <p>
* <ul>
* <li>If both parameters are null, return {@code true}</li>
* <li>If one parameter is null, return {@code false}</li>
* <li>If the array lengths are different, return {@code false}</li>
* <li>Compare array elements using .equals(); return {@code false} if any comparisons fail.</li>
* <li>Return {@code true}</li>
* </ul>
*
* @param a1 first array to compare, may be {@code null}
* @param a2 second array to compare, may be {@code null}
* @return {@code true} if the arrays are equal or both null
*/
public static boolean equals(final Object[] a1, final Object[] a2) {
if (a1 == null) {
if (a2 == null) {
return true;
} else {
return false;
}
} else {
if (a2 != null && a1.length == a2.length) {
for (int i = 0; i < a1.length; i++) {
if (!equals(a1[i], a2[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/LangUtils.java
|
Java
|
gpl3
| 3,576
|
/*
* ====================================================================
* 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.util;
import java.io.Serializable;
import org.apache.ogt.http.protocol.HTTP;
/**
* A resizable char array.
*
* @since 4.0
*/
public final class CharArrayBuffer implements Serializable {
private static final long serialVersionUID = -6208952725094867135L;
private char[] buffer;
private int len;
/**
* Creates an instance of {@link CharArrayBuffer} with the given initial
* capacity.
*
* @param capacity the capacity
*/
public CharArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
this.buffer = new char[capacity];
}
private void expand(int newlen) {
char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)];
System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
this.buffer = newbuffer;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> chars.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final char[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int newlen = this.len + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newlen;
}
/**
* Appends chars of the given string to this buffer. The capacity of the
* buffer is increased, if necessary, to accommodate all chars.
*
* @param str the string.
*/
public void append(String str) {
if (str == null) {
str = "null";
}
int strlen = str.length();
int newlen = this.len + strlen;
if (newlen > this.buffer.length) {
expand(newlen);
}
str.getChars(0, strlen, this.buffer, this.len);
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* buffer starting at index <code>off</code>. The capacity of the
* destination buffer is increased, if necessary, to accommodate all
* <code>len</code> chars.
*
* @param b the source buffer to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final CharArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer, off, len);
}
/**
* Appends all chars to this buffer from the given source buffer starting
* at index <code>0</code>. The capacity of the destination buffer is
* increased, if necessary, to accommodate all {@link #length()} chars.
*
* @param b the source buffer to be appended.
*/
public void append(final CharArrayBuffer b) {
if (b == null) {
return;
}
append(b.buffer,0, b.len);
}
/**
* Appends <code>ch</code> char to this buffer. The capacity of the buffer
* is increased, if necessary, to accommodate the additional char.
*
* @param ch the char to be appended.
*/
public void append(char ch) {
int newlen = this.len + 1;
if (newlen > this.buffer.length) {
expand(newlen);
}
this.buffer[this.len] = ch;
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final byte[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int oldlen = this.len;
int newlen = oldlen + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {
this.buffer[i2] = (char) (b[i1] & 0xff);
}
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final ByteArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer(), off, len);
}
/**
* Appends chars of the textual representation of the given object to this
* buffer. The capacity of the buffer is increased, if necessary, to
* accommodate all chars.
*
* @param obj the object.
*/
public void append(final Object obj) {
append(String.valueOf(obj));
}
/**
* Clears content of the buffer. The underlying char array is not resized.
*/
public void clear() {
this.len = 0;
}
/**
* Converts the content of this buffer to an array of chars.
*
* @return char array
*/
public char[] toCharArray() {
char[] b = new char[this.len];
if (this.len > 0) {
System.arraycopy(this.buffer, 0, b, 0, this.len);
}
return b;
}
/**
* Returns the <code>char</code> value in this buffer at the specified
* index. The index argument must be greater than or equal to
* <code>0</code>, and less than the length of this buffer.
*
* @param i the index of the desired char value.
* @return the char value at the specified index.
* @throws IndexOutOfBoundsException if <code>index</code> is
* negative or greater than or equal to {@link #length()}.
*/
public char charAt(int i) {
return this.buffer[i];
}
/**
* Returns reference to the underlying char array.
*
* @return the char array.
*/
public char[] buffer() {
return this.buffer;
}
/**
* Returns the current capacity. The capacity is the amount of storage
* available for newly appended chars, beyond which an allocation will
* occur.
*
* @return the current capacity
*/
public int capacity() {
return this.buffer.length;
}
/**
* Returns the length of the buffer (char count).
*
* @return the length of the buffer
*/
public int length() {
return this.len;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. If the <code>required</code>
* argument is non-positive, this method takes no action.
*
* @param required the minimum required capacity.
*/
public void ensureCapacity(int required) {
if (required <= 0) {
return;
}
int available = this.buffer.length - this.len;
if (required > available) {
expand(this.len + required);
}
}
/**
* Sets the length of the buffer. The new length value is expected to be
* less than the current capacity and greater than or equal to
* <code>0</code>.
*
* @param len the new length
* @throws IndexOutOfBoundsException if the
* <code>len</code> argument is greater than the current
* capacity of the buffer or less than <code>0</code>.
*/
public void setLength(int len) {
if (len < 0 || len > this.buffer.length) {
throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);
}
this.len = len;
}
/**
* Returns <code>true</code> if this buffer is empty, that is, its
* {@link #length()} is equal to <code>0</code>.
* @return <code>true</code> if this buffer is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return this.len == 0;
}
/**
* Returns <code>true</code> if this buffer is full, that is, its
* {@link #length()} is equal to its {@link #capacity()}.
* @return <code>true</code> if this buffer is full, <code>false</code>
* otherwise.
*/
public boolean isFull() {
return this.len == this.buffer.length;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at the specified
* <code>beginIndex</code> and finishing at <code>endIndex</code>.
* If no such character occurs in this buffer within the specified bounds,
* <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>beginIndex</code> and
* <code>endIndex</code>. If <code>beginIndex</code> is negative,
* it has the same effect as if it were zero. If <code>endIndex</code> is
* greater than {@link #length()}, it has the same effect as if it were
* {@link #length()}. If the <code>beginIndex</code> is greater than
* the <code>endIndex</code>, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @param beginIndex the index to start the search from.
* @param endIndex the index to finish the search at.
* @return the index of the first occurrence of the character in the buffer
* within the given bounds, or <code>-1</code> if the character does
* not occur.
*/
public int indexOf(int ch, int beginIndex, int endIndex) {
if (beginIndex < 0) {
beginIndex = 0;
}
if (endIndex > this.len) {
endIndex = this.len;
}
if (beginIndex > endIndex) {
return -1;
}
for (int i = beginIndex; i < endIndex; i++) {
if (this.buffer[i] == ch) {
return i;
}
}
return -1;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at <code>0</code> and finishing
* at {@link #length()}. If no such character occurs in this buffer within
* those bounds, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @return the index of the first occurrence of the character in the
* buffer, or <code>-1</code> if the character does not occur.
*/
public int indexOf(int ch) {
return indexOf(ch, 0, this.len);
}
/**
* Returns a substring of this buffer. The substring begins at the specified
* <code>beginIndex</code> and extends to the character at index
* <code>endIndex - 1</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception StringIndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substring(int beginIndex, int endIndex) {
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
/**
* Returns a substring of this buffer with leading and trailing whitespace
* omitted. The substring begins with the first non-whitespace character
* from <code>beginIndex</code> and extends to the last
* non-whitespace character with the index lesser than
* <code>endIndex</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substringTrimmed(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new IndexOutOfBoundsException("Negative beginIndex: "+beginIndex);
}
if (endIndex > this.len) {
throw new IndexOutOfBoundsException("endIndex: "+endIndex+" > length: "+this.len);
}
if (beginIndex > endIndex) {
throw new IndexOutOfBoundsException("beginIndex: "+beginIndex+" > endIndex: "+endIndex);
}
while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) {
beginIndex++;
}
while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) {
endIndex--;
}
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
public String toString() {
return new String(this.buffer, 0, this.len);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/CharArrayBuffer.java
|
Java
|
gpl3
| 16,437
|
/*
* ====================================================================
* 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.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.ArrayList;
/**
* Provides access to version information for HTTP components.
* Static methods are used to extract version information from property
* files that are automatically packaged with HTTP component release JARs.
* <br/>
* All available version information is provided in strings, where
* the string format is informal and subject to change without notice.
* Version information is provided for debugging output and interpretation
* by humans, not for automated processing in applications.
*
* @since 4.0
*/
public class VersionInfo {
/** A string constant for unavailable information. */
public final static String UNAVAILABLE = "UNAVAILABLE";
/** The filename of the version information files. */
public final static String VERSION_PROPERTY_FILE = "version.properties";
// the property names
public final static String PROPERTY_MODULE = "info.module";
public final static String PROPERTY_RELEASE = "info.release";
public final static String PROPERTY_TIMESTAMP = "info.timestamp";
/** The package that contains the version information. */
private final String infoPackage;
/** The module from the version info. */
private final String infoModule;
/** The release from the version info. */
private final String infoRelease;
/** The timestamp from the version info. */
private final String infoTimestamp;
/** The classloader from which the version info was obtained. */
private final String infoClassloader;
/**
* Instantiates version information.
*
* @param pckg the package
* @param module the module, or <code>null</code>
* @param release the release, or <code>null</code>
* @param time the build time, or <code>null</code>
* @param clsldr the class loader, or <code>null</code>
*/
protected VersionInfo(String pckg, String module,
String release, String time, String clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
infoPackage = pckg;
infoModule = (module != null) ? module : UNAVAILABLE;
infoRelease = (release != null) ? release : UNAVAILABLE;
infoTimestamp = (time != null) ? time : UNAVAILABLE;
infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE;
}
/**
* Obtains the package name.
* The package name identifies the module or informal unit.
*
* @return the package name, never <code>null</code>
*/
public final String getPackage() {
return infoPackage;
}
/**
* Obtains the name of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the module name, never <code>null</code>
*/
public final String getModule() {
return infoModule;
}
/**
* Obtains the release of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the release version, never <code>null</code>
*/
public final String getRelease() {
return infoRelease;
}
/**
* Obtains the timestamp of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the timestamp, never <code>null</code>
*/
public final String getTimestamp() {
return infoTimestamp;
}
/**
* Obtains the classloader used to read the version information.
* This is just the <code>toString</code> output of the classloader,
* since the version information should not keep a reference to
* the classloader itself. That could prevent garbage collection.
*
* @return the classloader description, never <code>null</code>
*/
public final String getClassloader() {
return infoClassloader;
}
/**
* Provides the version information in human-readable format.
*
* @return a string holding this version information
*/
public String toString() {
StringBuffer sb = new StringBuffer
(20 + infoPackage.length() + infoModule.length() +
infoRelease.length() + infoTimestamp.length() +
infoClassloader.length());
sb.append("VersionInfo(")
.append(infoPackage).append(':').append(infoModule);
// If version info is missing, a single "UNAVAILABLE" for the module
// is sufficient. Everything else just clutters the output.
if (!UNAVAILABLE.equals(infoRelease))
sb.append(':').append(infoRelease);
if (!UNAVAILABLE.equals(infoTimestamp))
sb.append(':').append(infoTimestamp);
sb.append(')');
if (!UNAVAILABLE.equals(infoClassloader))
sb.append('@').append(infoClassloader);
return sb.toString();
}
/**
* Loads version information for a list of packages.
*
* @param pckgs the packages for which to load version info
* @param clsldr the classloader to load from, or
* <code>null</code> for the thread context classloader
*
* @return the version information for all packages found,
* never <code>null</code>
*/
public final static VersionInfo[] loadVersionInfo(String[] pckgs,
ClassLoader clsldr) {
if (pckgs == null) {
throw new IllegalArgumentException
("Package identifier list must not be null.");
}
ArrayList vil = new ArrayList(pckgs.length);
for (int i=0; i<pckgs.length; i++) {
VersionInfo vi = loadVersionInfo(pckgs[i], clsldr);
if (vi != null)
vil.add(vi);
}
return (VersionInfo[]) vil.toArray(new VersionInfo[vil.size()]);
}
/**
* Loads version information for a package.
*
* @param pckg the package for which to load version information,
* for example "org.apache.ogt.http".
* The package name should NOT end with a dot.
* @param clsldr the classloader to load from, or
* <code>null</code> for the thread context classloader
*
* @return the version information for the argument package, or
* <code>null</code> if not available
*/
public final static VersionInfo loadVersionInfo(final String pckg,
ClassLoader clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
if (clsldr == null)
clsldr = Thread.currentThread().getContextClassLoader();
Properties vip = null; // version info properties, if available
try {
// org.apache.ogt.http becomes
// org/apache/http/version.properties
InputStream is = clsldr.getResourceAsStream
(pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE);
if (is != null) {
try {
Properties props = new Properties();
props.load(is);
vip = props;
} finally {
is.close();
}
}
} catch (IOException ex) {
// shamelessly munch this exception
}
VersionInfo result = null;
if (vip != null)
result = fromMap(pckg, vip, clsldr);
return result;
}
/**
* Instantiates version information from properties.
*
* @param pckg the package for the version information
* @param info the map from string keys to string values,
* for example {@link java.util.Properties}
* @param clsldr the classloader, or <code>null</code>
*
* @return the version information
*/
protected final static VersionInfo fromMap(String pckg, Map info,
ClassLoader clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
String module = null;
String release = null;
String timestamp = null;
if (info != null) {
module = (String) info.get(PROPERTY_MODULE);
if ((module != null) && (module.length() < 1))
module = null;
release = (String) info.get(PROPERTY_RELEASE);
if ((release != null) && ((release.length() < 1) ||
(release.equals("${pom.version}"))))
release = null;
timestamp = (String) info.get(PROPERTY_TIMESTAMP);
if ((timestamp != null) &&
((timestamp.length() < 1) ||
(timestamp.equals("${mvn.timestamp}")))
)
timestamp = null;
} // if info
String clsldrstr = null;
if (clsldr != null)
clsldrstr = clsldr.toString();
return new VersionInfo(pckg, module, release, timestamp, clsldrstr);
}
} // class VersionInfo
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/VersionInfo.java
|
Java
|
gpl3
| 10,766
|
/*
* ====================================================================
* 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.util;
import java.lang.reflect.Method;
/**
* The home for utility methods that handle various exception-related tasks.
*
*
* @since 4.0
*/
public final class ExceptionUtils {
/** A reference to Throwable's initCause method, or null if it's not there in this JVM */
static private final Method INIT_CAUSE_METHOD = getInitCauseMethod();
/**
* Returns a <code>Method<code> allowing access to
* {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable},
* or <code>null</code> if the method
* does not exist.
*
* @return A <code>Method<code> for <code>Throwable.initCause</code>, or
* <code>null</code> if unavailable.
*/
static private Method getInitCauseMethod() {
try {
Class[] paramsClasses = new Class[] { Throwable.class };
return Throwable.class.getMethod("initCause", paramsClasses);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* If we're running on JDK 1.4 or later, initialize the cause for the given throwable.
*
* @param throwable The throwable.
* @param cause The cause of the throwable.
*/
public static void initCause(Throwable throwable, Throwable cause) {
if (INIT_CAUSE_METHOD != null) {
try {
INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause });
} catch (Exception e) {
// Well, with no logging, the only option is to munch the exception
}
}
}
private ExceptionUtils() {
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/ExceptionUtils.java
|
Java
|
gpl3
| 2,809
|
/*
* ====================================================================
* 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.util;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.protocol.HTTP;
/**
* The home for utility methods that handle various encoding tasks.
*
*
* @since 4.0
*/
public final class EncodingUtils {
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(
final byte[] data,
int offset,
int length,
String charset
) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
if (charset == null || charset.length() == 0) {
throw new IllegalArgumentException("charset may not be null or empty");
}
try {
return new String(data, offset, length, charset);
} catch (UnsupportedEncodingException e) {
return new String(data, offset, length);
}
}
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(final byte[] data, final String charset) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
return getString(data, 0, data.length, charset);
}
/**
* Converts the specified string to a byte array. If the charset is not supported the
* default system charset is used.
*
* @param data the string to be encoded
* @param charset the desired character encoding
* @return The resulting byte array.
*/
public static byte[] getBytes(final String data, final String charset) {
if (data == null) {
throw new IllegalArgumentException("data may not be null");
}
if (charset == null || charset.length() == 0) {
throw new IllegalArgumentException("charset may not be null or empty");
}
try {
return data.getBytes(charset);
} catch (UnsupportedEncodingException e) {
return data.getBytes();
}
}
/**
* Converts the specified string to byte array of ASCII characters.
*
* @param data the string to be encoded
* @return The string as a byte array.
*/
public static byte[] getAsciiBytes(final String data) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
try {
return data.getBytes(HTTP.US_ASCII);
} catch (UnsupportedEncodingException e) {
throw new Error("HttpClient requires ASCII support");
}
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data, int offset, int length) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
try {
return new String(data, offset, length, HTTP.US_ASCII);
} catch (UnsupportedEncodingException e) {
throw new Error("HttpClient requires ASCII support");
}
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
return getAsciiString(data, 0, data.length);
}
/**
* This class should not be instantiated.
*/
private EncodingUtils() {
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/EncodingUtils.java
|
Java
|
gpl3
| 5,880
|
/*
* ====================================================================
* 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.params.HttpParams;
/**
* HTTP messages consist of requests from client to server and responses
* from server to client.
* <pre>
* HTTP-message = Request | Response ; HTTP/1.1 messages
* </pre>
* <p>
* HTTP messages use the generic message format of RFC 822 for
* transferring entities (the payload of the message). Both types
* of message consist of a start-line, zero or more header fields
* (also known as "headers"), an empty line (i.e., a line with nothing
* preceding the CRLF) indicating the end of the header fields,
* and possibly a message-body.
* </p>
* <pre>
* generic-message = start-line
* *(message-header CRLF)
* CRLF
* [ message-body ]
* start-line = Request-Line | Status-Line
* </pre>
*
* @since 4.0
*/
public interface HttpMessage {
/**
* Returns the protocol version this message is compatible with.
*/
ProtocolVersion getProtocolVersion();
/**
* Checks if a certain header is present in this message. Header values are
* ignored.
*
* @param name the header name to check for.
* @return true if at least one header with this name is present.
*/
boolean containsHeader(String name);
/**
* Returns all the headers with a specified name of this message. Header values
* are ignored. Headers are orderd in the sequence they will be sent over a
* connection.
*
* @param name the name of the headers to return.
* @return the headers whose name property equals <code>name</code>.
*/
Header[] getHeaders(String name);
/**
* Returns the first header with a specified name of this message. Header
* values are ignored. If there is more than one matching header in the
* message the first element of {@link #getHeaders(String)} is returned.
* If there is no matching header in the message <code>null</code> is
* returned.
*
* @param name the name of the header to return.
* @return the first header whose name property equals <code>name</code>
* or <code>null</code> if no such header could be found.
*/
Header getFirstHeader(String name);
/**
* Returns the last header with a specified name of this message. Header values
* are ignored. If there is more than one matching header in the message the
* last element of {@link #getHeaders(String)} is returned. If there is no
* matching header in the message <code>null</code> is returned.
*
* @param name the name of the header to return.
* @return the last header whose name property equals <code>name</code>.
* or <code>null</code> if no such header could be found.
*/
Header getLastHeader(String name);
/**
* Returns all the headers of this message. Headers are orderd in the sequence
* they will be sent over a connection.
*
* @return all the headers of this message
*/
Header[] getAllHeaders();
/**
* Adds a header to this message. The header will be appended to the end of
* the list.
*
* @param header the header to append.
*/
void addHeader(Header header);
/**
* Adds a header to this message. The header will be appended to the end of
* the list.
*
* @param name the name of the header.
* @param value the value of the header.
*/
void addHeader(String name, String value);
/**
* Overwrites the first header with the same name. The new header will be appended to
* the end of the list, if no header with the given name can be found.
*
* @param header the header to set.
*/
void setHeader(Header header);
/**
* Overwrites the first header with the same name. The new header will be appended to
* the end of the list, if no header with the given name can be found.
*
* @param name the name of the header.
* @param value the value of the header.
*/
void setHeader(String name, String value);
/**
* Overwrites all the headers in the message.
*
* @param headers the array of headers to set.
*/
void setHeaders(Header[] headers);
/**
* Removes a header from this message.
*
* @param header the header to remove.
*/
void removeHeader(Header header);
/**
* Removes all headers with a certain name from this message.
*
* @param name The name of the headers to remove.
*/
void removeHeaders(String name);
/**
* Returns an iterator of all the headers.
*
* @return Iterator that returns Header objects in the sequence they are
* sent over a connection.
*/
HeaderIterator headerIterator();
/**
* Returns an iterator of the headers with a given name.
*
* @param name the name of the headers over which to iterate, or
* <code>null</code> for all headers
*
* @return Iterator that returns Header objects with the argument name
* in the sequence they are sent over a connection.
*/
HeaderIterator headerIterator(String name);
/**
* Returns the parameters effective for this message as set by
* {@link #setParams(HttpParams)}.
*/
HttpParams getParams();
/**
* Provides parameters to be used for the processing of this message.
* @param params the parameters
*/
void setParams(HttpParams params);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpMessage.java
|
Java
|
gpl3
| 6,761
|
/*
* ====================================================================
* 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;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpServerConnection.java
|
Java
|
gpl3
| 3,262
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* The Request-Line begins with a method token, followed by the
* Request-URI and the protocol version, and ending with CRLF. The
* elements are separated by SP characters. No CR or LF is allowed
* except in the final CRLF sequence.
* <pre>
* Request-Line = Method SP Request-URI SP HTTP-Version CRLF
* </pre>
*
* @since 4.0
*/
public interface RequestLine {
String getMethod();
ProtocolVersion getProtocolVersion();
String getUri();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/RequestLine.java
|
Java
|
gpl3
| 1,687
|
/*
* ====================================================================
* 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;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpRequestFactory.java
|
Java
|
gpl3
| 1,547
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.Serializable;
import java.util.Locale;
import org.apache.ogt.http.util.CharArrayBuffer;
import org.apache.ogt.http.util.LangUtils;
/**
* Holds all of the variables needed to describe an HTTP connection to a host.
* This includes remote host name, port and scheme.
*
*
* @since 4.0
*/
//@Immutable
public final class HttpHost implements Cloneable, Serializable {
private static final long serialVersionUID = -7529410654042457626L;
/** The default scheme is "http". */
public static final String DEFAULT_SCHEME_NAME = "http";
/** The host to use. */
protected final String hostname;
/** The lowercase host, for {@link #equals} and {@link #hashCode}. */
protected final String lcHostname;
/** The port to use. */
protected final int port;
/** The scheme (lowercased) */
protected final String schemeName;
/**
* Creates a new {@link HttpHost HttpHost}, specifying all values.
* Constructor for HttpHost.
*
* @param hostname the hostname (IP or DNS name)
* @param port the port number.
* <code>-1</code> indicates the scheme default port.
* @param scheme the name of the scheme.
* <code>null</code> indicates the
* {@link #DEFAULT_SCHEME_NAME default scheme}
*/
public HttpHost(final String hostname, int port, final String scheme) {
super();
if (hostname == null) {
throw new IllegalArgumentException("Host name may not be null");
}
this.hostname = hostname;
this.lcHostname = hostname.toLowerCase(Locale.ENGLISH);
if (scheme != null) {
this.schemeName = scheme.toLowerCase(Locale.ENGLISH);
} else {
this.schemeName = DEFAULT_SCHEME_NAME;
}
this.port = port;
}
/**
* Creates a new {@link HttpHost HttpHost}, with default scheme.
*
* @param hostname the hostname (IP or DNS name)
* @param port the port number.
* <code>-1</code> indicates the scheme default port.
*/
public HttpHost(final String hostname, int port) {
this(hostname, port, null);
}
/**
* Creates a new {@link HttpHost HttpHost}, with default scheme and port.
*
* @param hostname the hostname (IP or DNS name)
*/
public HttpHost(final String hostname) {
this(hostname, -1, null);
}
/**
* Copy constructor for {@link HttpHost HttpHost}.
*
* @param httphost the HTTP host to copy details from
*/
public HttpHost (final HttpHost httphost) {
this(httphost.hostname, httphost.port, httphost.schemeName);
}
/**
* Returns the host name.
*
* @return the host name (IP or DNS name)
*/
public String getHostName() {
return this.hostname;
}
/**
* Returns the port.
*
* @return the host port, or <code>-1</code> if not set
*/
public int getPort() {
return this.port;
}
/**
* Returns the scheme name.
*
* @return the scheme name
*/
public String getSchemeName() {
return this.schemeName;
}
/**
* Return the host URI, as a string.
*
* @return the host URI
*/
public String toURI() {
CharArrayBuffer buffer = new CharArrayBuffer(32);
buffer.append(this.schemeName);
buffer.append("://");
buffer.append(this.hostname);
if (this.port != -1) {
buffer.append(':');
buffer.append(Integer.toString(this.port));
}
return buffer.toString();
}
/**
* Obtains the host string, without scheme prefix.
*
* @return the host string, for example <code>localhost:8080</code>
*/
public String toHostString() {
if (this.port != -1) {
//the highest port number is 65535, which is length 6 with the addition of the colon
CharArrayBuffer buffer = new CharArrayBuffer(this.hostname.length() + 6);
buffer.append(this.hostname);
buffer.append(":");
buffer.append(Integer.toString(this.port));
return buffer.toString();
} else {
return this.hostname;
}
}
public String toString() {
return toURI();
}
public boolean equals(final Object obj) {
if (this == obj) return true;
if (obj instanceof HttpHost) {
HttpHost that = (HttpHost) obj;
return this.lcHostname.equals(that.lcHostname)
&& this.port == that.port
&& this.schemeName.equals(that.schemeName);
} else {
return false;
}
}
/**
* @see java.lang.Object#hashCode()
*/
public int hashCode() {
int hash = LangUtils.HASH_SEED;
hash = LangUtils.hashCode(hash, this.lcHostname);
hash = LangUtils.hashCode(hash, this.port);
hash = LangUtils.hashCode(hash, this.schemeName);
return hash;
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpHost.java
|
Java
|
gpl3
| 6,407
|
/*
* ====================================================================
* 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 client-side HTTP connection, which can be used for sending
* requests and receiving responses.
*
* @since 4.0
*/
public interface HttpClientConnection extends HttpConnection {
/**
* Checks if response data is available from the connection. May wait for
* the specified time until some data becomes available. Note that some
* implementations may completely ignore the timeout parameter.
*
* @param timeout the maximum time in milliseconds to wait for data
* @return true if data is available; false if there was no data available
* even after waiting for <code>timeout</code> milliseconds.
* @throws IOException if an error happens on the connection
*/
boolean isResponseAvailable(int timeout)
throws IOException;
/**
* Sends the request line and all headers over the connection.
* @param request the request whose headers to send.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void sendRequestHeader(HttpRequest request)
throws HttpException, IOException;
/**
* Sends the request entity over the connection.
* @param request the request whose entity to send.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void sendRequestEntity(HttpEntityEnclosingRequest request)
throws HttpException, IOException;
/**
* Receives the request line and headers of the next response available from
* this connection. The caller should examine the HttpResponse object to
* find out if it should try to receive a response entity as well.
*
* @return a new HttpResponse object with status line and headers
* initialized.
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
HttpResponse receiveResponseHeader()
throws HttpException, IOException;
/**
* Receives the next response entity available from this connection and
* attaches it to an existing HttpResponse object.
*
* @param response the response to attach the entity to
* @throws HttpException in case of HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void receiveResponseEntity(HttpResponse response)
throws HttpException, IOException;
/**
* Writes out all pending buffered data over the open connection.
*
* @throws IOException in case of an I/O error
*/
void flush() throws IOException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpClientConnection.java
|
Java
|
gpl3
| 3,897
|
/*
* ====================================================================
* 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();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpInetConnection.java
|
Java
|
gpl3
| 1,513
|
/*
* ====================================================================
* 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);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/TruncatedChunkException.java
|
Java
|
gpl3
| 1,681
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* Represents an HTTP header field.
*
* <p>The HTTP header fields follow the same generic format as
* that given in Section 3.1 of RFC 822. Each header field consists
* of a name followed by a colon (":") and the field value. Field names
* are case-insensitive. The field value MAY be preceded by any amount
* of LWS, though a single SP is preferred.
*
*<pre>
* message-header = field-name ":" [ field-value ]
* field-name = token
* field-value = *( field-content | LWS )
* field-content = <the OCTETs making up the field-value
* and consisting of either *TEXT or combinations
* of token, separators, and quoted-string>
*</pre>
*
* @since 4.0
*/
public interface Header {
/**
* Get the name of the Header.
*
* @return the name of the Header, never {@code null}
*/
String getName();
/**
* Get the value of the Header.
*
* @return the value of the Header, may be {@code null}
*/
String getValue();
/**
* Parses the value.
*
* @return an array of {@link HeaderElement} entries, may be empty, but is never {@code null}
* @throws ParseException
*/
HeaderElement[] getElements() throws ParseException;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/Header.java
|
Java
|
gpl3
| 2,502
|
/*
* ====================================================================
* 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;
/**
* One element of an HTTP {@link Header header} value consisting of
* a name / value pair and a number of optional name / value parameters.
* <p>
* Some HTTP headers (such as the set-cookie header) have values that
* can be decomposed into multiple elements. Such headers must be in the
* following form:
* </p>
* <pre>
* header = [ element ] *( "," [ element ] )
* element = name [ "=" [ value ] ] *( ";" [ param ] )
* param = name [ "=" [ value ] ]
*
* name = token
* value = ( token | quoted-string )
*
* token = 1*<any char except "=", ",", ";", <"> and
* white space>
* quoted-string = <"> *( text | quoted-char ) <">
* text = any char except <">
* quoted-char = "\" char
* </pre>
* <p>
* Any amount of white space is allowed between any part of the
* header, element or param and is ignored. A missing value in any
* element or param will be stored as the empty {@link String};
* if the "=" is also missing <var>null</var> will be stored instead.
*
* @since 4.0
*/
public interface HeaderElement {
/**
* Returns header element name.
*
* @return header element name
*/
String getName();
/**
* Returns header element value.
*
* @return header element value
*/
String getValue();
/**
* Returns an array of name / value pairs.
*
* @return array of name / value pairs
*/
NameValuePair[] getParameters();
/**
* Returns the first parameter with the given name.
*
* @param name parameter name
*
* @return name / value pair
*/
NameValuePair getParameterByName(String name);
/**
* Returns the total count of parameters.
*
* @return parameter count
*/
int getParameterCount();
/**
* Returns parameter with the given index.
*
* @param index
* @return name / value pair
*/
NameValuePair getParameter(int index);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HeaderElement.java
|
Java
|
gpl3
| 3,225
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* The point of access to the statistics of an {@link HttpConnection}.
*
* @since 4.0
*/
public interface HttpConnectionMetrics {
/**
* Returns the number of requests transferred over the connection,
* 0 if not available.
*/
long getRequestCount();
/**
* Returns the number of responses transferred over the connection,
* 0 if not available.
*/
long getResponseCount();
/**
* Returns the number of bytes transferred over the connection,
* 0 if not available.
*/
long getSentBytesCount();
/**
* Returns the number of bytes transferred over the connection,
* 0 if not available.
*/
long getReceivedBytesCount();
/**
* Return the value for the specified metric.
*
*@param metricName the name of the metric to query.
*
*@return the object representing the metric requested,
* <code>null</code> if the metric cannot not found.
*/
Object getMetric(String metricName);
/**
* Resets the counts
*
*/
void reset();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpConnectionMetrics.java
|
Java
|
gpl3
| 2,301
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.Serializable;
/**
* Represents an HTTP version. HTTP uses a "major.minor" numbering
* scheme to indicate versions of the protocol.
* <p>
* The version of an HTTP message is indicated by an HTTP-Version field
* in the first line of the message.
* </p>
* <pre>
* HTTP-Version = "HTTP" "/" 1*DIGIT "." 1*DIGIT
* </pre>
*
* @since 4.0
*/
public final class HttpVersion extends ProtocolVersion
implements Serializable {
private static final long serialVersionUID = -5856653513894415344L;
/** The protocol name. */
public static final String HTTP = "HTTP";
/** HTTP protocol version 0.9 */
public static final HttpVersion HTTP_0_9 = new HttpVersion(0, 9);
/** HTTP protocol version 1.0 */
public static final HttpVersion HTTP_1_0 = new HttpVersion(1, 0);
/** HTTP protocol version 1.1 */
public static final HttpVersion HTTP_1_1 = new HttpVersion(1, 1);
/**
* Create an HTTP protocol version designator.
*
* @param major the major version number of the HTTP protocol
* @param minor the minor version number of the HTTP protocol
*
* @throws IllegalArgumentException if either major or minor version number is negative
*/
public HttpVersion(int major, int minor) {
super(HTTP, major, minor);
}
/**
* Obtains a specific HTTP version.
*
* @param major the major version
* @param minor the minor version
*
* @return an instance of {@link HttpVersion} with the argument version
*/
public ProtocolVersion forVersion(int major, int minor) {
if ((major == this.major) && (minor == this.minor)) {
return this;
}
if (major == 1) {
if (minor == 0) {
return HTTP_1_0;
}
if (minor == 1) {
return HTTP_1_1;
}
}
if ((major == 0) && (minor == 9)) {
return HTTP_0_9;
}
// argument checking is done in the constructor
return new HttpVersion(major, minor);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpVersion.java
|
Java
|
gpl3
| 3,320
|
/*
* ====================================================================
* 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);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ConnectionReuseStrategy.java
|
Java
|
gpl3
| 2,867
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.Serializable;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Represents a protocol version. The "major.minor" numbering
* scheme is used to indicate versions of the protocol.
* <p>
* This class defines a protocol version as a combination of
* protocol name, major version number, and minor version number.
* Note that {@link #equals} and {@link #hashCode} are defined as
* final here, they cannot be overridden in derived classes.
* </p>
*
* @since 4.0
*/
public class ProtocolVersion implements Serializable, Cloneable {
private static final long serialVersionUID = 8950662842175091068L;
/** Name of the protocol. */
protected final String protocol;
/** Major version number of the protocol */
protected final int major;
/** Minor version number of the protocol */
protected final int minor;
/**
* Create a protocol version designator.
*
* @param protocol the name of the protocol, for example "HTTP"
* @param major the major version number of the protocol
* @param minor the minor version number of the protocol
*/
public ProtocolVersion(String protocol, int major, int minor) {
if (protocol == null) {
throw new IllegalArgumentException
("Protocol name must not be null.");
}
if (major < 0) {
throw new IllegalArgumentException
("Protocol major version number must not be negative.");
}
if (minor < 0) {
throw new IllegalArgumentException
("Protocol minor version number may not be negative");
}
this.protocol = protocol;
this.major = major;
this.minor = minor;
}
/**
* Returns the name of the protocol.
*
* @return the protocol name
*/
public final String getProtocol() {
return protocol;
}
/**
* Returns the major version number of the protocol.
*
* @return the major version number.
*/
public final int getMajor() {
return major;
}
/**
* Returns the minor version number of the HTTP protocol.
*
* @return the minor version number.
*/
public final int getMinor() {
return minor;
}
/**
* Obtains a specific version of this protocol.
* This can be used by derived classes to instantiate themselves instead
* of the base class, and to define constants for commonly used versions.
* <br/>
* The default implementation in this class returns <code>this</code>
* if the version matches, and creates a new {@link ProtocolVersion}
* otherwise.
*
* @param major the major version
* @param minor the minor version
*
* @return a protocol version with the same protocol name
* and the argument version
*/
public ProtocolVersion forVersion(int major, int minor) {
if ((major == this.major) && (minor == this.minor)) {
return this;
}
// argument checking is done in the constructor
return new ProtocolVersion(this.protocol, major, minor);
}
/**
* Obtains a hash code consistent with {@link #equals}.
*
* @return the hashcode of this protocol version
*/
public final int hashCode() {
return this.protocol.hashCode() ^ (this.major * 100000) ^ this.minor;
}
/**
* Checks equality of this protocol version with an object.
* The object is equal if it is a protocl version with the same
* protocol name, major version number, and minor version number.
* The specific class of the object is <i>not</i> relevant,
* instances of derived classes with identical attributes are
* equal to instances of the base class and vice versa.
*
* @param obj the object to compare with
*
* @return <code>true</code> if the argument is the same protocol version,
* <code>false</code> otherwise
*/
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ProtocolVersion)) {
return false;
}
ProtocolVersion that = (ProtocolVersion) obj;
return ((this.protocol.equals(that.protocol)) &&
(this.major == that.major) &&
(this.minor == that.minor));
}
/**
* Checks whether this protocol can be compared to another one.
* Only protocol versions with the same protocol name can be
* {@link #compareToVersion compared}.
*
* @param that the protocol version to consider
*
* @return <code>true</code> if {@link #compareToVersion compareToVersion}
* can be called with the argument, <code>false</code> otherwise
*/
public boolean isComparable(ProtocolVersion that) {
return (that != null) && this.protocol.equals(that.protocol);
}
/**
* Compares this protocol version with another one.
* Only protocol versions with the same protocol name can be compared.
* This method does <i>not</i> define a total ordering, as it would be
* required for {@link java.lang.Comparable}.
*
* @param that the protocl version to compare with
*
* @return a negative integer, zero, or a positive integer
* as this version is less than, equal to, or greater than
* the argument version.
*
* @throws IllegalArgumentException
* if the argument has a different protocol name than this object,
* or if the argument is <code>null</code>
*/
public int compareToVersion(ProtocolVersion that) {
if (that == null) {
throw new IllegalArgumentException
("Protocol version must not be null.");
}
if (!this.protocol.equals(that.protocol)) {
throw new IllegalArgumentException
("Versions for different protocols cannot be compared. " +
this + " " + that);
}
int delta = getMajor() - that.getMajor();
if (delta == 0) {
delta = getMinor() - that.getMinor();
}
return delta;
}
/**
* Tests if this protocol version is greater or equal to the given one.
*
* @param version the version against which to check this version
*
* @return <code>true</code> if this protocol version is
* {@link #isComparable comparable} to the argument
* and {@link #compareToVersion compares} as greater or equal,
* <code>false</code> otherwise
*/
public final boolean greaterEquals(ProtocolVersion version) {
return isComparable(version) && (compareToVersion(version) >= 0);
}
/**
* Tests if this protocol version is less or equal to the given one.
*
* @param version the version against which to check this version
*
* @return <code>true</code> if this protocol version is
* {@link #isComparable comparable} to the argument
* and {@link #compareToVersion compares} as less or equal,
* <code>false</code> otherwise
*/
public final boolean lessEquals(ProtocolVersion version) {
return isComparable(version) && (compareToVersion(version) <= 0);
}
/**
* Converts this protocol version to a string.
*
* @return a protocol version string, like "HTTP/1.1"
*/
public String toString() {
CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append(this.protocol);
buffer.append('/');
buffer.append(Integer.toString(this.major));
buffer.append('.');
buffer.append(Integer.toString(this.minor));
return buffer.toString();
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ProtocolVersion.java
|
Java
|
gpl3
| 9,206
|
/*
* ====================================================================
* 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 a malformed chunked stream.
*
* @since 4.0
*/
public class MalformedChunkCodingException extends IOException {
private static final long serialVersionUID = 2158560246948994524L;
/**
* Creates a MalformedChunkCodingException without a detail message.
*/
public MalformedChunkCodingException() {
super();
}
/**
* Creates a MalformedChunkCodingException with the specified detail message.
*
* @param message The exception detail message
*/
public MalformedChunkCodingException(final String message) {
super(message);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/MalformedChunkCodingException.java
|
Java
|
gpl3
| 1,858
|
<html>
<head>
<!--
/*
* ====================================================================
* 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/>.
*
*/
-->
</head>
<body>
Representations for HTTP message entities.
An {@link org.apache.ogt.http.HttpEntity entity} is the optional content of a
{@link org.apache.ogt.http.HttpMessage message}.
This package provides a basic selection of entity implementations
that can obtain content from
{@link org.apache.ogt.http.entity.ByteArrayEntity byte array},
{@link org.apache.ogt.http.entity.StringEntity string},
{@link org.apache.ogt.http.entity.FileEntity file}, or through an arbitrary
{@link org.apache.ogt.http.entity.InputStreamEntity input stream}.
If a message is received from an open connection, usually it is
represented by
{@link org.apache.ogt.http.entity.BasicHttpEntity streamed} entity.
Entity implementations can be
{@link org.apache.ogt.http.entity.HttpEntityWrapper wrapped},
for example to
{@link org.apache.ogt.http.entity.BufferedHttpEntity buffer}
the content in memory.
</body>
</html>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/package.html
|
HTML
|
gpl3
| 2,107
|
/*
* ====================================================================
* 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
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/BasicHttpEntity.java
|
Java
|
gpl3
| 4,123
|
/*
* ====================================================================
* 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;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/ContentLengthStrategy.java
|
Java
|
gpl3
| 2,114
|
/*
* ====================================================================
* 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
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/BufferedHttpEntity.java
|
Java
|
gpl3
| 3,687
|
/*
* ====================================================================
* 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;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/ContentProducer.java
|
Java
|
gpl3
| 1,539
|
/*
* ====================================================================
* 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();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/SerializableEntity.java
|
Java
|
gpl3
| 3,739
|
/*
* ====================================================================
* 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;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/EntityTemplate.java
|
Java
|
gpl3
| 2,400
|
/*
* ====================================================================
* 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 {
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/AbstractHttpEntity.java
|
Java
|
gpl3
| 5,799
|
/*
* ====================================================================
* 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
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/FileEntity.java
|
Java
|
gpl3
| 3,012
|
/*
* ====================================================================
* 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
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/StringEntity.java
|
Java
|
gpl3
| 4,797
|
/*
* ====================================================================
* 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();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/InputStreamEntity.java
|
Java
|
gpl3
| 3,696
|
/*
* ====================================================================
* 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
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/ByteArrayEntity.java
|
Java
|
gpl3
| 2,597
|
/*
* ====================================================================
* 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();
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/entity/HttpEntityWrapper.java
|
Java
|
gpl3
| 3,355
|
/*
* ====================================================================
* 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;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpEntity.java
|
Java
|
gpl3
| 8,071
|
/*
* ====================================================================
* 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;
/**
* A factory for {@link HttpResponse HttpResponse} objects.
*
* @since 4.0
*/
public interface HttpResponseFactory {
/**
* Creates a new response from status line elements.
*
* @param ver the protocol version
* @param status the status code
* @param context the context from which to determine the locale
* for looking up a reason phrase to the status code, or
* <code>null</code> to use the default locale
*
* @return the new response with an initialized status line
*/
HttpResponse newHttpResponse(ProtocolVersion ver, int status,
HttpContext context);
/**
* Creates a new response from a status line.
*
* @param statusline the status line
* @param context the context from which to determine the locale
* for looking up a reason phrase if the status code
* is updated, or
* <code>null</code> to use the default locale
*
* @return the new response with the argument status line
*/
HttpResponse newHttpResponse(StatusLine statusline,
HttpContext context);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpResponseFactory.java
|
Java
|
gpl3
| 2,520
|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.util.Locale;
/**
* After receiving and interpreting a request message, a server responds
* with an HTTP response message.
* <pre>
* Response = Status-Line
* *(( general-header
* | response-header
* | entity-header ) CRLF)
* CRLF
* [ message-body ]
* </pre>
*
* @since 4.0
*/
public interface HttpResponse extends HttpMessage {
/**
* Obtains the status line of this response.
* The status line can be set using one of the
* {@link #setStatusLine setStatusLine} methods,
* or it can be initialized in a constructor.
*
* @return the status line, or <code>null</code> if not yet set
*/
StatusLine getStatusLine();
/**
* Sets the status line of this response.
*
* @param statusline the status line of this response
*/
void setStatusLine(StatusLine statusline);
/**
* Sets the status line of this response.
* The reason phrase will be determined based on the current
* {@link #getLocale locale}.
*
* @param ver the HTTP version
* @param code the status code
*/
void setStatusLine(ProtocolVersion ver, int code);
/**
* Sets the status line of this response with a reason phrase.
*
* @param ver the HTTP version
* @param code the status code
* @param reason the reason phrase, or <code>null</code> to omit
*/
void setStatusLine(ProtocolVersion ver, int code, String reason);
/**
* Updates the status line of this response with a new status code.
* The status line can only be updated if it is available. It must
* have been set either explicitly or in a constructor.
* <br/>
* The reason phrase will be updated according to the new status code,
* based on the current {@link #getLocale locale}. It can be set
* explicitly using {@link #setReasonPhrase setReasonPhrase}.
*
* @param code the HTTP status code.
*
* @throws IllegalStateException
* if the status line has not be set
*
* @see HttpStatus
* @see #setStatusLine(StatusLine)
* @see #setStatusLine(ProtocolVersion,int)
*/
void setStatusCode(int code)
throws IllegalStateException;
/**
* Updates the status line of this response with a new reason phrase.
* The status line can only be updated if it is available. It must
* have been set either explicitly or in a constructor.
*
* @param reason the new reason phrase as a single-line string, or
* <code>null</code> to unset the reason phrase
*
* @throws IllegalStateException
* if the status line has not be set
*
* @see #setStatusLine(StatusLine)
* @see #setStatusLine(ProtocolVersion,int)
*/
void setReasonPhrase(String reason)
throws IllegalStateException;
/**
* Obtains the message entity of this response, if any.
* The entity is provided by calling {@link #setEntity setEntity}.
*
* @return the response entity, or
* <code>null</code> if there is none
*/
HttpEntity getEntity();
/**
* Associates a response entity with this response.
*
* @param entity the entity to associate with this response, or
* <code>null</code> to unset
*/
void setEntity(HttpEntity entity);
/**
* Obtains the locale of this response.
* The locale is used to determine the reason phrase
* for the {@link #setStatusCode status code}.
* It can be changed using {@link #setLocale setLocale}.
*
* @return the locale of this response, never <code>null</code>
*/
Locale getLocale();
/**
* Changes the locale of this response.
* If there is a status line, it's reason phrase will be updated
* according to the status code and new locale.
*
* @param loc the new locale
*
* @see #getLocale getLocale
* @see #setStatusCode setStatusCode
*/
void setLocale(Locale loc);
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpResponse.java
|
Java
|
gpl3
| 5,400
|
/*
* ====================================================================
* 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 request message from a client to a server includes, within the
* first line of that message, the method to be applied to the resource,
* the identifier of the resource, and the protocol version in use.
* <pre>
* Request = Request-Line
* *(( general-header
* | request-header
* | entity-header ) CRLF)
* CRLF
* [ message-body ]
* </pre>
*
* @since 4.0
*/
public interface HttpRequest extends HttpMessage {
/**
* Returns the request line of this request.
* @return the request line.
*/
RequestLine getRequestLine();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpRequest.java
|
Java
|
gpl3
| 1,896
|
/*
* ====================================================================
* 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();
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HeaderIterator.java
|
Java
|
gpl3
| 1,835
|
/*
* ====================================================================
* 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);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/UnsupportedHttpVersionException.java
|
Java
|
gpl3
| 1,869
|
/*
====================================================================
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/>.
====================================================================
Based on the CSS file for the Spring Reference Documentation.
*/
body {
text-align: justify;
margin-right: 2em;
margin-left: 2em;
}
a:active {
color: #003399;
}
a:visited {
color: #888888;
}
p {
font-family: Verdana, Arial, sans-serif;
}
dt {
font-family: Verdana, Arial, sans-serif;
font-size: 12px;
}
p, dl, dt, dd, blockquote {
color: #000000;
margin-bottom: 3px;
margin-top: 3px;
padding-top: 0px;
}
ol, ul, p {
margin-top: 6px;
margin-bottom: 6px;
}
p, blockquote {
font-size: 90%;
}
p.releaseinfo {
font-size: 100%;
font-weight: bold;
font-family: Verdana, Arial, helvetica, sans-serif;
padding-top: 10px;
}
p.pubdate {
font-size: 120%;
font-weight: bold;
font-family: Verdana, Arial, helvetica, sans-serif;
}
td {
font-size: 80%;
}
td, th, span {
color: #000000;
}
blockquote {
margin-right: 0px;
}
h1, h2, h3, h4, h6, H6 {
color: #000000;
font-weight: 500;
margin-top: 0px;
padding-top: 14px;
font-family: Verdana, Arial, helvetica, sans-serif;
margin-bottom: 0px;
}
h2.title {
font-weight: 800;
margin-bottom: 8px;
}
h2.subtitle {
font-weight: 800;
margin-bottom: 20px;
}
.firstname, .surname {
font-size: 12px;
font-family: Verdana, Arial, helvetica, sans-serif;
}
table {
border-collapse: collapse;
border-spacing: 0;
border: 1px black;
empty-cells: hide;
margin: 10px 0px 30px 50px;
width: 90%;
}
div.table {
margin: 30px 0px 30px 0px;
border: 1px dashed gray;
padding: 10px;
}
div .table-contents table {
border: 1px solid black;
}
div.table > p.title {
padding-left: 10px;
}
td {
padding: 4pt;
font-family: Verdana, Arial, helvetica, sans-serif;
}
div.warning TD {
text-align: justify;
}
h1 {
font-size: 150%;
}
h2 {
font-size: 110%;
}
h3 {
font-size: 100%;
font-weight: bold;
}
h4 {
font-size: 90%;
font-weight: bold;
}
h5 {
font-size: 90%;
font-style: italic;
}
h6 {
font-size: 100%;
font-style: italic;
}
tt {
font-size: 110%;
font-family: "Courier New", Courier, monospace;
color: #000000;
}
.navheader, .navfooter {
border: none;
}
pre {
font-size: 110%;
padding: 5px;
border-style: solid;
border-width: 1px;
border-color: #CCCCCC;
background-color: #f3f5e9;
}
ul, ol, li {
list-style: disc;
}
hr {
width: 100%;
height: 1px;
background-color: #CCCCCC;
border-width: 0px;
padding: 0px;
}
.variablelist {
padding-top: 10px;
padding-bottom: 10px;
margin: 0;
}
.term {
font-weight: bold;
}
.mediaobject {
padding-top: 30px;
padding-bottom: 30px;
}
.legalnotice {
font-family: Verdana, Arial, helvetica, sans-serif;
font-size: 12px;
font-style: italic;
}
.sidebar {
float: right;
margin: 10px 0px 10px 30px;
padding: 10px 20px 20px 20px;
width: 33%;
border: 1px solid black;
background-color: #F4F4F4;
font-size: 14px;
}
.property {
font-family: "Courier New", Courier, monospace;
}
a code {
font-family: Verdana, Arial, monospace;
font-size: 12px;
}
td code {
font-size: 110%;
}
div.note * td,
div.tip * td,
div.warning * td,
div.calloutlist * td {
text-align: justify;
font-size: 100%;
}
.programlisting .interfacename,
.programlisting .literal,
.programlisting .classname {
font-size: 95%;
}
.title .interfacename,
.title .literal,
.title .classname {
font-size: 130%;
}
.programlisting * .lineannotation,
.programlisting * .lineannotation * {
color: blue;
}
.bannerLeft, .bannerRight {
font-size: xx-large;
font-weight: bold;
}
.bannerLeft img, .bannerRight img {
margin: 0px;
}
.bannerLeft img {
float:left;
text-shadow: #7CFC00;
}
.bannerRight img {
float:right;
text-shadow: #7CFC00;
}
.banner {
padding: 0px;
}
.banner img {
border: none;
}
.clear {
clear:both;
visibility: hidden;
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/css/hc-tutorial.css
|
CSS
|
gpl3
| 5,273
|
<?xml version="1.0" encoding="utf-8"?>
<!--
====================================================================
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 />.
====================================================================
Based on the XSL HTML configuration file for the Spring
Reference Documentation.
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<!--###################################################
HTML Settings
################################################### -->
<xsl:param name="chunk.section.depth">'5'</xsl:param>
<xsl:param name="use.id.as.filename">'1'</xsl:param>
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="use.extensions">1</xsl:param>
<xsl:param name="tablecolumns.extension">0</xsl:param>
<xsl:param name="callout.extensions">1</xsl:param>
<xsl:param name="graphicsize.extension">0</xsl:param>
<!--###################################################
Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">3</xsl:param>
<!--###################################################
Labels
################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!--###################################################
Callouts
################################################### -->
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.graphics">1</xsl:param>
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name"/>
<xsl:apply-templates mode="titlepage.mode" select="./contrib"/>
<xsl:apply-templates mode="titlepage.mode" select="./affiliation"/>
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p/>
<xsl:apply-templates mode="titlepage.mode"/>
</div>
</xsl:template>
<!--###################################################
Headers and Footers
################################################### -->
<xsl:template name="user.header.navigation">
<div class="banner">
<a class="bannerLeft" href="http://www.apache.org/"
title="Apache Software Foundation">
<img style="border:none;" src="images/asf_logo_wide.gif"/>
</a>
<a class="bannerRight" href="http://hc.apache.org/httpcomponents-core-ga/"
title="Apache HttpComponents Core">
<img style="border:none;" src="images/hc_logo.png"/>
</a>
<div class="clear"/>
</div>
</xsl:template>
</xsl:stylesheet>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/xsl/html_chunk.xsl
|
XSLT
|
gpl3
| 5,079
|
<?xml version="1.0" encoding="utf-8"?>
<!--
====================================================================
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 />.
====================================================================
Based on the XSL HTML configuration file for the Spring
Reference Documentation.
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<!--###################################################
HTML Settings
################################################### -->
<xsl:param name="html.stylesheet">html.css</xsl:param>
<!-- These extensions are required for table printing and other stuff -->
<xsl:param name="use.extensions">1</xsl:param>
<xsl:param name="tablecolumns.extension">0</xsl:param>
<xsl:param name="callout.extensions">1</xsl:param>
<xsl:param name="graphicsize.extension">0</xsl:param>
<!--###################################################
Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">3</xsl:param>
<!--###################################################
Labels
################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!--###################################################
Callouts
################################################### -->
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">0</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!--###################################################
Admonitions
################################################### -->
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">0</xsl:param>
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<xsl:template match="author" mode="titlepage.mode">
<xsl:if test="name(preceding-sibling::*[1]) = 'author'">
<xsl:text>, </xsl:text>
</xsl:if>
<span class="{name(.)}">
<xsl:call-template name="person.name"/>
<xsl:apply-templates mode="titlepage.mode" select="./contrib"/>
<xsl:apply-templates mode="titlepage.mode" select="./affiliation"/>
</span>
</xsl:template>
<xsl:template match="authorgroup" mode="titlepage.mode">
<div class="{name(.)}">
<h2>Authors</h2>
<p/>
<xsl:apply-templates mode="titlepage.mode"/>
</div>
</xsl:template>
</xsl:stylesheet>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/xsl/html.xsl
|
XSLT
|
gpl3
| 4,600
|
<?xml version="1.0" encoding="utf-8"?>
<!--
====================================================================
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 />.
====================================================================
Based on XSL FO (PDF) stylesheet for the Spring reference
documentation.
Thanks are due to Christian Bauer of the Hibernate project
team for writing the original stylesheet upon which this one
is based.
-->
<xsl:stylesheet xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
xmlns:fo="http://www.w3.org/1999/XSL/Format"
version="1.0">
<xsl:import href="urn:docbkx:stylesheet"/>
<!-- Prevent blank pages in output -->
<xsl:template name="book.titlepage.before.verso">
</xsl:template>
<xsl:template name="book.titlepage.verso">
</xsl:template>
<xsl:template name="book.titlepage.separator">
</xsl:template>
<!--###################################################
Header
################################################### -->
<!-- More space in the center header for long text -->
<xsl:attribute-set name="header.content.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$body.font.family"/>
</xsl:attribute>
<xsl:attribute name="margin-left">-5em</xsl:attribute>
<xsl:attribute name="margin-right">-5em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Custom Footer
################################################### -->
<xsl:template name="footer.content">
<xsl:param name="pageclass" select="''"/>
<xsl:param name="sequence" select="''"/>
<xsl:param name="position" select="''"/>
<xsl:param name="gentext-key" select="''"/>
<xsl:variable name="Version">
<xsl:if test="//releaseinfo">
<xsl:text>HttpCore (</xsl:text>
<xsl:value-of select="//releaseinfo"/>
<xsl:text>)</xsl:text>
</xsl:if>
</xsl:variable>
<xsl:choose>
<xsl:when test="$sequence='blank'">
<xsl:if test="$position = 'center'">
<xsl:value-of select="$Version"/>
</xsl:if>
</xsl:when>
<!-- for double sided printing, print page numbers on alternating sides (of the page) -->
<xsl:when test="$double.sided != 0">
<xsl:choose>
<xsl:when test="$sequence = 'even' and $position='left'">
<fo:page-number/>
</xsl:when>
<xsl:when test="$sequence = 'odd' and $position='right'">
<fo:page-number/>
</xsl:when>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version"/>
</xsl:when>
</xsl:choose>
</xsl:when>
<!-- for single sided printing, print all page numbers on the right (of the page) -->
<xsl:when test="$double.sided = 0">
<xsl:choose>
<xsl:when test="$position='center'">
<xsl:value-of select="$Version"/>
</xsl:when>
<xsl:when test="$position='right'">
<fo:page-number/>
</xsl:when>
</xsl:choose>
</xsl:when>
</xsl:choose>
</xsl:template>
<!--###################################################
Table Of Contents
################################################### -->
<!-- Generate the TOCs for named components only -->
<xsl:param name="generate.toc">
book toc
</xsl:param>
<!-- Show only Sections up to level 3 in the TOCs -->
<xsl:param name="toc.section.depth">2</xsl:param>
<!-- Dot and Whitespace as separator in TOC between Label and Title-->
<xsl:param name="autotoc.label.separator" select="'. '"/>
<!-- Show titles in bookmarks pane -->
<xsl:param name="fop1.extensions">1</xsl:param>
<!--###################################################
Paper & Page Size
################################################### -->
<!-- Paper type, no headers on blank pages, no double sided printing -->
<xsl:param name="paper.type" select="'A4'"/>
<xsl:param name="double.sided">0</xsl:param>
<xsl:param name="headers.on.blank.pages">0</xsl:param>
<xsl:param name="footers.on.blank.pages">0</xsl:param>
<!-- Space between paper border and content (chaotic stuff, don't touch) -->
<xsl:param name="page.margin.top">5mm</xsl:param>
<xsl:param name="region.before.extent">10mm</xsl:param>
<xsl:param name="body.margin.top">10mm</xsl:param>
<xsl:param name="body.margin.bottom">15mm</xsl:param>
<xsl:param name="region.after.extent">10mm</xsl:param>
<xsl:param name="page.margin.bottom">0mm</xsl:param>
<xsl:param name="page.margin.outer">18mm</xsl:param>
<xsl:param name="page.margin.inner">18mm</xsl:param>
<!-- No intendation of Titles -->
<xsl:param name="title.margin.left">0pc</xsl:param>
<!--###################################################
Fonts & Styles
################################################### -->
<!-- Left aligned text and no hyphenation -->
<xsl:param name="alignment">justify</xsl:param>
<xsl:param name="hyphenate">false</xsl:param>
<!-- Default Font size -->
<xsl:param name="body.font.master">11</xsl:param>
<xsl:param name="body.font.small">8</xsl:param>
<!-- Line height in body text -->
<xsl:param name="line-height">1.4</xsl:param>
<!-- Monospaced fonts are smaller than regular text -->
<xsl:attribute-set name="monospace.properties">
<xsl:attribute name="font-family">
<xsl:value-of select="$monospace.font.family"/>
</xsl:attribute>
<xsl:attribute name="font-size">0.8em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Tables
################################################### -->
<!-- The table width should be adapted to the paper size -->
<xsl:param name="default.table.width">17.4cm</xsl:param>
<!-- Some padding inside tables -->
<xsl:attribute-set name="table.cell.padding">
<xsl:attribute name="padding-left">4pt</xsl:attribute>
<xsl:attribute name="padding-right">4pt</xsl:attribute>
<xsl:attribute name="padding-top">4pt</xsl:attribute>
<xsl:attribute name="padding-bottom">4pt</xsl:attribute>
</xsl:attribute-set>
<!-- Only hairlines as frame and cell borders in tables -->
<xsl:param name="table.frame.border.thickness">0.1pt</xsl:param>
<xsl:param name="table.cell.border.thickness">0.1pt</xsl:param>
<!--###################################################
Labels
################################################### -->
<!-- Label Chapters and Sections (numbering) -->
<xsl:param name="chapter.autolabel">1</xsl:param>
<xsl:param name="section.autolabel" select="1"/>
<xsl:param name="section.label.includes.component.label" select="1"/>
<!--###################################################
Titles
################################################### -->
<!-- Chapter title size -->
<xsl:attribute-set name="chapter.titlepage.recto.style">
<xsl:attribute name="text-align">left</xsl:attribute>
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.8"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
</xsl:attribute-set>
<!-- Why is the font-size for chapters hardcoded in the XSL FO templates?
Let's remove it, so this sucker can use our attribute-set only... -->
<xsl:template match="title" mode="chapter.titlepage.recto.auto.mode">
<fo:block xmlns:fo="http://www.w3.org/1999/XSL/Format"
xsl:use-attribute-sets="chapter.titlepage.recto.style">
<xsl:call-template name="component.title">
<xsl:with-param name="node" select="ancestor-or-self::chapter[1]"/>
</xsl:call-template>
</fo:block>
</xsl:template>
<!-- Sections 1, 2 and 3 titles have a small bump factor and padding -->
<xsl:attribute-set name="section.title.level1.properties">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.5"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level2.properties">
<xsl:attribute name="space-before.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.6em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.6em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.25"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="section.title.level3.properties">
<xsl:attribute name="space-before.optimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.4em</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master * 1.0"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<!-- Titles of formal objects (tables, examples, ...) -->
<xsl:attribute-set name="formal.title.properties" use-attribute-sets="normal.para.spacing">
<xsl:attribute name="font-weight">bold</xsl:attribute>
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.master"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
<xsl:attribute name="hyphenate">false</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.4em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.6em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.8em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Programlistings
################################################### -->
<!-- Verbatim text formatting (programlistings) -->
<xsl:attribute-set name="monospace.verbatim.properties">
<xsl:attribute name="font-size">
<xsl:value-of select="$body.font.small * 1.0"/>
<xsl:text>pt</xsl:text>
</xsl:attribute>
</xsl:attribute-set>
<xsl:attribute-set name="verbatim.properties">
<xsl:attribute name="space-before.minimum">1em</xsl:attribute>
<xsl:attribute name="space-before.optimum">1em</xsl:attribute>
<xsl:attribute name="space-before.maximum">1em</xsl:attribute>
<xsl:attribute name="border-color">#444444</xsl:attribute>
<xsl:attribute name="border-style">solid</xsl:attribute>
<xsl:attribute name="border-width">0.1pt</xsl:attribute>
<xsl:attribute name="padding-top">0.5em</xsl:attribute>
<xsl:attribute name="padding-left">0.5em</xsl:attribute>
<xsl:attribute name="padding-right">0.5em</xsl:attribute>
<xsl:attribute name="padding-bottom">0.5em</xsl:attribute>
<xsl:attribute name="margin-left">0.5em</xsl:attribute>
<xsl:attribute name="margin-right">0.5em</xsl:attribute>
</xsl:attribute-set>
<!-- Shade (background) programlistings -->
<xsl:param name="shade.verbatim">1</xsl:param>
<xsl:attribute-set name="shade.verbatim.style">
<xsl:attribute name="background-color">#F0F0F0</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
Callouts
################################################### -->
<!-- Use images for callouts instead of (1) (2) (3) -->
<xsl:param name="callout.graphics">0</xsl:param>
<xsl:param name="callout.unicode">1</xsl:param>
<!-- Place callout marks at this column in annotated areas -->
<xsl:param name="callout.defaultcolumn">90</xsl:param>
<!--###################################################
Admonitions
################################################### -->
<!-- Use nice graphics for admonitions -->
<xsl:param name="admon.graphics">'1'</xsl:param>
<!-- <xsl:param name="admon.graphics.path">&admon_gfx_path;</xsl:param> -->
<!--###################################################
Misc
################################################### -->
<!-- Placement of titles -->
<xsl:param name="formal.title.placement">
figure after
example before
equation before
table before
procedure before
</xsl:param>
<!-- Format Variable Lists as Blocks (prevents horizontal overflow) -->
<xsl:param name="variablelist.as.blocks">1</xsl:param>
<!-- The horrible list spacing problems -->
<xsl:attribute-set name="list.block.spacing">
<xsl:attribute name="space-before.optimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.minimum">0.8em</xsl:attribute>
<xsl:attribute name="space-before.maximum">0.8em</xsl:attribute>
<xsl:attribute name="space-after.optimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.minimum">0.1em</xsl:attribute>
<xsl:attribute name="space-after.maximum">0.1em</xsl:attribute>
</xsl:attribute-set>
<!--###################################################
colored and hyphenated links
################################################### -->
<xsl:template match="ulink">
<fo:basic-link external-destination="{@url}"
xsl:use-attribute-sets="xref.properties"
text-decoration="underline"
color="blue">
<xsl:choose>
<xsl:when test="count(child::node())=0">
<xsl:value-of select="@url"/>
</xsl:when>
<xsl:otherwise>
<xsl:apply-templates/>
</xsl:otherwise>
</xsl:choose>
</fo:basic-link>
</xsl:template>
</xsl:stylesheet>
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/src/docbkx/resources/xsl/fopdf.xsl
|
XSLT
|
gpl3
| 16,604
|
@import url("../../css/hc-maven.css");
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/src/site/resources/css/site.css
|
CSS
|
gpl3
| 39
|
/*
* ====================================================================
* 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;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.http.mockup.HttpClientNio;
import org.apache.http.mockup.HttpServerNio;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
/**
* Base class for all HttpCore NIO tests
*
*/
public class HttpCoreNIOTestBase extends TestCase {
public HttpCoreNIOTestBase(String testName) {
super(testName);
}
protected HttpServerNio server;
protected HttpClientNio client;
@Override
protected void setUp() throws Exception {
HttpParams serverParams = new SyncBasicHttpParams();
serverParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.server = new HttpServerNio(serverParams);
this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler());
HttpParams clientParams = new SyncBasicHttpParams();
clientParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.client = new HttpClientNio(clientParams);
this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler());
}
@Override
protected void tearDown() {
try {
this.client.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
try {
this.server.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/HttpCoreNIOTestBase.java
|
Java
|
gpl3
| 3,505
|
/*
* ====================================================================
* 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;
public class OoopsieRuntimeException extends RuntimeException {
private static final long serialVersionUID = 662807254163212266L;
public OoopsieRuntimeException() {
super("Ooopsie!!!");
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/OoopsieRuntimeException.java
|
Java
|
gpl3
| 1,424
|
/*
* ====================================================================
* 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.mockup;
import org.apache.http.nio.protocol.NHttpRequestHandler;
import org.apache.http.nio.protocol.NHttpRequestHandlerResolver;
public class SimpleNHttpRequestHandlerResolver implements NHttpRequestHandlerResolver {
private final NHttpRequestHandler handler;
public SimpleNHttpRequestHandlerResolver(final NHttpRequestHandler handler) {
this.handler = handler;
}
public NHttpRequestHandler lookup(final String requestURI) {
return this.handler;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/SimpleNHttpRequestHandlerResolver.java
|
Java
|
gpl3
| 1,701
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.params.HttpParams;
/**
* Trivial test server based on HttpCore NIO SSL
*
*/
public class HttpSSLServer {
private final SSLContext sslcontext;
private final DefaultListeningIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
private ListenerEndpoint endpoint;
public HttpSSLServer(final HttpParams params) throws Exception {
super();
this.params = params;
this.sslcontext = createSSLContext();
this.ioReactor = new DefaultListeningIOReactor(2, this.params);
}
private KeyManagerFactory createKeyManagerFactory() throws NoSuchAlgorithmException {
String algo = KeyManagerFactory.getDefaultAlgorithm();
try {
return KeyManagerFactory.getInstance(algo);
} catch (NoSuchAlgorithmException ex) {
return KeyManagerFactory.getInstance("SunX509");
}
}
protected SSLContext createSSLContext() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
KeyManagerFactory kmfactory = createKeyManagerFactory();
kmfactory.init(keystore, "nopassword".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
return sslcontext;
}
public HttpParams getParams() {
return this.params;
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpServiceHandler serviceHandler,
final SSLContext sslcontext,
final HttpParams params) {
return new SSLServerIOEventDispatch(serviceHandler, sslcontext, params);
}
private void execute(final NHttpServiceHandler serviceHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
serviceHandler,
this.sslcontext,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public ListenerEndpoint getListenerEndpoint() {
return this.endpoint;
}
public void start(final NHttpServiceHandler serviceHandler) {
this.endpoint = this.ioReactor.listen(new InetSocketAddress(0));
this.thread = new IOReactorThread(serviceHandler);
this.thread.start();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
if (this.thread != null) {
this.thread.join(500);
}
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpServiceHandler serviceHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
try {
execute(this.serviceHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpSSLServer.java
|
Java
|
gpl3
| 6,048
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import org.apache.http.HttpException;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.EventListener;
public class SimpleEventListener implements EventListener {
public SimpleEventListener() {
super();
}
public void connectionOpen(final NHttpConnection conn) {
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out");
}
public void connectionClosed(final NHttpConnection conn) {
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
ex.printStackTrace(System.out);
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
ex.printStackTrace(System.out);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/SimpleEventListener.java
|
Java
|
gpl3
| 2,036
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.params.HttpParams;
public class HttpClientNio {
private final DefaultConnectingIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
public HttpClientNio(final HttpParams params) throws IOException {
super();
this.ioReactor = new DefaultConnectingIOReactor(2, params);
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpClientHandler clientHandler, final HttpParams params) {
return new DefaultClientIOEventDispatch(clientHandler, params);
}
private void execute(final NHttpClientHandler clientHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
clientHandler,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) {
return this.ioReactor.connect(address, null, attachment, null);
}
public void start(final NHttpClientHandler clientHandler) {
this.thread = new IOReactorThread(clientHandler);
this.thread.start();
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
join(500);
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpClientHandler clientHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpClientHandler clientHandler) {
super();
this.clientHandler = clientHandler;
}
@Override
public void run() {
try {
execute(this.clientHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpClientNio.java
|
Java
|
gpl3
| 4,511
|
/*
* ====================================================================
* 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.mockup;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerResolver;
public class SimpleHttpRequestHandlerResolver implements HttpRequestHandlerResolver {
private final HttpRequestHandler handler;
public SimpleHttpRequestHandlerResolver(final HttpRequestHandler handler) {
super();
this.handler = handler;
}
public HttpRequestHandler lookup(final String requestURI) {
return this.handler;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/SimpleHttpRequestHandlerResolver.java
|
Java
|
gpl3
| 1,702
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.util.List;
import org.apache.http.impl.nio.DefaultServerIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.nio.NHttpServiceHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.ListenerEndpoint;
import org.apache.http.params.HttpParams;
/**
* Trivial test server based on HttpCore NIO
*
*/
public class HttpServerNio {
private final DefaultListeningIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
private ListenerEndpoint endpoint;
public HttpServerNio(final HttpParams params) throws IOException {
super();
this.ioReactor = new DefaultListeningIOReactor(2, params);
this.params = params;
}
public HttpParams getParams() {
return this.params;
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpServiceHandler serviceHandler, final HttpParams params) {
return new DefaultServerIOEventDispatch(serviceHandler, params);
}
private void execute(final NHttpServiceHandler serviceHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
serviceHandler,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public ListenerEndpoint getListenerEndpoint() {
return this.endpoint;
}
public void setEndpoint(ListenerEndpoint endpoint) {
this.endpoint = endpoint;
}
public void start(final NHttpServiceHandler serviceHandler) {
this.endpoint = this.ioReactor.listen(new InetSocketAddress(0));
this.thread = new IOReactorThread(serviceHandler);
this.thread.start();
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
join(500);
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpServiceHandler serviceHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpServiceHandler serviceHandler) {
super();
this.serviceHandler = serviceHandler;
}
@Override
public void run() {
try {
execute(this.serviceHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpServerNio.java
|
Java
|
gpl3
| 4,702
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.nio.ContentDecoder;
public class MockupDecoder implements ContentDecoder {
private final ReadableByteChannel channel;
private boolean completed;
public MockupDecoder(final ReadableByteChannel channel) {
super();
this.channel = channel;
}
public int read(final ByteBuffer dst) throws IOException {
if (dst == null) {
throw new IllegalArgumentException("Byte buffer may not be null");
}
if (this.completed) {
return -1;
}
int bytesRead = this.channel.read(dst);
if (bytesRead == -1) {
this.completed = true;
}
return bytesRead;
}
public boolean isCompleted() {
return this.completed;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/MockupDecoder.java
|
Java
|
gpl3
| 2,092
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.URL;
import java.security.KeyStore;
import java.security.NoSuchAlgorithmException;
import java.util.List;
import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.TrustManagerFactory;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.reactor.ExceptionEvent;
import org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch;
import org.apache.http.nio.NHttpClientHandler;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.params.HttpParams;
public class HttpSSLClient {
private final SSLContext sslcontext;
private final DefaultConnectingIOReactor ioReactor;
private final HttpParams params;
private volatile IOReactorThread thread;
public HttpSSLClient(final HttpParams params) throws Exception {
super();
this.params = params;
this.sslcontext = createSSLContext();
this.ioReactor = new DefaultConnectingIOReactor(2, this.params);
}
private TrustManagerFactory createTrustManagerFactory() throws NoSuchAlgorithmException {
String algo = TrustManagerFactory.getDefaultAlgorithm();
try {
return TrustManagerFactory.getInstance(algo);
} catch (NoSuchAlgorithmException ex) {
return TrustManagerFactory.getInstance("SunX509");
}
}
protected SSLContext createSSLContext() throws Exception {
ClassLoader cl = getClass().getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
TrustManagerFactory tmfactory = createTrustManagerFactory();
tmfactory.init(keystore);
TrustManager[] trustmanagers = tmfactory.getTrustManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(null, trustmanagers, null);
return sslcontext;
}
public HttpParams getParams() {
return this.params;
}
public IOReactorStatus getStatus() {
return this.ioReactor.getStatus();
}
public List<ExceptionEvent> getAuditLog() {
return this.ioReactor.getAuditLog();
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.ioReactor.setExceptionHandler(exceptionHandler);
}
protected IOEventDispatch createIOEventDispatch(
final NHttpClientHandler clientHandler,
final SSLContext sslcontext,
final HttpParams params) {
return new SSLClientIOEventDispatch(clientHandler, sslcontext, params);
}
private void execute(final NHttpClientHandler clientHandler) throws IOException {
IOEventDispatch ioEventDispatch = createIOEventDispatch(
clientHandler,
this.sslcontext,
this.params);
this.ioReactor.execute(ioEventDispatch);
}
public SessionRequest openConnection(final InetSocketAddress address, final Object attachment) {
return this.ioReactor.connect(address, null, attachment, null);
}
public void start(final NHttpClientHandler clientHandler) {
this.thread = new IOReactorThread(clientHandler);
this.thread.start();
}
public void join(long timeout) throws InterruptedException {
if (this.thread != null) {
this.thread.join(timeout);
}
}
public Exception getException() {
if (this.thread != null) {
return this.thread.getException();
} else {
return null;
}
}
public void shutdown() throws IOException {
this.ioReactor.shutdown();
try {
if (this.thread != null) {
this.thread.join(500);
}
} catch (InterruptedException ignore) {
}
}
private class IOReactorThread extends Thread {
private final NHttpClientHandler clientHandler;
private volatile Exception ex;
public IOReactorThread(final NHttpClientHandler clientHandler) {
super();
this.clientHandler = clientHandler;
}
@Override
public void run() {
try {
execute(this.clientHandler);
} catch (Exception ex) {
this.ex = ex;
}
}
public Exception getException() {
return this.ex;
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/HttpSSLClient.java
|
Java
|
gpl3
| 5,949
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;
import org.apache.http.util.EncodingUtils;
public class ReadableByteChannelMockup implements ReadableByteChannel {
private final String[] chunks;
private final String charset;
private int chunkCount = 0;
private ByteBuffer currentChunk;
private boolean closed = false;
public ReadableByteChannelMockup(final String[] chunks, final String charset) {
super();
this.chunks = chunks;
this.charset = charset;
}
private void prepareChunk() {
if (this.currentChunk == null || !this.currentChunk.hasRemaining()) {
if (this.chunkCount < this.chunks.length) {
String s = this.chunks[this.chunkCount];
this.chunkCount++;
this.currentChunk = ByteBuffer.wrap(EncodingUtils.getBytes(s, this.charset));
} else {
this.closed = true;
}
}
}
public int read(final ByteBuffer dst) throws IOException {
prepareChunk();
if (this.closed) {
return -1;
}
int i = 0;
while (dst.hasRemaining() && this.currentChunk.hasRemaining()) {
dst.put(this.currentChunk.get());
i++;
}
return i;
}
public void close() throws IOException {
this.closed = true;
}
public boolean isOpen() {
return !this.closed;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/ReadableByteChannelMockup.java
|
Java
|
gpl3
| 2,713
|
/*
* ====================================================================
* 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.mockup;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.WritableByteChannel;
import org.apache.http.impl.io.HttpTransportMetricsImpl;
import org.apache.http.impl.nio.codecs.AbstractContentEncoder;
import org.apache.http.nio.reactor.SessionOutputBuffer;
public class MockupEncoder extends AbstractContentEncoder {
// TODO? remove this field and the complete() and isCompleted() methods
private boolean completed;
public MockupEncoder(
final WritableByteChannel channel,
final SessionOutputBuffer buffer,
final HttpTransportMetricsImpl metrics) {
super(channel, buffer, metrics);
}
@Override
public boolean isCompleted() {
return this.completed;
}
@Override
public void complete() throws IOException {
this.completed = true;
}
public int write(final ByteBuffer src) throws IOException {
if (src == null) {
return 0;
}
if (this.completed) {
throw new IllegalStateException("Decoding process already completed");
}
return this.channel.write(src);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/mockup/MockupEncoder.java
|
Java
|
gpl3
| 2,370
|
/*
* ====================================================================
* 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.nio.protocol;
import java.util.Random;
public class Job {
private static final Random RND = new Random();
private static final String TEST_CHARS = "0123456789ABCDEF";
private final int count;
private final String pattern;
private volatile boolean completed;
private volatile int statusCode;
private volatile String result;
private volatile String failureMessage;
private volatile Exception ex;
public Job(int maxCount) {
super();
this.count = RND.nextInt(maxCount - 1) + 1;
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < 5; i++) {
char rndchar = TEST_CHARS.charAt(RND.nextInt(TEST_CHARS.length() - 1));
buffer.append(rndchar);
}
this.pattern = buffer.toString();
}
public Job() {
this(1000);
}
public Job(final String pattern, int count) {
super();
this.count = count;
this.pattern = pattern;
}
public int getCount() {
return this.count;
}
public String getPattern() {
return this.pattern;
}
public String getExpected() {
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < this.count; i++) {
buffer.append(this.pattern);
}
return buffer.toString();
}
public int getStatusCode() {
return this.statusCode;
}
public String getResult() {
return this.result;
}
public boolean isSuccessful() {
return this.result != null;
}
public String getFailureMessage() {
return this.failureMessage;
}
public Exception getException() {
return this.ex;
}
public boolean isCompleted() {
return this.completed;
}
public synchronized void setResult(int statusCode, final String result) {
if (this.completed) {
return;
}
this.completed = true;
this.statusCode = statusCode;
this.result = result;
notifyAll();
}
public synchronized void fail(final String message, final Exception ex) {
if (this.completed) {
return;
}
this.completed = true;
this.result = null;
this.failureMessage = message;
this.ex = ex;
notifyAll();
}
public void fail(final String message) {
fail(message, null);
}
public synchronized void waitFor() throws InterruptedException {
while (!this.completed) {
wait();
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/nio/protocol/Job.java
|
Java
|
gpl3
| 3,767
|
/*
* ====================================================================
* 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.nio.protocol;
import java.io.IOException;
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.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.entity.NStringEntity;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.util.EntityUtils;
final class RequestHandler extends SimpleNHttpRequestHandler implements HttpRequestHandler {
private final boolean chunking;
RequestHandler() {
this(false);
}
RequestHandler(boolean chunking) {
super();
this.chunking = chunking;
}
public ConsumingNHttpEntity entityRequest(
final HttpEntityEnclosingRequest request,
final HttpContext context) {
return new BufferingNHttpEntity(
request.getEntity(),
new HeapByteBufferAllocator());
}
@Override
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String content = null;
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
if (entity != null) {
content = EntityUtils.toString(entity);
} else {
response.setStatusCode(HttpStatus.SC_BAD_REQUEST);
content = "Request entity not avaialble";
}
} else {
String s = request.getRequestLine().getUri();
int idx = s.indexOf('x');
if (idx == -1) {
throw new HttpException("Unexpected request-URI format");
}
String pattern = s.substring(0, idx);
int count = Integer.parseInt(s.substring(idx + 1, s.length()));
StringBuilder buffer = new StringBuilder();
for (int i = 0; i < count; i++) {
buffer.append(pattern);
}
content = buffer.toString();
}
NStringEntity entity = new NStringEntity(content, "US-ASCII");
entity.setChunked(this.chunking);
response.setEntity(entity);
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/nio/protocol/RequestHandler.java
|
Java
|
gpl3
| 3,738
|
/*
* ====================================================================
* 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.nio.protocol;
import java.io.IOException;
import java.util.Queue;
import org.apache.http.HttpEntity;
import org.apache.http.HttpRequest;
import org.apache.http.HttpResponse;
import org.apache.http.nio.entity.BufferingNHttpEntity;
import org.apache.http.nio.entity.ConsumingNHttpEntity;
import org.apache.http.nio.util.HeapByteBufferAllocator;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;
abstract class RequestExecutionHandler
implements NHttpRequestExecutionHandler, HttpRequestExecutionHandler {
public void initalizeContext(final HttpContext context, final Object attachment) {
context.setAttribute("queue", attachment);
}
protected abstract HttpRequest generateRequest(Job testjob);
public HttpRequest submitRequest(final HttpContext context) {
@SuppressWarnings("unchecked")
Queue<Job> queue = (Queue<Job>) context.getAttribute("queue");
if (queue == null) {
throw new IllegalStateException("Queue is null");
}
Job testjob = queue.poll();
context.setAttribute("job", testjob);
if (testjob != null) {
return generateRequest(testjob);
} else {
return null;
}
}
public ConsumingNHttpEntity responseEntity(
final HttpResponse response,
final HttpContext context) throws IOException {
return new BufferingNHttpEntity(response.getEntity(),
new HeapByteBufferAllocator());
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob == null) {
throw new IllegalStateException("TestJob is null");
}
int statusCode = response.getStatusLine().getStatusCode();
String content = null;
HttpEntity entity = response.getEntity();
if (entity != null) {
try {
content = EntityUtils.toString(entity);
} catch (IOException ex) {
content = "I/O exception: " + ex.getMessage();
}
}
testjob.setResult(statusCode, content);
}
public void finalizeContext(final HttpContext context) {
Job testjob = (Job) context.removeAttribute("job");
if (testjob != null) {
testjob.fail("Request failed");
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/nio/protocol/RequestExecutionHandler.java
|
Java
|
gpl3
| 3,634
|
/*
* ====================================================================
* 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;
import java.io.IOException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
class SimpleIOReactorExceptionHandler implements IOReactorExceptionHandler {
public boolean handle(final RuntimeException ex) {
if (!(ex instanceof OoopsieRuntimeException)) {
ex.printStackTrace(System.out);
}
return false;
}
public boolean handle(final IOException ex) {
ex.printStackTrace(System.out);
return false;
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/SimpleIOReactorExceptionHandler.java
|
Java
|
gpl3
| 1,695
|
/*
* ====================================================================
* 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;
import java.io.IOException;
import junit.framework.TestCase;
import org.apache.http.mockup.HttpSSLClient;
import org.apache.http.mockup.HttpSSLServer;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.SyncBasicHttpParams;
/**
* Base class for all HttpCore NIO tests
*/
public class HttpCoreNIOSSLTestBase extends TestCase {
public HttpCoreNIOSSLTestBase(String testName) {
super(testName);
}
protected HttpSSLServer server;
protected HttpSSLClient client;
@Override
protected void setUp() throws Exception {
HttpParams serverParams = new SyncBasicHttpParams();
serverParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.server = new HttpSSLServer(serverParams);
this.server.setExceptionHandler(new SimpleIOReactorExceptionHandler());
HttpParams clientParams = new SyncBasicHttpParams();
clientParams
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 120000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.client = new HttpSSLClient(clientParams);
this.client.setExceptionHandler(new SimpleIOReactorExceptionHandler());
}
@Override
protected void tearDown() {
try {
this.client.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
try {
this.server.shutdown();
} catch (IOException ex) {
ex.printStackTrace(System.out);
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/test/java/org/apache/http/HttpCoreNIOSSLTestBase.java
|
Java
|
gpl3
| 3,511
|
@import url("../../../css/hc-maven.css");
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/site/resources/css/site.css
|
CSS
|
gpl3
| 41
|
/*
* ====================================================================
* 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.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.nio.reactor.EventMask;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOSession;
import org.apache.http.nio.reactor.ListeningIOReactor;
import org.apache.http.params.HttpParams;
public class ElementalEchoServer {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
IOEventDispatch ioEventDispatch = new DefaultIoEventDispatch();
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
ioReactor.listen(new InetSocketAddress(8080));
try {
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class DefaultIoEventDispatch implements IOEventDispatch {
private final ByteBuffer buffer = ByteBuffer.allocate(1024);
public void connected(IOSession session) {
System.out.println("connected");
session.setEventMask(EventMask.READ);
session.setSocketTimeout(20000);
}
public void inputReady(final IOSession session) {
System.out.println("readable");
try {
this.buffer.compact();
int bytesRead = session.channel().read(this.buffer);
if (this.buffer.position() > 0) {
session.setEventMask(EventMask.READ_WRITE);
}
System.out.println("Bytes read: " + bytesRead);
if (bytesRead == -1) {
session.close();
}
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
}
public void outputReady(final IOSession session) {
System.out.println("writeable");
try {
this.buffer.flip();
int bytesWritten = session.channel().write(this.buffer);
if (!this.buffer.hasRemaining()) {
session.setEventMask(EventMask.READ);
}
System.out.println("Bytes written: " + bytesWritten);
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
}
public void timeout(final IOSession session) {
System.out.println("timeout");
session.close();
}
public void disconnected(final IOSession session) {
System.out.println("disconnected");
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/ElementalEchoServer.java
|
Java
|
gpl3
| 4,229
|
/*
* ====================================================================
* 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.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.nio.DefaultClientIOEventDispatch;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
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;
/**
* Elemental example for executing HTTP requests using the non-blocking I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*/
public class NHttpClient {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 10000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "HttpComponents/1.1");
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
// We are going to use this object to synchronize between the
// I/O event and main threads
CountDownLatch requestCount = new CountDownLatch(3);
BufferingHttpClientHandler handler = new BufferingHttpClientHandler(
httpproc,
new MyHttpRequestExecutionHandler(requestCount),
new DefaultConnectionReuseStrategy(),
params);
handler.setEventListener(new EventLogger());
final IOEventDispatch ioEventDispatch = new DefaultClientIOEventDispatch(handler, params);
Thread t = new Thread(new Runnable() {
public void run() {
try {
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
});
t.start();
SessionRequest[] reqs = new SessionRequest[3];
reqs[0] = ioReactor.connect(
new InetSocketAddress("www.yahoo.com", 80),
null,
new HttpHost("www.yahoo.com"),
new MySessionRequestCallback(requestCount));
reqs[1] = ioReactor.connect(
new InetSocketAddress("www.google.com", 80),
null,
new HttpHost("www.google.ch"),
new MySessionRequestCallback(requestCount));
reqs[2] = ioReactor.connect(
new InetSocketAddress("www.apache.org", 80),
null,
new HttpHost("www.apache.org"),
new MySessionRequestCallback(requestCount));
// Block until all connections signal
// completion of the request execution
requestCount.await();
System.out.println("Shutting down I/O reactor");
ioReactor.shutdown();
System.out.println("Done");
}
static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
private final static String REQUEST_SENT = "request-sent";
private final static String RESPONSE_RECEIVED = "response-received";
private final CountDownLatch requestCount;
public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void initalizeContext(final HttpContext context, final Object attachment) {
HttpHost targetHost = (HttpHost) attachment;
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
}
public void finalizeContext(final HttpContext context) {
Object flag = context.getAttribute(RESPONSE_RECEIVED);
if (flag == null) {
// Signal completion of the request execution
requestCount.countDown();
}
}
public HttpRequest submitRequest(final HttpContext context) {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Object flag = context.getAttribute(REQUEST_SENT);
if (flag == null) {
// Stick some object into the context
context.setAttribute(REQUEST_SENT, Boolean.TRUE);
System.out.println("--------------");
System.out.println("Sending request to " + targetHost);
System.out.println("--------------");
return new BasicHttpRequest("GET", "/");
} else {
// No new request to submit
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
HttpEntity entity = response.getEntity();
try {
String content = EntityUtils.toString(entity);
System.out.println("--------------");
System.out.println(response.getStatusLine());
System.out.println("--------------");
System.out.println("Document length: " + content.length());
System.out.println("--------------");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE);
// Signal completion of the request execution
requestCount.countDown();
}
}
static class MySessionRequestCallback implements SessionRequestCallback {
private final CountDownLatch requestCount;
public MySessionRequestCallback(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void cancelled(final SessionRequest request) {
System.out.println("Connect request cancelled: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void completed(final SessionRequest request) {
}
public void failed(final SessionRequest request) {
System.out.println("Connect request failed: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void timeout(final SessionRequest request) {
System.out.println("Connect request timed out: " + request.getRemoteAddress());
this.requestCount.countDown();
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpClient.java
|
Java
|
gpl3
| 10,951
|
/*
* ====================================================================
* 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.examples.nio;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetSocketAddress;
import java.util.concurrent.CountDownLatch;
import javax.net.ssl.SSLContext;
import org.apache.http.HttpEntity;
import org.apache.http.HttpException;
import org.apache.http.HttpHost;
import org.apache.http.HttpRequest;
import org.apache.http.HttpRequestInterceptor;
import org.apache.http.HttpResponse;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.nio.reactor.DefaultConnectingIOReactor;
import org.apache.http.impl.nio.ssl.SSLClientIOEventDispatch;
import org.apache.http.message.BasicHttpRequest;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.BufferingHttpClientHandler;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.HttpRequestExecutionHandler;
import org.apache.http.nio.reactor.ConnectingIOReactor;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.SessionRequest;
import org.apache.http.nio.reactor.SessionRequestCallback;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.params.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.ExecutionContext;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.ImmutableHttpProcessor;
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;
/**
* Elemental example for executing HTTPS requests using the non-blocking I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*/
public class NHttpSSLClient {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 30000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.USER_AGENT, "Jakarta-HttpComponents-NIO/1.1");
final ConnectingIOReactor ioReactor = new DefaultConnectingIOReactor(2, params);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
// Initialize default SSL context
SSLContext sslcontext = SSLContext.getInstance("SSL");
sslcontext.init(null, null, null);
// We are going to use this object to synchronize between the
// I/O event and main threads
CountDownLatch requestCount = new CountDownLatch(3);
BufferingHttpClientHandler handler = new BufferingHttpClientHandler(
httpproc,
new MyHttpRequestExecutionHandler(requestCount),
new DefaultConnectionReuseStrategy(),
params);
handler.setEventListener(new EventLogger());
final IOEventDispatch ioEventDispatch = new SSLClientIOEventDispatch(
handler,
sslcontext,
params);
Thread t = new Thread(new Runnable() {
public void run() {
try {
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
});
t.start();
SessionRequest[] reqs = new SessionRequest[3];
reqs[0] = ioReactor.connect(
new InetSocketAddress("www.netscape.com", 443),
null,
new HttpHost("www.netscape.com", 443),
new MySessionRequestCallback(requestCount));
reqs[1] = ioReactor.connect(
new InetSocketAddress("www.verisign.com", 443),
null,
new HttpHost("www.verisign.com", 443),
new MySessionRequestCallback(requestCount));
reqs[2] = ioReactor.connect(
new InetSocketAddress("www.yahoo.com", 443),
null,
new HttpHost("www.yahoo.com", 443),
new MySessionRequestCallback(requestCount));
// Block until all connections signal
// completion of the request execution
requestCount.await();
System.out.println("Shutting down I/O reactor");
ioReactor.shutdown();
System.out.println("Done");
}
static class MyHttpRequestExecutionHandler implements HttpRequestExecutionHandler {
private final static String REQUEST_SENT = "request-sent";
private final static String RESPONSE_RECEIVED = "response-received";
private final CountDownLatch requestCount;
public MyHttpRequestExecutionHandler(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void initalizeContext(final HttpContext context, final Object attachment) {
HttpHost targetHost = (HttpHost) attachment;
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
}
public void finalizeContext(final HttpContext context) {
Object flag = context.getAttribute(RESPONSE_RECEIVED);
if (flag == null) {
// Signal completion of the request execution
this.requestCount.countDown();
}
}
public HttpRequest submitRequest(final HttpContext context) {
HttpHost targetHost = (HttpHost) context.getAttribute(
ExecutionContext.HTTP_TARGET_HOST);
Object token = context.getAttribute(REQUEST_SENT);
if (token == null) {
// Stick some object into the context
context.setAttribute(REQUEST_SENT, Boolean.TRUE);
System.out.println("--------------");
System.out.println("Sending request to " + targetHost);
System.out.println("--------------");
return new BasicHttpRequest("GET", "/");
} else {
// No new request to submit
return null;
}
}
public void handleResponse(final HttpResponse response, final HttpContext context) {
HttpEntity entity = response.getEntity();
try {
String content = EntityUtils.toString(entity);
System.out.println("--------------");
System.out.println(response.getStatusLine());
System.out.println("--------------");
System.out.println("Document length: " + content.length());
System.out.println("--------------");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
}
context.setAttribute(RESPONSE_RECEIVED, Boolean.TRUE);
// Signal completion of the request execution
this.requestCount.countDown();
}
}
static class MySessionRequestCallback implements SessionRequestCallback {
private final CountDownLatch requestCount;
public MySessionRequestCallback(final CountDownLatch requestCount) {
super();
this.requestCount = requestCount;
}
public void cancelled(final SessionRequest request) {
System.out.println("Connect request cancelled: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void completed(final SessionRequest request) {
}
public void failed(final SessionRequest request) {
System.out.println("Connect request failed: " + request.getRemoteAddress());
this.requestCount.countDown();
}
public void timeout(final SessionRequest request) {
System.out.println("Connect request timed out: " + request.getRemoteAddress());
this.requestCount.countDown();
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpSSLClient.java
|
Java
|
gpl3
| 11,239
|
/*
* ====================================================================
* 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.examples.nio;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.InetSocketAddress;
import java.net.URL;
import java.net.URLDecoder;
import java.security.KeyStore;
import java.util.Locale;
import javax.net.ssl.KeyManager;
import javax.net.ssl.KeyManagerFactory;
import javax.net.ssl.SSLContext;
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.HttpResponseInterceptor;
import org.apache.http.HttpStatus;
import org.apache.http.MethodNotSupportedException;
import org.apache.http.entity.ContentProducer;
import org.apache.http.entity.EntityTemplate;
import org.apache.http.entity.FileEntity;
import org.apache.http.impl.DefaultConnectionReuseStrategy;
import org.apache.http.impl.DefaultHttpResponseFactory;
import org.apache.http.impl.nio.reactor.DefaultListeningIOReactor;
import org.apache.http.impl.nio.ssl.SSLServerIOEventDispatch;
import org.apache.http.nio.NHttpConnection;
import org.apache.http.nio.protocol.EventListener;
import org.apache.http.nio.protocol.BufferingHttpServiceHandler;
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.HttpParams;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.params.SyncBasicHttpParams;
import org.apache.http.protocol.HttpContext;
import org.apache.http.protocol.HttpProcessor;
import org.apache.http.protocol.HttpRequestHandler;
import org.apache.http.protocol.HttpRequestHandlerRegistry;
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.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTPS/1.1 server based on the non-blocking
* I/O model.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP server.
*
*
*/
public class NHttpSSLServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
ClassLoader cl = NHttpSSLServer.class.getClassLoader();
URL url = cl.getResource("test.keystore");
KeyStore keystore = KeyStore.getInstance("jks");
keystore.load(url.openStream(), "nopassword".toCharArray());
KeyManagerFactory kmfactory = KeyManagerFactory.getInstance(
KeyManagerFactory.getDefaultAlgorithm());
kmfactory.init(keystore, "nopassword".toCharArray());
KeyManager[] keymanagers = kmfactory.getKeyManagers();
SSLContext sslcontext = SSLContext.getInstance("TLS");
sslcontext.init(keymanagers, null, null);
HttpParams params = new SyncBasicHttpParams();
params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "Jakarta-HttpComponents-NIO/1.1");
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
BufferingHttpServiceHandler handler = new BufferingHttpServiceHandler(
httpproc,
new DefaultHttpResponseFactory(),
new DefaultConnectionReuseStrategy(),
params);
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(args[0]));
handler.setHandlerResolver(reqistry);
// Provide an event logger
handler.setEventListener(new EventLogger());
IOEventDispatch ioEventDispatch = new SSLServerIOEventDispatch(
handler,
sslcontext,
params);
ListeningIOReactor ioReactor = new DefaultListeningIOReactor(2, params);
try {
ioReactor.listen(new InetSocketAddress(8080));
ioReactor.execute(ioEventDispatch);
} catch (InterruptedIOException ex) {
System.err.println("Interrupted");
} catch (IOException e) {
System.err.println("I/O error: " + e.getMessage());
}
System.out.println("Shutdown");
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
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();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
String target = request.getRequestLine().getUri();
final File file = new File(this.docRoot, URLDecoder.decode(target, "UTF-8"));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class EventLogger implements EventListener {
public void connectionOpen(final NHttpConnection conn) {
System.out.println("Connection open: " + conn);
}
public void connectionTimeout(final NHttpConnection conn) {
System.out.println("Connection timed out: " + conn);
}
public void connectionClosed(final NHttpConnection conn) {
System.out.println("Connection closed: " + conn);
}
public void fatalIOException(final IOException ex, final NHttpConnection conn) {
System.err.println("I/O error: " + ex.getMessage());
}
public void fatalProtocolException(final HttpException ex, final NHttpConnection conn) {
System.err.println("HTTP error: " + ex.getMessage());
}
}
}
|
zzy157-running
|
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/examples/org/apache/http/examples/nio/NHttpSSLServer.java
|
Java
|
gpl3
| 10,698
|