code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.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");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import org.apache.ogt.http.io.EofSensor;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link SessionInputBuffer} implementation bound to a {@link Socket}.
* <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#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class SocketInputBuffer extends AbstractSessionInputBuffer implements EofSensor {
static private final Class SOCKET_TIMEOUT_CLASS = SocketTimeoutExceptionClass();
/**
* Returns <code>SocketTimeoutExceptionClass<code> or <code>null</code> if the class
* does not exist.
*
* @return <code>SocketTimeoutExceptionClass<code>, or <code>null</code> if unavailable.
*/
static private Class SocketTimeoutExceptionClass() {
try {
return Class.forName("java.net.SocketTimeoutException");
} catch (ClassNotFoundException e) {
return null;
}
}
private static boolean isSocketTimeoutException(final InterruptedIOException e) {
if (SOCKET_TIMEOUT_CLASS != null) {
return SOCKET_TIMEOUT_CLASS.isInstance(e);
} else {
return true;
}
}
private final Socket socket;
private boolean eof;
/**
* Creates an instance of this class.
*
* @param socket the socket to read data from.
* @param buffersize the size of the internal buffer. If this number is less
* than <code>0</code> it is set to the value of
* {@link Socket#getReceiveBufferSize()}. If resultant number is less
* than <code>1024</code> it is set to <code>1024</code>.
* @param params HTTP parameters.
*/
public SocketInputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
super();
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
this.socket = socket;
this.eof = false;
if (buffersize < 0) {
buffersize = socket.getReceiveBufferSize();
}
if (buffersize < 1024) {
buffersize = 1024;
}
init(socket.getInputStream(), buffersize, params);
}
protected int fillBuffer() throws IOException {
int i = super.fillBuffer();
this.eof = i == -1;
return i;
}
public boolean isDataAvailable(int timeout) throws IOException {
boolean result = hasBufferedData();
if (!result) {
int oldtimeout = this.socket.getSoTimeout();
try {
this.socket.setSoTimeout(timeout);
fillBuffer();
result = hasBufferedData();
} catch (InterruptedIOException e) {
if (!isSocketTimeoutException(e)) {
throw e;
}
} finally {
socket.setSoTimeout(oldtimeout);
}
}
return result;
}
public boolean isEof() {
return this.eof;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.util.Iterator;
import org.apache.ogt.http.Header;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.io.HttpMessageWriter;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.message.BasicLineFormatter;
import org.apache.ogt.http.message.LineFormatter;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract base class for HTTP message writers that serialize output to
* an instance of {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public abstract class AbstractMessageWriter implements HttpMessageWriter {
protected final SessionOutputBuffer sessionBuffer;
protected final CharArrayBuffer lineBuf;
protected final LineFormatter lineFormatter;
/**
* Creates an instance of AbstractMessageWriter.
*
* @param buffer the session output buffer.
* @param formatter the line formatter.
* @param params HTTP parameters.
*/
public AbstractMessageWriter(final SessionOutputBuffer buffer,
final LineFormatter formatter,
final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.sessionBuffer = buffer;
this.lineBuf = new CharArrayBuffer(128);
this.lineFormatter = (formatter != null) ?
formatter : BasicLineFormatter.DEFAULT;
}
/**
* Subclasses must override this method to write out the first header line
* based on the {@link HttpMessage} passed as a parameter.
*
* @param message the message whose first line is to be written out.
* @throws IOException in case of an I/O error.
*/
protected abstract void writeHeadLine(HttpMessage message) throws IOException;
public void write(
final HttpMessage message) throws IOException, HttpException {
if (message == null) {
throw new IllegalArgumentException("HTTP message may not be null");
}
writeHeadLine(message);
for (Iterator it = message.headerIterator(); it.hasNext(); ) {
Header header = (Header) it.next();
this.sessionBuffer.writeLine
(lineFormatter.formatHeader(this.lineBuf, header));
}
this.lineBuf.clear();
this.sessionBuffer.writeLine(this.lineBuf);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.NoHttpResponseException;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.StatusLine;
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 response 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 HttpResponseParser extends AbstractMessageParser {
private final HttpResponseFactory responseFactory;
private final CharArrayBuffer lineBuf;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param responseFactory the factory to use to create
* {@link HttpResponse}s.
* @param params HTTP parameters.
*/
public HttpResponseParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpResponseFactory responseFactory,
final HttpParams params) {
super(buffer, parser, params);
if (responseFactory == null) {
throw new IllegalArgumentException("Response factory may not be null");
}
this.responseFactory = responseFactory;
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 NoHttpResponseException("The target server failed to respond");
}
//create the status line from the status string
ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
StatusLine statusline = lineParser.parseStatusLine(this.lineBuf, cursor);
return this.responseFactory.newHttpResponse(statusline, null);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* Output stream that cuts off after a defined number of bytes. This class
* is used to send 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, the stream will be marked as closed and no further
* output will be permitted.
*
* @since 4.0
*/
public class ContentLengthOutputStream extends OutputStream {
/**
* Wrapped session output buffer.
*/
private final SessionOutputBuffer out;
/**
* The maximum number of bytes that can be written the stream. Subsequent
* write operations will be ignored.
*/
private final long contentLength;
/** Total bytes written */
private long total = 0;
/** True if the stream is closed. */
private boolean closed = false;
/**
* Wraps a session output buffer and cuts off output after a defined number
* of bytes.
*
* @param out The session output buffer
* @param contentLength The maximum number of bytes that can be written to
* the stream. Subsequent write operations will be ignored.
*
* @since 4.0
*/
public ContentLengthOutputStream(final SessionOutputBuffer out, long contentLength) {
super();
if (out == null) {
throw new IllegalArgumentException("Session output buffer may not be null");
}
if (contentLength < 0) {
throw new IllegalArgumentException("Content length may not be negative");
}
this.out = out;
this.contentLength = contentLength;
}
/**
* <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.");
}
if (this.total < this.contentLength) {
long max = this.contentLength - this.total;
if (len > max) {
len = (int) max;
}
this.out.write(b, off, len);
this.total += 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.");
}
if (this.total < this.contentLength) {
this.out.write(b);
this.total++;
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.net.Socket;
import org.apache.ogt.http.io.SessionOutputBuffer;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link SessionOutputBuffer} implementation bound to a {@link Socket}.
* <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>
* </ul>
*
* @since 4.0
*/
public class SocketOutputBuffer extends AbstractSessionOutputBuffer {
/**
* Creates an instance of this class.
*
* @param socket the socket to write data to.
* @param buffersize the size of the internal buffer. If this number is less
* than <code>0</code> it is set to the value of
* {@link Socket#getSendBufferSize()}. If resultant number is less
* than <code>1024</code> it is set to <code>1024</code>.
* @param params HTTP parameters.
*/
public SocketOutputBuffer(
final Socket socket,
int buffersize,
final HttpParams params) throws IOException {
super();
if (socket == null) {
throw new IllegalArgumentException("Socket may not be null");
}
if (buffersize < 0) {
buffersize = socket.getSendBufferSize();
}
if (buffersize < 1024) {
buffersize = 1024;
}
init(socket.getOutputStream(), buffersize, params);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.SessionInputBuffer;
/**
* Input stream that reads 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, it will read until the end of the stream (until
* <code>-1</code> is returned).
*
* @since 4.0
*/
public class IdentityInputStream extends InputStream {
private final SessionInputBuffer in;
private boolean closed = false;
/**
* Wraps session input stream and reads input until the the end of stream.
*
* @param in The session input buffer
*/
public IdentityInputStream(final SessionInputBuffer in) {
super();
if (in == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
this.in = in;
}
public int available() throws IOException {
if (this.in instanceof BufferInfo) {
return ((BufferInfo) this.in).length();
} else {
return 0;
}
}
public void close() throws IOException {
this.closed = true;
}
public int read() throws IOException {
if (this.closed) {
return -1;
} else {
return this.in.read();
}
}
public int read(final byte[] b, int off, int len) throws IOException {
if (this.closed) {
return -1;
} else {
return this.in.read(b, off, len);
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.SessionOutputBuffer;
/**
* Implements chunked transfer coding. The content is sent in small chunks.
* Entities transferred using this output stream can be of unlimited length.
* Writes are buffered to an internal buffer (2048 default size).
* <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 ChunkedOutputStream extends OutputStream {
// ----------------------------------------------------- Instance Variables
private final SessionOutputBuffer out;
private byte[] cache;
private int cachePosition = 0;
private boolean wroteLastChunk = false;
/** True if the stream is closed. */
private boolean closed = false;
// ----------------------------------------------------------- Constructors
/**
* Wraps a session output buffer and chunk-encodes the output.
*
* @param out The session output buffer
* @param bufferSize The minimum chunk size (excluding last chunk)
* @throws IOException in case of an I/O error
*/
public ChunkedOutputStream(final SessionOutputBuffer out, int bufferSize)
throws IOException {
super();
this.cache = new byte[bufferSize];
this.out = out;
}
/**
* Wraps a session output buffer and chunks the output. The default buffer
* size of 2048 was chosen because the chunk overhead is less than 0.5%
*
* @param out the output buffer to wrap
* @throws IOException in case of an I/O error
*/
public ChunkedOutputStream(final SessionOutputBuffer out)
throws IOException {
this(out, 2048);
}
// ----------------------------------------------------------- Internal methods
/**
* Writes the cache out onto the underlying stream
*/
protected void flushCache() throws IOException {
if (this.cachePosition > 0) {
this.out.writeLine(Integer.toHexString(this.cachePosition));
this.out.write(this.cache, 0, this.cachePosition);
this.out.writeLine("");
this.cachePosition = 0;
}
}
/**
* Writes the cache and bufferToAppend to the underlying stream
* as one large chunk
*/
protected void flushCacheWithAppend(byte bufferToAppend[], int off, int len) throws IOException {
this.out.writeLine(Integer.toHexString(this.cachePosition + len));
this.out.write(this.cache, 0, this.cachePosition);
this.out.write(bufferToAppend, off, len);
this.out.writeLine("");
this.cachePosition = 0;
}
protected void writeClosingChunk() throws IOException {
// Write the final chunk.
this.out.writeLine("0");
this.out.writeLine("");
}
// ----------------------------------------------------------- Public Methods
/**
* Must be called to ensure the internal cache is flushed and the closing
* chunk is written.
* @throws IOException in case of an I/O error
*/
public void finish() throws IOException {
if (!this.wroteLastChunk) {
flushCache();
writeClosingChunk();
this.wroteLastChunk = true;
}
}
// -------------------------------------------- OutputStream Methods
public void write(int b) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
this.cache[this.cachePosition] = (byte) b;
this.cachePosition++;
if (this.cachePosition == this.cache.length) flushCache();
}
/**
* Writes the array. If the array does not fit within the buffer, it is
* not split, but rather written out as one large chunk.
*/
public void write(byte b[]) throws IOException {
write(b, 0, b.length);
}
/**
* Writes the array. If the array does not fit within the buffer, it is
* not split, but rather written out as one large chunk.
*/
public void write(byte src[], int off, int len) throws IOException {
if (this.closed) {
throw new IOException("Attempted write to closed stream.");
}
if (len >= this.cache.length - this.cachePosition) {
flushCacheWithAppend(src, off, len);
} else {
System.arraycopy(src, off, cache, this.cachePosition, len);
this.cachePosition += len;
}
}
/**
* Flushes the content buffer and the underlying stream.
*/
public void flush() throws IOException {
flushCache();
this.out.flush();
}
/**
* Finishes writing to the underlying stream, but does NOT close the underlying stream.
*/
public void close() throws IOException {
if (!this.closed) {
this.closed = true;
finish();
this.out.flush();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.io.BufferInfo;
import org.apache.ogt.http.io.HttpTransportMetrics;
import org.apache.ogt.http.io.SessionInputBuffer;
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 input buffers that stream data from
* an arbitrary {@link InputStream}. This class buffers input data in
* an internal byte array for optimal input performance.
* <p>
* {@link #readLine(CharArrayBuffer)} and {@link #readLine()} methods of this
* class treat a lone LF as valid line delimiters in addition to CR-LF required
* by the HTTP specification.
*
* <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#MAX_LINE_LENGTH}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MIN_CHUNK_LIMIT}</li>
* </ul>
* @since 4.0
*/
public abstract class AbstractSessionInputBuffer implements SessionInputBuffer, BufferInfo {
private InputStream instream;
private byte[] buffer;
private int bufferpos;
private int bufferlen;
private ByteArrayBuffer linebuffer = null;
private String charset = HTTP.US_ASCII;
private boolean ascii = true;
private int maxLineLen = -1;
private int minChunkLimit = 512;
private HttpTransportMetricsImpl metrics;
/**
* Initializes this session input buffer.
*
* @param instream the source input stream.
* @param buffersize the size of the internal buffer.
* @param params HTTP parameters.
*/
protected void init(final InputStream instream, int buffersize, final HttpParams params) {
if (instream == 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.instream = instream;
this.buffer = new byte[buffersize];
this.bufferpos = 0;
this.bufferlen = 0;
this.linebuffer = new ByteArrayBuffer(buffersize);
this.charset = HttpProtocolParams.getHttpElementCharset(params);
this.ascii = this.charset.equalsIgnoreCase(HTTP.US_ASCII)
|| this.charset.equalsIgnoreCase(HTTP.ASCII);
this.maxLineLen = params.getIntParameter(CoreConnectionPNames.MAX_LINE_LENGTH, -1);
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.length;
}
/**
* @since 4.1
*/
public int length() {
return this.bufferlen - this.bufferpos;
}
/**
* @since 4.1
*/
public int available() {
return capacity() - length();
}
protected int fillBuffer() throws IOException {
// compact the buffer if necessary
if (this.bufferpos > 0) {
int len = this.bufferlen - this.bufferpos;
if (len > 0) {
System.arraycopy(this.buffer, this.bufferpos, this.buffer, 0, len);
}
this.bufferpos = 0;
this.bufferlen = len;
}
int l;
int off = this.bufferlen;
int len = this.buffer.length - off;
l = this.instream.read(this.buffer, off, len);
if (l == -1) {
return -1;
} else {
this.bufferlen = off + l;
this.metrics.incrementBytesTransferred(l);
return l;
}
}
protected boolean hasBufferedData() {
return this.bufferpos < this.bufferlen;
}
public int read() throws IOException {
int noRead = 0;
while (!hasBufferedData()) {
noRead = fillBuffer();
if (noRead == -1) {
return -1;
}
}
return this.buffer[this.bufferpos++] & 0xff;
}
public int read(final byte[] b, int off, int len) throws IOException {
if (b == null) {
return 0;
}
if (hasBufferedData()) {
int chunk = Math.min(len, this.bufferlen - this.bufferpos);
System.arraycopy(this.buffer, this.bufferpos, b, off, chunk);
this.bufferpos += chunk;
return chunk;
}
// If the remaining capacity is big enough, read directly from the
// underlying input stream bypassing the buffer.
if (len > this.minChunkLimit) {
int read = this.instream.read(b, off, len);
if (read > 0) {
this.metrics.incrementBytesTransferred(read);
}
return read;
} else {
// otherwise read to the buffer first
while (!hasBufferedData()) {
int noRead = fillBuffer();
if (noRead == -1) {
return -1;
}
}
int chunk = Math.min(len, this.bufferlen - this.bufferpos);
System.arraycopy(this.buffer, this.bufferpos, b, off, chunk);
this.bufferpos += chunk;
return chunk;
}
}
public int read(final byte[] b) throws IOException {
if (b == null) {
return 0;
}
return read(b, 0, b.length);
}
private int locateLF() {
for (int i = this.bufferpos; i < this.bufferlen; i++) {
if (this.buffer[i] == HTTP.LF) {
return i;
}
}
return -1;
}
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer into the given line buffer. The number of chars actually
* read is returned as an integer. The line delimiter itself is discarded.
* If no char is available because the end of the stream has been reached,
* the value <code>-1</code> is returned. This method blocks until input
* data is available, end of file is detected, or an exception is thrown.
* <p>
* This method treats a lone LF as a valid line delimiters in addition
* to CR-LF required by the HTTP specification.
*
* @param charbuffer the line buffer.
* @return one line of characters
* @exception IOException if an I/O error occurs.
*/
public int readLine(final CharArrayBuffer charbuffer) throws IOException {
if (charbuffer == null) {
throw new IllegalArgumentException("Char array buffer may not be null");
}
int noRead = 0;
boolean retry = true;
while (retry) {
// attempt to find end of line (LF)
int i = locateLF();
if (i != -1) {
// end of line found.
if (this.linebuffer.isEmpty()) {
// the entire line is preset in the read buffer
return lineFromReadBuffer(charbuffer, i);
}
retry = false;
int len = i + 1 - this.bufferpos;
this.linebuffer.append(this.buffer, this.bufferpos, len);
this.bufferpos = i + 1;
} else {
// end of line not found
if (hasBufferedData()) {
int len = this.bufferlen - this.bufferpos;
this.linebuffer.append(this.buffer, this.bufferpos, len);
this.bufferpos = this.bufferlen;
}
noRead = fillBuffer();
if (noRead == -1) {
retry = false;
}
}
if (this.maxLineLen > 0 && this.linebuffer.length() >= this.maxLineLen) {
throw new IOException("Maximum line length limit exceeded");
}
}
if (noRead == -1 && this.linebuffer.isEmpty()) {
// indicate the end of stream
return -1;
}
return lineFromLineBuffer(charbuffer);
}
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer. The line delimiter itself is discarded. If no char is
* available because the end of the stream has been reached,
* <code>null</code> is returned. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
* <p>
* This method treats a lone LF as a valid line delimiters in addition
* to CR-LF required by the HTTP specification.
*
* @return HTTP line as a string
* @exception IOException if an I/O error occurs.
*/
private int lineFromLineBuffer(final CharArrayBuffer charbuffer)
throws IOException {
// discard LF if found
int l = this.linebuffer.length();
if (l > 0) {
if (this.linebuffer.byteAt(l - 1) == HTTP.LF) {
l--;
this.linebuffer.setLength(l);
}
// discard CR if found
if (l > 0) {
if (this.linebuffer.byteAt(l - 1) == HTTP.CR) {
l--;
this.linebuffer.setLength(l);
}
}
}
l = this.linebuffer.length();
if (this.ascii) {
charbuffer.append(this.linebuffer, 0, l);
} else {
// This is VERY memory inefficient, BUT since non-ASCII charsets are
// NOT meant to be used anyway, there's no point optimizing it
String s = new String(this.linebuffer.buffer(), 0, l, this.charset);
l = s.length();
charbuffer.append(s);
}
this.linebuffer.clear();
return l;
}
private int lineFromReadBuffer(final CharArrayBuffer charbuffer, int pos)
throws IOException {
int off = this.bufferpos;
int len;
this.bufferpos = pos + 1;
if (pos > 0 && this.buffer[pos - 1] == HTTP.CR) {
// skip CR if found
pos--;
}
len = pos - off;
if (this.ascii) {
charbuffer.append(this.buffer, off, len);
} else {
// This is VERY memory inefficient, BUT since non-ASCII charsets are
// NOT meant to be used anyway, there's no point optimizing it
String s = new String(this.buffer, off, len, this.charset);
charbuffer.append(s);
len = s.length();
}
return len;
}
public String readLine() throws IOException {
CharArrayBuffer charbuffer = new CharArrayBuffer(64);
int l = readLine(charbuffer);
if (l != -1) {
return charbuffer.toString();
} else {
return null;
}
}
public HttpTransportMetrics getMetrics() {
return this.metrics;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.ogt.http.Header;
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.io.HttpMessageParser;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.message.BasicLineParser;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Abstract base class for HTTP message parsers that obtain 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 abstract class AbstractMessageParser implements HttpMessageParser {
private static final int HEAD_LINE = 0;
private static final int HEADERS = 1;
private final SessionInputBuffer sessionBuffer;
private final int maxHeaderCount;
private final int maxLineLen;
private final List headerLines;
protected final LineParser lineParser;
private int state;
private HttpMessage message;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param params HTTP parameters.
*/
public AbstractMessageParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpParams params) {
super();
if (buffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
this.sessionBuffer = buffer;
this.maxHeaderCount = params.getIntParameter(
CoreConnectionPNames.MAX_HEADER_COUNT, -1);
this.maxLineLen = params.getIntParameter(
CoreConnectionPNames.MAX_LINE_LENGTH, -1);
this.lineParser = (parser != null) ? parser : BasicLineParser.DEFAULT;
this.headerLines = new ArrayList();
this.state = HEAD_LINE;
}
/**
* Parses HTTP headers from the data receiver stream according to the generic
* format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3.
*
* @param inbuffer Session input buffer
* @param maxHeaderCount maximum number of headers allowed. If the number
* of headers received from the data stream exceeds maxCount value, an
* IOException will be thrown. Setting this parameter to a negative value
* or zero will disable the check.
* @param maxLineLen maximum number of characters for a header line,
* including the continuation lines. Setting this parameter to a negative
* value or zero will disable the check.
* @return array of HTTP headers
* @param parser line parser to use. Can be <code>null</code>, in which case
* the default implementation of this interface will be used.
*
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
public static Header[] parseHeaders(
final SessionInputBuffer inbuffer,
int maxHeaderCount,
int maxLineLen,
LineParser parser)
throws HttpException, IOException {
if (parser == null) {
parser = BasicLineParser.DEFAULT;
}
List headerLines = new ArrayList();
return parseHeaders(inbuffer, maxHeaderCount, maxLineLen, parser, headerLines);
}
/**
* Parses HTTP headers from the data receiver stream according to the generic
* format as given in Section 3.1 of RFC 822, RFC-2616 Section 4 and 19.3.
*
* @param inbuffer Session input buffer
* @param maxHeaderCount maximum number of headers allowed. If the number
* of headers received from the data stream exceeds maxCount value, an
* IOException will be thrown. Setting this parameter to a negative value
* or zero will disable the check.
* @param maxLineLen maximum number of characters for a header line,
* including the continuation lines. Setting this parameter to a negative
* value or zero will disable the check.
* @param parser line parser to use.
* @param headerLines List of header lines. This list will be used to store
* intermediate results. This makes it possible to resume parsing of
* headers in case of a {@link java.io.InterruptedIOException}.
*
* @return array of HTTP headers
*
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*
* @since 4.1
*/
public static Header[] parseHeaders(
final SessionInputBuffer inbuffer,
int maxHeaderCount,
int maxLineLen,
final LineParser parser,
final List headerLines)
throws HttpException, IOException {
if (inbuffer == null) {
throw new IllegalArgumentException("Session input buffer may not be null");
}
if (parser == null) {
throw new IllegalArgumentException("Line parser may not be null");
}
if (headerLines == null) {
throw new IllegalArgumentException("Header line list may not be null");
}
CharArrayBuffer current = null;
CharArrayBuffer previous = null;
for (;;) {
if (current == null) {
current = new CharArrayBuffer(64);
} else {
current.clear();
}
int l = inbuffer.readLine(current);
if (l == -1 || current.length() < 1) {
break;
}
// Parse the header name and value
// Check for folded headers first
// Detect LWS-char see HTTP/1.0 or HTTP/1.1 Section 2.2
// discussion on folded headers
if ((current.charAt(0) == ' ' || current.charAt(0) == '\t') && previous != null) {
// we have continuation folded header
// so append value
int i = 0;
while (i < current.length()) {
char ch = current.charAt(i);
if (ch != ' ' && ch != '\t') {
break;
}
i++;
}
if (maxLineLen > 0
&& previous.length() + 1 + current.length() - i > maxLineLen) {
throw new IOException("Maximum line length limit exceeded");
}
previous.append(' ');
previous.append(current, i, current.length() - i);
} else {
headerLines.add(current);
previous = current;
current = null;
}
if (maxHeaderCount > 0 && headerLines.size() >= maxHeaderCount) {
throw new IOException("Maximum header count exceeded");
}
}
Header[] headers = new Header[headerLines.size()];
for (int i = 0; i < headerLines.size(); i++) {
CharArrayBuffer buffer = (CharArrayBuffer) headerLines.get(i);
try {
headers[i] = parser.parseHeader(buffer);
} catch (ParseException ex) {
throw new ProtocolException(ex.getMessage());
}
}
return headers;
}
/**
* Subclasses must override this method to generate an instance of
* {@link HttpMessage} based on the initial input from the session buffer.
* <p>
* Usually this method is expected to read just the very first line or
* the very first valid from the data stream and based on the input generate
* an appropriate instance of {@link HttpMessage}.
*
* @param sessionBuffer the session input buffer.
* @return HTTP message based on the input from the session buffer.
* @throws IOException in case of an I/O error.
* @throws HttpException in case of HTTP protocol violation.
* @throws ParseException in case of a parse error.
*/
protected abstract HttpMessage parseHead(SessionInputBuffer sessionBuffer)
throws IOException, HttpException, ParseException;
public HttpMessage parse() throws IOException, HttpException {
int st = this.state;
switch (st) {
case HEAD_LINE:
try {
this.message = parseHead(this.sessionBuffer);
} catch (ParseException px) {
throw new ProtocolException(px.getMessage(), px);
}
this.state = HEADERS;
//$FALL-THROUGH$
case HEADERS:
Header[] headers = AbstractMessageParser.parseHeaders(
this.sessionBuffer,
this.maxHeaderCount,
this.maxLineLen,
this.lineParser,
this.headerLines);
this.message.setHeaders(headers);
HttpMessage result = this.message;
this.message = null;
this.headerLines.clear();
this.state = HEAD_LINE;
return result;
default:
throw new IllegalStateException("Inconsistent parser state");
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl;
import java.io.IOException;
import java.net.Socket;
import org.apache.ogt.http.params.HttpConnectionParams;
import org.apache.ogt.http.params.HttpParams;
/**
* Default implementation of a client-side HTTP connection.
* <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#TCP_NODELAY}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</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>
* </ul>
*
* @since 4.0
*/
public class DefaultHttpClientConnection extends SocketHttpClientConnection {
public DefaultHttpClientConnection() {
super();
}
public 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");
}
assertNotOpen();
socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params));
socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params));
int linger = HttpConnectionParams.getLinger(params);
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
super.bind(socket, params);
}
public String toString() {
StringBuffer buffer = new StringBuffer();
buffer.append("[");
if (isOpen()) {
buffer.append(getRemotePort());
} else {
buffer.append("closed");
}
buffer.append("]");
return buffer.toString();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* Signals that an HTTP method is not supported.
*
* @since 4.0
*/
public class MethodNotSupportedException extends HttpException {
private static final long serialVersionUID = 3365359036840171201L;
/**
* Creates a new MethodNotSupportedException with the specified detail message.
*
* @param message The exception detail message
*/
public MethodNotSupportedException(final String message) {
super(message);
}
/**
* Creates a new MethodNotSupportedException 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 MethodNotSupportedException(final String message, final Throwable cause) {
super(message, cause);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.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();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
/**
* Signals 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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
/**
* A 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;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* Signals 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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* The first line of a Response message is the Status-Line, consisting
* of the protocol version followed by a numeric status code and its
* associated textual phrase, with each element separated by SP
* characters. No CR or LF is allowed except in the final CRLF sequence.
* <pre>
* Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF
* </pre>
*
* @see HttpStatus
* @version $Id: StatusLine.java 937295 2010-04-23 13:44:00Z olegk $
*
* @since 4.0
*/
public interface StatusLine {
ProtocolVersion getProtocolVersion();
int getStatusCode();
String getReasonPhrase();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.util.Locale;
/**
* 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);
}
| Java |
/*
* $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();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* A 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();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import org.apache.ogt.http.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);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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;
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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() {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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() {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* The 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();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import org.apache.ogt.http.protocol.HttpContext;
/**
* 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);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Session output buffer for blocking connections. This interface is similar to
* OutputStream class, but it also provides methods for writing lines of text.
* <p>
* Implementing classes are also expected to manage intermediate data buffering
* for optimal output performance.
*
* @since 4.0
*/
public interface SessionOutputBuffer {
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this session buffer.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b, int off, int len) throws IOException;
/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this session buffer.
*
* @param b the data.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b) throws IOException;
/**
* Writes the specified byte to this session buffer.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
void write(int b) throws IOException;
/**
* Writes characters from the specified string followed by a line delimiter
* to this session buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param s the line.
* @exception IOException if an I/O error occurs.
*/
void writeLine(String s) throws IOException;
/**
* Writes characters from the specified char array followed by a line
* delimiter to this session buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param buffer the buffer containing chars of the line.
* @exception IOException if an I/O error occurs.
*/
void writeLine(CharArrayBuffer buffer) throws IOException;
/**
* Flushes this session buffer and forces any buffered output bytes
* to be written out. The general contract of <code>flush</code> is
* that calling it is an indication that, if any bytes previously
* written have been buffered by the implementation of the output
* stream, such bytes should immediately be written to their
* intended destination.
*
* @exception IOException if an I/O error occurs.
*/
void flush() throws IOException;
/**
* Returns {@link HttpTransportMetrics} for this session buffer.
*
* @return transport metrics.
*/
HttpTransportMetrics getMetrics();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
/**
* Abstract message parser intended to build HTTP messages from an arbitrary
* data source.
*
* @since 4.0
*/
public interface HttpMessageParser {
/**
* Generates an instance of {@link HttpMessage} from the underlying data
* source.
*
* @return HTTP message
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
HttpMessage parse()
throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* EOF sensor.
*
* @since 4.0
*/
public interface EofSensor {
boolean isEof();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
/**
* Abstract message writer intended to serialize HTTP messages to an arbitrary
* data sink.
*
* @since 4.0
*/
public interface HttpMessageWriter {
/**
* Serializes an instance of {@link HttpMessage} to the underlying data
* sink.
*
* @param message
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
void write(HttpMessage message)
throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* The point of access to the statistics of {@link SessionInputBuffer} or
* {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public interface HttpTransportMetrics {
/**
* Returns the number of bytes transferred.
*/
long getBytesTransferred();
/**
* Resets the counts
*/
void reset();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Session input buffer for blocking connections. This interface is similar to
* InputStream class, but it also provides methods for reading lines of text.
* <p>
* Implementing classes are also expected to manage intermediate data buffering
* for optimal input performance.
*
* @since 4.0
*/
public interface SessionInputBuffer {
/**
* Reads up to <code>len</code> bytes of data from the session buffer into
* an array of bytes. An attempt is made to read as many as
* <code>len</code> bytes, but a smaller number may be read, possibly
* zero. The number of bytes actually read is returned as an integer.
*
* <p> This method blocks until input data is available, end of file is
* detected, or an exception is thrown.
*
* <p> If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <code>IndexOutOfBoundsException</code> is
* thrown.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Reads some number of bytes from the session buffer and stores them into
* the buffer array <code>b</code>. The number of bytes actually read is
* returned as an integer. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> is there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b) throws IOException;
/**
* Reads the next byte of data from this session buffer. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
*/
int read() throws IOException;
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer into the given line buffer. The number of chars actually
* read is returned as an integer. The line delimiter itself is discarded.
* If no char is available because the end of the stream has been reached,
* the value <code>-1</code> is returned. This method blocks until input
* data is available, end of file is detected, or an exception is thrown.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param buffer the line buffer.
* @return one line of characters
* @exception IOException if an I/O error occurs.
*/
int readLine(CharArrayBuffer buffer) throws IOException;
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer. The line delimiter itself is discarded. If no char is
* available because the end of the stream has been reached,
* <code>null</code> is returned. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @return HTTP line as a string
* @exception IOException if an I/O error occurs.
*/
String readLine() throws IOException;
/** Blocks until some data becomes available in the session buffer or the
* given timeout period in milliseconds elapses. If the timeout value is
* <code>0</code> this method blocks indefinitely.
*
* @param timeout in milliseconds.
* @return <code>true</code> if some data is available in the session
* buffer or <code>false</code> otherwise.
* @exception IOException if an I/O error occurs.
*/
boolean isDataAvailable(int timeout) throws IOException;
/**
* Returns {@link HttpTransportMetrics} for this session buffer.
*
* @return transport metrics.
*/
HttpTransportMetrics getMetrics();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* Basic buffer properties.
*
* @since 4.1
*/
public interface BufferInfo {
/**
* Return length data stored in the buffer
*
* @return data length
*/
int length();
/**
* Returns total capacity of the buffer
*
* @return total capacity
*/
int capacity();
/**
* Returns available space in the buffer.
*
* @return available space.
*/
int available();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
import org.apache.ogt.http.protocol.HttpContext;
/**
* HTTP protocol interceptor is a routine that implements a specific aspect of
* the HTTP protocol. Usually protocol interceptors are expected to act upon
* one specific header or a group of related headers of the incoming message
* or populate the outgoing message with one specific header or a group of
* related headers.
* <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;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.Serializable;
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();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* 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);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.ogt.http.ConnectionClosedException;
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.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.ContentProducer;
import org.apache.ogt.http.entity.EntityTemplate;
import org.apache.ogt.http.entity.FileEntity;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
import org.apache.ogt.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
* <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 file server.
*
*
*/
public class ElementalHttpServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
Thread t = new RequestListenerThread(8080, args[0]);
t.setDaemon(false);
t.start();
}
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");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
final File file = new File(this.docRoot, URLDecoder.decode(target));
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 RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final String docroot) throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.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, "HttpComponents/1.1");
// Set up the HTTP protocol processor
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(docroot));
// Set up the HTTP service
this.httpService = new HttpService(
httpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + socket.getInetAddress());
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.ByteArrayInputStream;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.entity.InputStreamEntity;
import org.apache.ogt.http.entity.StringEntity;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a POST request.
* <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 ElementalHttpPost {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
/**
* Rudimentary HTTP/1.1 reverse proxy.
* <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 reverse proxy.
*
*
*/
public class ElementalReverseProxy {
private static final String HTTP_IN_CONN = "http.proxy.in-conn";
private static final String HTTP_OUT_CONN = "http.proxy.out-conn";
private static final String HTTP_CONN_KEEPALIVE = "http.proxy.conn-keepalive";
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specified target hostname and port");
System.exit(1);
}
String hostname = args[0];
int port = 80;
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
HttpHost target = new HttpHost(hostname, port);
Thread t = new RequestListenerThread(8888, target);
t.setDaemon(false);
t.start();
}
static class ProxyHandler implements HttpRequestHandler {
private final HttpHost target;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
public ProxyHandler(
final HttpHost target,
final HttpProcessor httpproc,
final HttpRequestExecutor httpexecutor) {
super();
this.target = target;
this.httpproc = httpproc;
this.httpexecutor = httpexecutor;
this.connStrategy = new DefaultConnectionReuseStrategy();
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpClientConnection conn = (HttpClientConnection) context.getAttribute(
HTTP_OUT_CONN);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.target);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
// Remove hop-by-hop headers
request.removeHeaders(HTTP.CONTENT_LEN);
request.removeHeaders(HTTP.TRANSFER_ENCODING);
request.removeHeaders(HTTP.CONN_DIRECTIVE);
request.removeHeaders("Keep-Alive");
request.removeHeaders("Proxy-Authenticate");
request.removeHeaders("TE");
request.removeHeaders("Trailers");
request.removeHeaders("Upgrade");
this.httpexecutor.preProcess(request, this.httpproc, context);
HttpResponse targetResponse = this.httpexecutor.execute(request, conn, context);
this.httpexecutor.postProcess(response, this.httpproc, context);
// Remove hop-by-hop headers
targetResponse.removeHeaders(HTTP.CONTENT_LEN);
targetResponse.removeHeaders(HTTP.TRANSFER_ENCODING);
targetResponse.removeHeaders(HTTP.CONN_DIRECTIVE);
targetResponse.removeHeaders("Keep-Alive");
targetResponse.removeHeaders("TE");
targetResponse.removeHeaders("Trailers");
targetResponse.removeHeaders("Upgrade");
response.setStatusLine(targetResponse.getStatusLine());
response.setHeaders(targetResponse.getAllHeaders());
response.setEntity(targetResponse.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
boolean keepalive = this.connStrategy.keepAlive(response, context);
context.setAttribute(HTTP_CONN_KEEPALIVE, new Boolean(keepalive));
}
}
static class RequestListenerThread extends Thread {
private final HttpHost target;
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final HttpHost target) throws IOException {
this.target = target;
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.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, "HttpComponents/1.1");
// Set up HTTP protocol processor for incoming connections
HttpProcessor inhttpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
// Set up HTTP protocol processor for outgoing connections
HttpProcessor outhttpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up outgoing request executor
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
// Set up incoming request handler
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new ProxyHandler(
this.target,
outhttpproc,
httpexecutor));
// Set up the HTTP service
this.httpService = new HttpService(
inhttpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up incoming HTTP connection
Socket insocket = this.serversocket.accept();
DefaultHttpServerConnection inconn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + insocket.getInetAddress());
inconn.bind(insocket, this.params);
// Set up outgoing HTTP connection
Socket outsocket = new Socket(this.target.getHostName(), this.target.getPort());
DefaultHttpClientConnection outconn = new DefaultHttpClientConnection();
outconn.bind(outsocket, this.params);
System.out.println("Outgoing connection to " + outsocket.getInetAddress());
// Start worker thread
Thread t = new ProxyThread(this.httpService, inconn, outconn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class ProxyThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection inconn;
private final HttpClientConnection outconn;
public ProxyThread(
final HttpService httpservice,
final HttpServerConnection inconn,
final HttpClientConnection outconn) {
super();
this.httpservice = httpservice;
this.inconn = inconn;
this.outconn = outconn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
// Bind connection objects to the execution context
context.setAttribute(HTTP_IN_CONN, this.inconn);
context.setAttribute(HTTP_OUT_CONN, this.outconn);
try {
while (!Thread.interrupted()) {
if (!this.inconn.isOpen()) {
this.outconn.close();
break;
}
this.httpservice.handleRequest(this.inconn, context);
Boolean keepalive = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE);
if (!Boolean.TRUE.equals(keepalive)) {
this.outconn.close();
this.inconn.close();
break;
}
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.inconn.shutdown();
} catch (IOException ignore) {}
try {
this.outconn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a GET request.
* <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 ElementalHttpGet {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
String[] targets = {
"/",
"/servlets-examples/servlet/RequestInfoExample",
"/somewhere%20in%20pampa"};
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import org.apache.ogt.http.util.VersionInfo;
/**
* Prints version information for debugging purposes.
* This can be used to verify that the correct versions of the
* HttpComponent JARs are picked up from the classpath.
*
*
*/
public class PrintVersionInfo {
/** A default list of module packages. */
private final static String[] MODULE_LIST = {
"org.apache.ogt.http", // HttpCore
"org.apache.ogt.http.nio", // HttpCore NIO
"org.apache.ogt.http.client", // HttpClient
};
/**
* Prints version information.
*
* @param args command line arguments. Leave empty to print version
* information for the default packages. Otherwise, pass
* a list of packages for which to get version info.
*/
public static void main(String args[]) {
String[] pckgs = (args.length > 0) ? args : MODULE_LIST;
VersionInfo[] via = VersionInfo.loadVersionInfo(pckgs, null);
System.out.println("version info for thread context classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
System.out.println();
// if the version information for the classloader of this class
// is different from that for the thread context classloader,
// there may be a problem with multiple versions in the classpath
via = VersionInfo.loadVersionInfo
(pckgs, PrintVersionInfo.class.getClassLoader());
System.out.println("version info for static classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.message.AbstractHttpMessage;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* {@link org.apache.ogt.http.HttpMessage} mockup implementation.
*
*/
public class HttpMessageMockup extends AbstractHttpMessage {
public HttpMessageMockup() {
super();
}
public ProtocolVersion getProtocolVersion() {
return HttpProtocolParams.getVersion(this.getParams());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.apache.ogt.http.impl.io.AbstractSessionOutputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionOutputBuffer} mockup implementation.
*
*/
public class SessionOutputBufferMockup extends AbstractSessionOutputBuffer {
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public static final int BUFFER_SIZE = 16;
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize,
final HttpParams params) {
super();
init(outstream, buffersize, params);
}
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize) {
this(outstream, buffersize, new BasicHttpParams());
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer,
final HttpParams params) {
this(buffer, BUFFER_SIZE, params);
this.buffer = buffer;
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer) {
this(buffer, BUFFER_SIZE, new BasicHttpParams());
this.buffer = buffer;
}
public SessionOutputBufferMockup(final HttpParams params) {
this(new ByteArrayOutputStream(), params);
}
public SessionOutputBufferMockup() {
this(new ByteArrayOutputStream(), new BasicHttpParams());
}
public byte[] getData() {
if (this.buffer != null) {
return this.buffer.toByteArray();
} else {
return new byte[] {};
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.impl.io.AbstractSessionInputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionInputBuffer} mockup implementation.
*/
public class SessionInputBufferMockup extends AbstractSessionInputBuffer {
public static final int BUFFER_SIZE = 16;
public SessionInputBufferMockup(
final InputStream instream,
int buffersize,
final HttpParams params) {
super();
init(instream, buffersize, params);
}
public SessionInputBufferMockup(
final InputStream instream,
int buffersize) {
this(instream, buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
final HttpParams params) {
this(bytes, BUFFER_SIZE, params);
}
public SessionInputBufferMockup(
final byte[] bytes) {
this(bytes, BUFFER_SIZE, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize,
final HttpParams params) {
this(new ByteArrayInputStream(bytes), buffersize, params);
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize) {
this(new ByteArrayInputStream(bytes), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, params);
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), params);
}
public SessionInputBufferMockup(
final String s,
final String charset)
throws UnsupportedEncodingException {
this(s.getBytes(charset), new BasicHttpParams());
}
public boolean isDataAvailable(int timeout) throws IOException {
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
/**
* Test class similar to {@link java.io.ByteArrayInputStream} that throws if encounters
* value zero '\000' in the source byte array.
*/
public class TimeoutByteArrayInputStream extends InputStream {
private final byte[] buf;
private int pos;
protected int count;
public TimeoutByteArrayInputStream(byte[] buf, int off, int len) {
super();
this.buf = buf;
this.pos = off;
this.count = Math.min(off + len, buf.length);
}
public TimeoutByteArrayInputStream(byte[] buf) {
this(buf, 0, buf.length);
}
public int read() throws IOException {
if (this.pos < this.count) {
return -1;
}
int v = this.buf[this.pos++] & 0xff;
if (v != 0) {
return v;
} else {
throw new InterruptedIOException("Timeout");
}
}
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (this.pos >= this.count) {
return -1;
}
if (this.pos + len > this.count) {
len = this.count - this.pos;
}
if (len <= 0) {
return 0;
}
if ((this.buf[this.pos] & 0xff) == 0) {
this.pos++;
throw new InterruptedIOException("Timeout");
}
for (int i = 0; i < len; i++) {
int v = this.buf[this.pos] & 0xff;
if (v == 0) {
return i;
} else {
b[off + i] = (byte) v;
this.pos++;
}
}
return len;
}
public long skip(long n) {
if (this.pos + n > this.count) {
n = this.count - this.pos;
}
if (n < 0) {
return 0;
}
this.pos += n;
return n;
}
public int available() {
return this.count - this.pos;
}
public boolean markSupported() {
return false;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpConnectionMetrics;
/**
* {@link HttpConnection} mockup implementation.
*
*/
public class HttpConnectionMockup implements HttpConnection {
private boolean open = true;
public HttpConnectionMockup() {
super();
}
public void close() throws IOException {
this.open = false;
}
public void shutdown() throws IOException {
this.open = false;
}
public void setSocketTimeout(int timeout) {
}
public int getSocketTimeout() {
return -1;
}
public boolean isOpen() {
return this.open;
}
public boolean isStale() {
return false;
}
public HttpConnectionMetrics getMetrics() {
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.DefaultedHttpParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
public class HttpClient {
private final HttpParams params;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
private final HttpContext context;
public HttpClient() {
super();
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
this.httpexecutor = new HttpRequestExecutor();
this.connStrategy = new DefaultConnectionReuseStrategy();
this.context = new BasicHttpContext();
}
public HttpParams getParams() {
return this.params;
}
public HttpResponse execute(
final HttpRequest request,
final HttpHost targetHost,
final HttpClientConnection conn) throws HttpException, IOException {
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
this.httpexecutor.preProcess(request, this.httpproc, this.context);
HttpResponse response = this.httpexecutor.execute(request, conn, this.context);
response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
this.httpexecutor.postProcess(response, this.httpproc, this.context);
return response;
}
public boolean keepAlive(final HttpResponse response) {
return this.connStrategy.keepAlive(response, this.context);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.AbstractHttpEntity;
/**
* {@link AbstractHttpEntity} mockup implementation.
*
*/
public class HttpEntityMockup extends AbstractHttpEntity {
private boolean stream;
public InputStream getContent() throws IOException, IllegalStateException {
return null;
}
public long getContentLength() {
return 0;
}
public boolean isRepeatable() {
return false;
}
public void setStreaming(final boolean b) {
this.stream = b;
}
public boolean isStreaming() {
return this.stream;
}
public void writeTo(OutputStream outstream) throws IOException {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpExpectationVerifier;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
public class HttpServer {
private final HttpParams params;
private final HttpProcessor httpproc;
private final ConnectionReuseStrategy connStrategy;
private final HttpResponseFactory responseFactory;
private final HttpRequestHandlerRegistry reqistry;
private final ServerSocket serversocket;
private HttpExpectationVerifier expectationVerifier;
private Thread listener;
private volatile boolean shutdown;
public HttpServer() throws IOException {
super();
this.params = new SyncBasicHttpParams();
this.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, "TEST-SERVER/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
this.connStrategy = new DefaultConnectionReuseStrategy();
this.responseFactory = new DefaultHttpResponseFactory();
this.reqistry = new HttpRequestHandlerRegistry();
this.serversocket = new ServerSocket(0);
}
public void registerHandler(
final String pattern,
final HttpRequestHandler handler) {
this.reqistry.register(pattern, handler);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
private HttpServerConnection acceptConnection() throws IOException {
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, this.params);
return conn;
}
public int getPort() {
return this.serversocket.getLocalPort();
}
public InetAddress getInetAddress() {
return this.serversocket.getInetAddress();
}
public void start() {
if (this.listener != null) {
throw new IllegalStateException("Listener already running");
}
this.listener = new Thread(new Runnable() {
public void run() {
while (!shutdown && !Thread.interrupted()) {
try {
// Set up HTTP connection
HttpServerConnection conn = acceptConnection();
// Set up the HTTP service
HttpService httpService = new HttpService(
httpproc,
connStrategy,
responseFactory,
reqistry,
expectationVerifier,
params);
// Start worker thread
Thread t = new WorkerThread(httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
break;
}
}
}
});
this.listener.start();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
try {
this.serversocket.close();
} catch (IOException ignore) {}
this.listener.interrupt();
try {
this.listener.join(1000);
} catch (InterruptedException ignore) {}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
/**
* Translates SimplePosition objects to a telnet command and sends the commands to a telnet session with an android emulator.
*
* @version $Id$
* @author Bram Pouwelse (c) Jan 22, 2009, Sogeti B.V.
*
*/
public class TelnetPositionSender
{
private static final String TAG = "TelnetPositionSender";
private static final String TELNET_OK_FEEDBACK_MESSAGE = "OK\r\n";
private static String HOST = "10.0.2.2";
private static int PORT = 5554;
private Socket socket;
private OutputStream out;
private InputStream in;
/**
* Constructor
*/
public TelnetPositionSender()
{
}
/**
* Setup a telnet connection to the android emulator
*/
private void createTelnetConnection() {
try {
this.socket = new Socket(HOST, PORT);
this.in = this.socket.getInputStream();
this.out = this.socket.getOutputStream();
Thread.sleep(500); // give the telnet session half a second to
// respond
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
readInput(); // read the input to throw it away the first time :)
}
private void closeConnection()
{
try
{
this.out.close();
this.in.close();
this.socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* read the input buffer
* @return
*/
private String readInput() {
StringBuffer sb = new StringBuffer();
try {
byte[] bytes = new byte[this.in.available()];
this.in.read(bytes);
for (byte b : bytes) {
sb.append((char) b);
}
} catch (Exception e) {
System.err.println("Warning: Could not read the input from the telnet session");
}
return sb.toString();
}
/**
* When a new position is received it is sent to the android emulator over the telnet connection.
*
* @param position the position to send
*/
public void sendCommand(String telnetString)
{
createTelnetConnection();
Log.v( TAG, "Sending command: "+telnetString);
byte[] sendArray = telnetString.getBytes();
for (byte b : sendArray)
{
try
{
this.out.write(b);
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
String feedback = readInput();
if (!feedback.equals(TELNET_OK_FEEDBACK_MESSAGE))
{
System.err.println("Warning: no OK mesage message was(" + feedback + ")");
}
closeConnection();
}
} | Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
/**
* Feeder of GPS-location information
*
* @version $Id$
* @author Maarten van Berkel (maarten.van.berkel@sogeti.nl / +0586)
*/
public class MockGPSLoggerDriver implements Runnable
{
private static final String TAG = "MockGPSLoggerDriver";
private boolean running = true;
private int mTimeout;
private Context mContext;
private TelnetPositionSender sender;
private ArrayList<SimplePosition> positions;
private int mRouteResource;
/**
* Constructor: create a new MockGPSLoggerDriver.
*
* @param context context of the test package
* @param route resource identifier for the xml route
* @param timeout time to idle between waypoints in miliseconds
*/
public MockGPSLoggerDriver(Context context, int route, int timeout)
{
this();
this.mTimeout = timeout;
this.mRouteResource = route;// R.xml.denhaagdenbosch;
this.mContext = context;
}
public MockGPSLoggerDriver()
{
this.sender = new TelnetPositionSender();
}
public int getPositions()
{
return this.positions.size();
}
private void prepareRun( int xmlResource )
{
this.positions = new ArrayList<SimplePosition>();
XmlResourceParser xmlParser = this.mContext.getResources().getXml( xmlResource );
doUglyXMLParsing( this.positions, xmlParser );
xmlParser.close();
}
public void run()
{
prepareRun( this.mRouteResource );
while( this.running && ( this.positions.size() > 0 ) )
{
SimplePosition position = this.positions.remove( 0 );
//String nmeaCommand = createGPGGALocationCommand(position.getLongitude(), position.getLatitude(), 0);
String nmeaCommand = createGPRMCLocationCommand( position.lng, position.lat, 0, 0 );
String checksum = calulateChecksum( nmeaCommand );
this.sender.sendCommand( "geo nmea $" + nmeaCommand + "*" + checksum + "\r\n" );
try
{
Thread.sleep( this.mTimeout );
}
catch( InterruptedException e )
{
Log.w( TAG, "Interrupted" );
}
}
}
public static String calulateChecksum( String nmeaCommand )
{
byte[] chars = null;
try
{
chars = nmeaCommand.getBytes( "ASCII" );
}
catch( UnsupportedEncodingException e )
{
e.printStackTrace();
}
byte xor = 0;
for( int i = 0; i < chars.length; i++ )
{
xor ^= chars[i];
}
return Integer.toHexString( (int) xor ).toUpperCase();
}
public void stop()
{
this.running = false;
}
private void doUglyXMLParsing( ArrayList<SimplePosition> positions, XmlResourceParser xmlParser )
{
int eventType;
try
{
eventType = xmlParser.getEventType();
SimplePosition lastPosition = null;
boolean speed = false;
while( eventType != XmlPullParser.END_DOCUMENT )
{
if( eventType == XmlPullParser.START_TAG )
{
if( xmlParser.getName().equals( "trkpt" ) || xmlParser.getName().equals( "rtept" ) || xmlParser.getName().equals( "wpt" ) )
{
lastPosition = new SimplePosition( xmlParser.getAttributeFloatValue( 0, 12.3456F ), xmlParser.getAttributeFloatValue( 1, 12.3456F ) );
positions.add( lastPosition );
}
if( xmlParser.getName().equals( "speed" ) )
{
speed = true;
}
}
else if( eventType == XmlPullParser.END_TAG )
{
if( xmlParser.getName().equals( "speed" ) )
{
speed = false;
}
}
else if( eventType == XmlPullParser.TEXT )
{
if( lastPosition != null && speed )
{
lastPosition.speed = Float.parseFloat( xmlParser.getText() );
}
}
eventType = xmlParser.next();
}
}
catch( XmlPullParserException e )
{ /* ignore */
}
catch( IOException e )
{/* ignore */
}
}
/**
* Create a NMEA GPRMC sentence
*
* @param longitude
* @param latitude
* @param elevation
* @param speed in mps
* @return
*/
public static String createGPRMCLocationCommand( double longitude, double latitude, double elevation, double speed )
{
speed *= 0.51; // from m/s to knots
final String COMMAND_GPS = "GPRMC," + "%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d,A," + // ss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection (N or S)
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection (E or W)
"%14$.2f," + // Speed over ground in knot
"0," + // Track made good in degrees True
"%11$02d" + // dd
"%12$02d" + // mm
"%13$02d," + // yy
"0," + // Magnetic variation degrees (Easterly var. subtracts from true course)
"E," + // East/West
"mode"; // Just as workaround....
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection, c.get( Calendar.DAY_OF_MONTH ), c.get( Calendar.MONTH ), c.get( Calendar.YEAR ) - 2000 , speed);
return command;
}
public static String createGPGGALocationCommand( double longitude, double latitude, double elevation )
{
final String COMMAND_GPS = "GPGGA," + // $--GGA,
"%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d," + // sss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection
"1,05,02.1,00545.5,M,-26.0,M,,";
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection );
return command;
}
class SimplePosition
{
public float speed;
public double lat, lng;
public SimplePosition(float latitude, float longtitude)
{
this.lat = latitude;
this.lng = longtitude;
}
}
public void sendSMS( String string )
{
this.sender.sendCommand( "sms send 31886606607 " + string + "\r\n" );
}
} | Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests;
import junit.framework.TestSuite;
import nl.sogeti.android.gpstracker.tests.actions.ExportGPXTest;
import nl.sogeti.android.gpstracker.tests.db.GPStrackingProviderTest;
import nl.sogeti.android.gpstracker.tests.gpsmock.MockGPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.logger.GPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.userinterface.LoggerMapTest;
import android.test.InstrumentationTestRunner;
import android.test.InstrumentationTestSuite;
/**
* Perform unit tests Run on the adb shell:
*
* <pre>
* am instrument -w nl.sogeti.android.gpstracker.tests/.GPStrackingInstrumentation
* </pre>
*
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class GPStrackingInstrumentation extends InstrumentationTestRunner
{
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getAllTests()
*/
@Override
public TestSuite getAllTests()
{
TestSuite suite = new InstrumentationTestSuite( this );
suite.setName( "GPS Tracking Testsuite" );
suite.addTestSuite( GPStrackingProviderTest.class );
suite.addTestSuite( MockGPSLoggerServiceTest.class );
suite.addTestSuite( GPSLoggerServiceTest.class );
suite.addTestSuite( ExportGPXTest.class );
suite.addTestSuite( LoggerMapTest.class );
// suite.addTestSuite( OpenGPSTrackerDemo.class ); // The demo recorded for youtube
// suite.addTestSuite( MapStressTest.class ); // The stress test of the map viewer
return suite;
}
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getLoader()
*/
@Override
public ClassLoader getLoader()
{
return GPStrackingInstrumentation.class.getClassLoader();
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.demo;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.tests.utils.MockGPSLoggerDriver;
import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
/**
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class OpenGPSTrackerDemo extends ActivityInstrumentationTestCase2<CommonLoggerMap>
{
private static final int ZOOM_LEVEL = 16;
private static final Class<CommonLoggerMap> CLASS = CommonLoggerMap.class;
private static final String PACKAGE = "nl.sogeti.android.gpstracker";
private CommonLoggerMap mLoggermap;
private GPSLoggerServiceManager mLoggerServiceManager;
private MapView mMapView;
private MockGPSLoggerDriver mSender;
public OpenGPSTrackerDemo()
{
super( PACKAGE, CLASS );
}
@Override
protected void setUp() throws Exception
{
super.setUp();
this.mLoggermap = getActivity();
this.mMapView = (MapView) this.mLoggermap.findViewById( nl.sogeti.android.gpstracker.R.id.myMapView );
this.mSender = new MockGPSLoggerDriver();
}
protected void tearDown() throws Exception
{
this.mLoggerServiceManager.shutdown( getActivity() );
super.tearDown();
}
/**
* Start tracking and allow it to go on for 30 seconds
*
* @throws InterruptedException
*/
@LargeTest
public void testTracking() throws InterruptedException
{
a_introSingelUtrecht30Seconds();
c_startRoute10Seconds();
d_showDrawMethods30seconds();
e_statistics10Seconds();
f_showPrecision30seconds();
g_stopTracking10Seconds();
h_shareTrack30Seconds();
i_finish10Seconds();
}
@SmallTest
public void a_introSingelUtrecht30Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL);
Thread.sleep( 1 * 1000 );
// Browse the Utrecht map
sendMessage( "Selecting a previous recorded track" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
Thread.sleep( 2 * 1000 );
sendMessage( "The walk around the \"singel\" in Utrecht" );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
Thread.sleep( 2 * 1000 );
sendMessage( "Scrolling about" );
this.mMapView.getController().animateTo( new GeoPoint( 52095829, 5118599 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52096778, 5125090 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52085117, 5128255 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52081517, 5121646 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52093535, 5116711 ) );
Thread.sleep( 2 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 5 * 1000 );
}
@SmallTest
public void c_startRoute10Seconds() throws InterruptedException
{
sendMessage( "Lets start a new route" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );//Toggle start/stop tracker
Thread.sleep( 1 * 1000 );
this.mMapView.getController().setZoom( ZOOM_LEVEL);
this.sendKeys( "D E M O SPACE R O U T E ENTER" );
Thread.sleep( 5 * 1000 );
sendMessage( "The GPS logger is already running as a background service" );
Thread.sleep( 5 * 1000 );
this.sendKeys( "ENTER" );
this.sendKeys( "T T T T" );
Thread.sleep( 30 * 1000 );
this.sendKeys( "G G" );
}
@SmallTest
public void d_showDrawMethods30seconds() throws InterruptedException
{
sendMessage( "Track drawing color has different options" );
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Plain green" );
Thread.sleep( 15 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "MENU" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP");
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Average speeds drawn" );
Thread.sleep( 15 * 1000 );
}
@SmallTest
public void e_statistics10Seconds() throws InterruptedException
{
// Show of the statistics screen
sendMessage( "Lets look at some statistics" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "E" );
Thread.sleep( 2 * 1000 );
sendMessage( "Shows the basics on time, speed and distance" );
Thread.sleep( 10 * 1000 );
this.sendKeys( "BACK" );
}
@SmallTest
public void f_showPrecision30seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
sendMessage( "There are options on the precision of tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Course will drain the battery the least" );
Thread.sleep( 5 * 1000 );
sendMessage( "Fine will store the best track" );
Thread.sleep( 10 * 1000 );
}
@SmallTest
public void g_stopTracking10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
Thread.sleep( 5 * 1000 );
// Stop tracking
sendMessage( "Stopping tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );
Thread.sleep( 2 * 1000 );
sendMessage( "Is the track stored?" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
}
private void h_shareTrack30Seconds()
{
// TODO Auto-generated method stub
}
@SmallTest
public void i_finish10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
sendMessage( "Thank you for watching this demo." );
Thread.sleep( 10 * 1000 );
Thread.sleep( 5 * 1000 );
}
private void sendMessage( String string )
{
this.mSender.sendSMS( string );
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Utility methods for working with a DOM tree.
* $Id: DOMUtil.java,v 1.18 2004/09/10 14:20:50 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class DOMUtil
{
/**
* Clears all childnodes in document
*/
public static void clearDocument(Document document)
{
NodeList nodeList = document.getChildNodes();
if (nodeList == null)
{
return;
}
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
document.removeChild(nodeList.item(i));
}
}
/**
* Create empty document TO BE DEBUGGED!.
*/
public static Document createDocument()
{
DocumentBuilder documentBuilder = null;
// System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
try
{
documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException pce)
{
warn("ParserConfigurationException: " + pce);
return null;
}
return documentBuilder.newDocument();
}
/**
* Copies all attributes from one element to another in the official way.
*/
public static void copyAttributes(Element elementFrom, Element elementTo)
{
NamedNodeMap nodeList = elementFrom.getAttributes();
if (nodeList == null)
{
// No attributes to copy: just return
return;
}
Attr attrFrom = null;
Attr attrTo = null;
// Needed as factory to create attrs
Document documentTo = elementTo.getOwnerDocument();
int len = nodeList.getLength();
// Copy each attr by making/setting a new one and
// adding to the target element.
for (int i = 0; i < len; i++)
{
attrFrom = (Attr) nodeList.item(i);
// Create an set value
attrTo = documentTo.createAttribute(attrFrom.getName());
attrTo.setValue(attrFrom.getValue());
// Set in target element
elementTo.setAttributeNode(attrTo);
}
}
public static Element getFirstElementByTagName(Document document, String tag)
{
// Get all elements matching the tagname
NodeList nodeList = document.getElementsByTagName(tag);
if (nodeList == null)
{
p("no list of elements with tag=" + tag);
return null;
}
// Get the first if any.
Element element = (Element) nodeList.item(0);
if (element == null)
{
p("no element for tag=" + tag);
return null;
}
return element;
}
public static Element getElementById(Document document, String id)
{
return getElementById(document.getDocumentElement(), id);
}
public static Element getElementById(Element element, String id)
{
return getElementById(element.getChildNodes(), id);
}
/**
* Get Element that has attribute id="xyz".
*/
public static Element getElementById(NodeList nodeList, String id)
{
// Note we should really use the Query here !!
Element element = null;
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
Node node = (Node) nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
element = (Element) node;
if (((Element) node).getAttribute("id").equals(id))
{
// found it !
break;
}
}
}
// returns found element or null
return element;
}
public static Document parse(InputStream anInputStream)
{
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(anInputStream);
} catch (Exception e)
{
throw new RuntimeException(e);
}
return document;
}
/**
* Prints an XML DOM.
*/
public static void printAsXML(Document document, PrintWriter printWriter)
{
new TreeWalker(new XMLPrintVisitor(printWriter)).traverse(document);
}
/**
* Prints an XML DOM.
*/
public static String dom2String(Document document)
{
StringWriter sw = new StringWriter();
DOMUtil.printAsXML(document, new PrintWriter(sw));
return sw.toString();
}
/**
* Replaces an element in document.
*/
public static void replaceElement(Element newElement, Element oldElement)
{
// Must be 1
Node parent = oldElement.getParentNode();
if (parent == null)
{
warn("replaceElement: no parent of oldElement found");
return;
}
// Create a copy owned by the document
ElementCopyVisitor ecv = new ElementCopyVisitor(oldElement.getOwnerDocument(), newElement);
Element newElementCopy = ecv.getCopy();
// Replace the old element with the new copy
parent.replaceChild(newElementCopy, oldElement);
}
/**
* Write Document structure to XML file.
*/
static public void document2File(Document document, String fileName)
{
new TreeWalker(new XMLPrintVisitor(fileName)).traverse(document);
}
public static void warn(String s)
{
p("DOMUtil: WARNING " + s);
}
public static void p(String s)
{
// System.out.println("DOMUtil: "+s);
}
}
/*
* $Log: DOMUtil.java,v $
* Revision 1.18 2004/09/10 14:20:50 just
* expandIncludes() tab to 2 spaces
*
* Revision 1.17 2004/09/10 12:48:11 just
* ok
*
* Revision 1.16 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.15 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.14 2002/06/18 10:30:02 just
* no rel change
*
* Revision 1.13 2001/08/01 15:20:23 kstroke
* fix for expand includes (added rootDir)
*
* Revision 1.12 2001/02/17 14:28:16 just
* added comments and changed interface for expandIds()
*
* Revision 1.11 2000/12/09 14:35:35 just
* added parse() method with optional DTD validation
*
* Revision 1.10 2000/09/21 22:37:20 just
* removed print statements
*
* Revision 1.9 2000/08/28 00:07:46 just
* changes for introduction of EntityResolverImpl
*
* Revision 1.8 2000/08/24 10:11:12 just
* added XML file verfication
*
* Revision 1.7 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Makes deep copy of an Element for another Document.
* $Id: ElementCopyVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class ElementCopyVisitor extends DefaultVisitor
{
Document ownerDocument;
Element elementOrig;
Element elementCopy;
Element elementPointer;
int level = 0;
public ElementCopyVisitor(Document theOwnerDocument, Element theElement)
{
ownerDocument = theOwnerDocument;
elementOrig = theElement;
}
public Element getCopy()
{
new TreeWalker(this).traverse(elementOrig);
return elementCopy;
}
public void visitDocumentPre(Document document)
{
p("visitDocumentPre: level=" + level);
}
public void visitDocumentPost(Document document)
{
p("visitDocumentPost: level=" + level);
}
public void visitElementPre(Element element)
{
p("visitElementPre: " + element.getTagName() + " level=" + level);
// Create the copy; must use target document as factory
Element newElement = ownerDocument.createElement(element.getTagName());
// If first time we need to create the copy
if (elementCopy == null)
{
elementCopy = newElement;
} else
{
elementPointer.appendChild(newElement);
}
// Always point to the last created and appended element
elementPointer = newElement;
level++;
}
public void visitElementPost(Element element)
{
p("visitElementPost: " + element.getTagName() + " level=" + level);
DOMUtil.copyAttributes(element, elementPointer);
level--;
if (level == 0) return;
// Always transfer attributes if any
if (level > 0)
{
elementPointer = (Element) elementPointer.getParentNode();
}
}
public void visitText(Text element)
{
// Create the copy; must use target document as factory
Text newText = ownerDocument.createTextNode(element.getData());
// If first time we need to create the copy
if (elementPointer == null)
{
p("ERROR no element copy");
return;
} else
{
elementPointer.appendChild(newText);
}
}
private void p(String s)
{
//System.out.println("ElementCopyVisitor: "+s);
}
}
/*
* $Log: ElementCopyVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* XMLPrintVisitor implements the Visitor interface in the visitor design pattern for the
* purpose of printing in HTML-like format the various DOM-Nodes.
* <p>In HTML-like printing, only the following Nodes are printed:
* <DL>
* <DT>Document</DT>
* <DD>Only the doctype provided on this constructor is written (i.e. no XML declaration, <!DOCTYPE>, or internal DTD).</DD>
* <DT>Element</DT>
* <DD>All element names are uppercased.</DD>
* <DD>Empty elements are written as <code><BR></code> instead of <code><BR/></code>.</DD>
* <DT>Attr</DT>
* <DD>All attribute names are lowercased.</DD>
* <DT>Text</DT>
* </DL>
* <p/>
* <p>The following sample code uses the XMLPrintVisitor on a hierarchy of nodes:
* <pre>
* <p/>
* PrintWriter printWriter = new PrintWriter();
* Visitor htmlPrintVisitor = new XMLPrintVisitor(printWriter);
* TreeWalker treeWalker = new TreeWalker(htmlPrintVisitor);
* treeWalker.traverse(document);
* printWriter.close();
* <p/>
* </pre>
* <p/>
* <P>By default, this doesn't print non-specified attributes.</P>
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
* @version $Id: XMLPrintVisitor.java,v 1.8 2003/01/06 00:23:49 just Exp $
* @see Visitor
* @see TreeWalker
*/
public class XMLPrintVisitor implements Visitor
{
protected Writer writer = null;
protected int level = 0;
protected String doctype = null;
/**
* Constructor for customized encoding and doctype.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
* @param doctype String to be printed at the top of the document.
*/
public XMLPrintVisitor(Writer writer, String encoding, String doctype)
{
this.writer = writer;
this.doctype = doctype;
// this.isPrintNonSpecifiedAttributes = false;
}
/**
* Constructor for customized encoding.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
*/
public XMLPrintVisitor(Writer writer, String encoding)
{
this(writer, encoding, null);
}
/**
* Constructor for default encoding.
*
* @param writer The character output stream to use.
*/
public XMLPrintVisitor(Writer writer)
{
this(writer, null, null);
}
/**
* Constructor for default encoding.
*
* @param fileName the filepath to write to
*/
public XMLPrintVisitor(String fileName)
{
try
{
writer = new FileWriter(fileName);
} catch (IOException ioe)
{
}
}
/**
* Writes the <var>doctype</var> from the constructor (if any).
*
* @param document Node print as HTML.
*/
public void visitDocumentPre(Document document)
{
}
/**
* Flush the writer.
*
* @param document Node to print as HTML.
*/
public void visitDocumentPost(Document document)
{
write("\n");
flush();
}
/**
* Creates a formatted string representation of the start of the specified <var>element</var> Node
* and its associated attributes, and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPre(Element element)
{
this.level++;
write("<" + element.getTagName());
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
Attr attr = (Attr) attributes.item(i);
visitAttributePre(attr);
}
write(">\n");
}
/**
* Creates a formatted string representation of the end of the specified <var>element</var> Node,
* and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPost(Element element)
{
String tagName = element.getTagName();
// if (element.hasChildNodes()) {
write("</" + tagName + ">\n");
// }
level--;
}
/**
* Creates a formatted string representation of the specified <var>attribute</var> Node
* and its associated attributes, and directs it to the print writer.
* <p>Note that TXAttribute Nodes are not parsed into the document object hierarchy by the
* XML4J parser; attributes exist as part of a Element Node.
*
* @param attr attr to print.
*/
public void visitAttributePre(Attr attr)
{
write(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
}
/**
* Creates a formatted string representation of the specified <var>text</var> Node,
* and directs it to the print writer. CDATASections are respected.
*
* @param text Node to print with format.
*/
public void visitText(Text text)
{
if (this.level > 0)
{
write(text.getData());
}
}
private void write(String s)
{
try
{
writer.write(s);
} catch (IOException e)
{
}
}
private void flush()
{
try
{
writer.flush();
} catch (IOException e)
{
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This class does a pre-order walk of a DOM tree or Node, calling an ElementVisitor
* interface as it goes.
* <p>The numbered nodes in the trees below indicate the order of traversal given
* the specified <code>startNode</code> of "1".
* <pre>
*
* 1 x x
* / \ / \ / \
* 2 6 1 x x x
* /|\ \ /|\ \ /|\ \
* 3 4 5 7 2 3 4 x x 1 x x
*
* </pre>
* $Id: TreeWalker.java,v 1.5 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
public class TreeWalker
{
private Visitor visitor;
private Node topNode;
/**
* Constructor.
*
* @param
*/
public TreeWalker(Visitor theVisitor)
{
visitor = theVisitor;
}
/**
* Disabled default constructor.
*/
private TreeWalker()
{
}
/**
* Perform a pre-order traversal non-recursive style.
*/
public void traverse(Node node)
{
// Remember the top node
if (topNode == null)
{
topNode = node;
}
while (node != null)
{
visitPre(node);
Node nextNode = node.getFirstChild();
while (nextNode == null)
{
visitPost(node);
// We are ready after post-visiting the topnode
if (node == topNode)
{
return;
}
try
{
nextNode = node.getNextSibling();
}
catch (IndexOutOfBoundsException e)
{
nextNode = null;
}
if (nextNode == null)
{
node = node.getParentNode();
if (node == null)
{
nextNode = node;
break;
}
}
}
node = nextNode;
}
}
protected void visitPre(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPre((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPre((Element) node);
break;
case Node.TEXT_NODE:
visitor.visitText((Text) node);
break;
// Not yet
case Node.ENTITY_REFERENCE_NODE:
System.out.println("ENTITY_REFERENCE_NODE");
default:
break;
}
}
protected void visitPost(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPost((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPost((Element) node);
break;
case Node.TEXT_NODE:
break;
default:
break;
}
}
}
/*
* $Log: TreeWalker.java,v $
* Revision 1.5 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.4 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.3 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This interface specifies the callbacks from the TreeWalker.
* $Id: Visitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Callback methods from the TreeWalker.
*/
public interface Visitor
{
public void visitDocumentPre(Document document);
public void visitDocumentPost(Document document);
public void visitElementPre(Element element);
public void visitElementPost(Element element);
public void visitText(Text element);
}
/*
* $Log: Visitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* Implements a Visitor that does nothin'
* $Id: DefaultVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class DefaultVisitor implements Visitor
{
public void visitDocumentPre(Document document)
{
}
public void visitDocumentPost(Document document)
{
}
public void visitElementPre(Element element)
{
}
public void visitElementPost(Element element)
{
}
public void visitText(Text element)
{
}
}
/*
* $Log: DefaultVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.logger;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import nl.sogeti.android.gpstracker.logger.IGPSLoggerServiceRemote;
import org.opentraces.metatracker.Constants;
/**
* Class to interact with the service that tracks and logs the locations
*
* @author rene (c) Jan 18, 2009, Sogeti B.V. adapted by Just van den Broecke
* @version $Id: GPSLoggerServiceManager.java 455 2010-03-14 08:16:44Z rcgroot $
*/
public class GPSLoggerServiceManager
{
private static final String TAG = "MT.GPSLoggerServiceManager";
private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION";
private Context mCtx;
private IGPSLoggerServiceRemote mGPSLoggerRemote;
private final Object mStartLock = new Object();
private boolean mStarted = false;
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mServiceConnection = null;
public GPSLoggerServiceManager(Context ctx)
{
this.mCtx = ctx;
}
public boolean isStarted()
{
synchronized (mStartLock)
{
return mStarted;
}
}
public int getLoggingState()
{
synchronized (mStartLock)
{
int logging = Constants.UNKNOWN;
try
{
if (this.mGPSLoggerRemote != null)
{
logging = this.mGPSLoggerRemote.loggingState();
Log.d(TAG, "mGPSLoggerRemote tells state to be " + logging);
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return logging;
}
}
public boolean isMediaPrepared()
{
synchronized (mStartLock)
{
boolean prepared = false;
try
{
if (this.mGPSLoggerRemote != null)
{
prepared = this.mGPSLoggerRemote.isMediaPrepared();
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return prepared;
}
}
public long startGPSLogging(String name)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.startLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void pauseGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.pauseLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
}
}
public long resumeGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.resumeLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void stopGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.stopLogging();
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
public void storeMediaUri(Uri mediaUri)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.storeMediaUri(mediaUri);
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void startup(final ServiceConnection observer)
{
Log.d(TAG, "connectToGPSLoggerService()");
if (!mStarted)
{
this.mServiceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
synchronized (mStartLock)
{
Log.d(TAG, "onServiceConnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface(service);
mStarted = true;
if (observer != null)
{
observer.onServiceConnected(className, service);
}
}
}
public void onServiceDisconnected(ComponentName className)
{
synchronized (mStartLock)
{
Log.e(TAG, "onServiceDisconnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = null;
mStarted = false;
if (observer != null)
{
observer.onServiceDisconnected(className);
}
}
}
};
this.mCtx.bindService(new Intent(Constants.SERVICE_GPS_LOGGING), this.mServiceConnection, Context.BIND_AUTO_CREATE);
} else
{
Log.w(TAG, "Attempting to connect whilst connected");
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void shutdown()
{
Log.d(TAG, "disconnectFromGPSLoggerService()");
try
{
this.mCtx.unbindService(this.mServiceConnection);
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Failed to unbind a service, prehaps the service disapeared?", e);
}
}
} | Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Constants and utilities for the KW protocol.
*
* @author $Author: $
* @version $Id: Protocol.java,v 1.2 2005/07/22 22:25:20 just Exp $
*/
public class Protocol
{
/**
* AMUSE Protocol version.
*/
public static final String PROTOCOL_VERSION = "4.0";
/**
* Postfixes
*/
public static final String POSTFIX_REQ = "-req";
public static final String POSTFIX_RSP = "-rsp";
public static final String POSTFIX_NRSP = "-nrsp";
public static final String POSTFIX_IND = "-ind";
/**
* Service id's
*/
public static final String SERVICE_SESSION_CREATE = "ses-create";
public static final String SERVICE_LOGIN = "ses-login";
public static final String SERVICE_LOGOUT = "ses-logout";
public static final String SERVICE_SESSION_PING = "ses-ping";
public static final String SERVICE_QUERY_STORE = "query-store";
public static final String SERVICE_MAP_AVAIL = "map-avail";
public static final String SERVICE_MULTI_REQ = "multi-req";
/**
* Common Attributes *
*/
public static final String ATTR_DEVID = "devid";
public static final String ATTR_USER = "user";
public static final String ATTR_AGENT = "agent";
public static final String ATTR_AGENTKEY = "agentkey";
public static final String ATTR_SECTIONS = "sections";
public static final String ATTR_ID = "id";
public static final String ATTR_CMD = "cmd";
public static final String ATTR_ERROR = "error";
public static final String ATTR_ERRORID = "errorId"; // yes id must be Id !!
public static final String ATTR_PASSWORD = "password";
public static final String ATTR_PROTOCOLVERSION = "protocolversion";
public static final String ATTR_STOPONERROR = "stoponerror";
public static final String ATTR_T = "t";
public static final String ATTR_TIME = "time";
public static final String ATTR_DETAILS = "details";
public static final String ATTR_NAME = "name";
/**
* Error ids returned in -nrsp as attribute ATTR_ERRORID
*/
public final static int
// 4000-4999 are "user-correctable" errors (user sends wrong input)
// 5000-5999 are server failures
ERR4004_ILLEGAL_COMMAND_FOR_STATE = 4003,
ERR4004_INVALID_ATTR_VALUE = 4004,
ERR4007_AGENT_LEASE_EXPIRED = 4007,
//_Portal/Application_error_codes_(4100-4199)
ERR4100_INVALID_USERNAME = 4100,
ERR4101_INVALID_PASSWORD = 4101,
ERR4102_MAX_LOGIN_ATTEMPTS_EXCEEDED = 4102,
//_General_Server_Error_Codes
ERR5000_INTERNAL_SERVER_ERROR = 5000;
/**
* Create login protocol request.
*/
public static Element createLoginRequest(String aName, String aPassword)
{
Element request = createRequest(SERVICE_LOGIN);
request.setAttribute(ATTR_NAME, aName);
request.setAttribute(ATTR_PASSWORD, aPassword);
request.setAttribute(ATTR_PROTOCOLVERSION, PROTOCOL_VERSION);
return request;
}
/**
* Create create-session protocol request.
*/
public static Element createSessionCreateRequest()
{
return createRequest(SERVICE_SESSION_CREATE);
}
/**
* Create a positive response element.
*/
public static Element createRequest(String aService)
{
Element element = null;
try
{
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
element = doc.createElement(aService + POSTFIX_REQ);
doc.appendChild(element);
} catch (Throwable t)
{
}
return element;
}
/**
* Return service name for a message tag.
*
* @param aMessageTag
* @return
*/
public static String getServiceName(String aMessageTag)
{
try
{
return aMessageTag.substring(0, aMessageTag.lastIndexOf('-'));
}
catch (Throwable t)
{
throw new IllegalArgumentException("getServiceName: invalid tag: " + aMessageTag);
}
}
/**
* Is message a (negative) response..
*
* @param message
* @return
*/
public static boolean isResponse(Element message)
{
String tag = message.getTagName();
return tag.endsWith(POSTFIX_RSP) || tag.endsWith(POSTFIX_NRSP);
}
/**
* Is message a positive response..
*
* @param message
* @return
*/
public static boolean isPositiveResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_RSP);
}
/**
* Is message a negative response..
*
* @param message
* @return
*/
public static boolean isNegativeResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_NRSP);
}
public static boolean isPositiveServiceResponse(Element message, String service)
{
return isPositiveResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isNegativeServiceResponse(Element message, String service)
{
return isNegativeResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isService(Element message, String service)
{
return service.equals(getServiceName(message.getTagName()));
}
protected Protocol()
{
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.opentraces.metatracker.xml.DOMUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Basic OpenTraces client using XML over HTTP.
* <p/>
* Use this class within Android HTTP clients.
*
* @author $Author: Just van den Broecke$
* @version $Revision: 3043 $ $Id: HTTPClient.java 3043 2009-01-17 16:25:21Z just $
* @see
*/
public class OpenTracesClient extends Protocol
{
private static final String LOG_TAG = "MT.OpenTracesClient";
/**
* Default KW session timeout (minutes).
*/
public static final int DEFAULT_TIMEOUT_MINS = 5;
/**
* Full KW protocol URL.
*/
private String protocolURL;
/**
* Debug flag for verbose output.
*/
private boolean debug;
/**
* Key gotten on login ack
*/
private String agentKey;
/**
* Keyworx session timeout (minutes).
*/
private int timeout;
/**
* Saved login request for session restore on timeout.
*/
private Element loginRequest;
/**
* Constructor with full protocol URL e.g. http://www.bla.com/proto.srv.
*/
public OpenTracesClient(String aProtocolURL)
{
this(aProtocolURL, DEFAULT_TIMEOUT_MINS);
}
/**
* Constructor with protocol URL and timeout.
*/
public OpenTracesClient(String aProtocolURL, int aTimeout)
{
protocolURL = aProtocolURL;
if (!protocolURL.endsWith("/proto.srv")) {
protocolURL += "/proto.srv";
}
timeout = aTimeout;
}
/**
* Create session.
*/
synchronized public Element createSession() throws ClientException
{
agentKey = null;
// Create XML request
Element request = createRequest(SERVICE_SESSION_CREATE);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
public String getAgentKey()
{
return agentKey;
}
public boolean hasSession()
{
return agentKey != null;
}
public boolean isLoggedIn()
{
return hasSession() && loginRequest != null;
}
/**
* Login on portal.
*/
synchronized public Element login(String aName, String aPassword) throws ClientException
{
// Create XML request
Element request = createLoginRequest(aName, aPassword);
// Execute request
Element response = doRequest(request);
// Filter session-related attrs
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
/**
* Keep alive service.
*/
synchronized public Element ping() throws ClientException
{
return service(createRequest(SERVICE_SESSION_PING));
}
/**
* perform TWorx service request.
*/
synchronized public Element service(Element request) throws ClientException
{
throwOnInvalidSession();
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Positive response: return wrapped handler response
return response;
}
/**
* perform TWorx multi-service request.
*/
synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException
{
// We don't need a valid session as one of the requests
// may be a login or create-session request.
// Create multi-req request with individual requests as children
Element request = createRequest(SERVICE_MULTI_REQ);
request.setAttribute(ATTR_STOPONERROR, stopOnError + "");
for (Element req : requests)
{
request.appendChild(req);
}
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Filter child responses for session-based responses
NodeList responseList = response.getChildNodes();
List<Element> responses = new ArrayList(responseList.getLength());
for (int i = 0; i < responseList.getLength(); i++)
{
handleResponse(requests.get(i), (Element) responseList.item(i));
responses.add((Element) responseList.item(i));
}
// Positive multi-req response: return child responses
return responses;
}
/**
* Logout from portal.
*/
synchronized public Element logout() throws ClientException
{
throwOnInvalidSession();
// Create XML request
Element request = createRequest(SERVICE_LOGOUT);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
// Throw exception or return positive response
// throwOnNrsp(response);
return response;
}
/*
http://brainflush.wordpress.com/2008/10/17/talking-to-web-servers-via-http-in-android-10/
*/
public void uploadFile(String fileName)
{
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
File f = new File(fileName);
HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myIdentifier", new StringBody("somevalue"));
entity.addPart("myFile", new FileBody(f));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
Log.d(LOG_TAG, "Upload result: " + response.getStatusLine());
if (entity != null)
{
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
} catch (Throwable ex)
{
Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
}
}
public void setDebug(boolean b)
{
debug = b;
}
/**
* Filter responses for session-related requests.
*/
private void handleResponse(Element request, Element response) throws ClientException
{
if (isNegativeResponse(response))
{
return;
}
String service = Protocol.getServiceName(request.getTagName());
if (service.equals(SERVICE_LOGIN))
{
// Save for later session restore
loginRequest = request;
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// if (response.hasAttribute(ATTR_TIME)) {
// DateTimeUtils.setTime(response.getLongAttr(ATTR_TIME));
// }
} else if (service.equals(SERVICE_SESSION_CREATE))
{
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
} else if (service.equals(SERVICE_LOGOUT))
{
loginRequest = null;
agentKey = null;
}
}
/**
* Throw exception on negative protocol response.
*/
private void throwOnNrsp(Element anElement) throws ClientException
{
if (isNegativeResponse(anElement))
{
String details = "no details";
if (anElement.hasAttribute(ATTR_DETAILS))
{
details = anElement.getAttribute(ATTR_DETAILS);
}
throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)),
anElement.getAttribute(ATTR_ERROR), details);
}
}
/**
* Throw exception when not logged in.
*/
private void throwOnInvalidSession() throws ClientException
{
if (agentKey == null)
{
throw new ClientException("Invalid tworx session");
}
}
/**
* .
*/
private Element redoRequestOnSessionTimeout(Element request, Element response) throws ClientException
{
// Check for session timeout
if (isNegativeResponse(response) && Integer.parseInt(response.getAttribute(ATTR_ERRORID)) == Protocol.ERR4007_AGENT_LEASE_EXPIRED)
{
p("Reestablishing session...");
// Reset session
agentKey = null;
// Do login if already logged in
if (loginRequest != null)
{
response = doRequest(loginRequest);
throwOnNrsp(response);
} else
{
response = createSession();
throwOnNrsp(response);
}
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// Re-issue service request and return new response
return doRequest(request);
}
// No session timeout so same response
return response;
}
/**
* Do XML over HTTP request and retun response.
*/
private Element doRequest(Element anElement) throws ClientException
{
// Create URL to use
String url = protocolURL;
if (agentKey != null)
{
url = url + "?agentkey=" + agentKey;
} else
{
// Must be login
url = url + "?timeout=" + timeout;
}
p("doRequest: " + url + " req=" + anElement.getTagName());
// Perform request/response
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Element replyElement = null;
try
{
// Make sure the server knows what kind of a response we will accept
httpPost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httpPost.addHeader("Content-Type", "application/xml");
String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument());
StringEntity entity = new StringEntity(xmlString, "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
// Parse response
Document replyDoc = DOMUtil.parse(response.getEntity().getContent());
replyElement = replyDoc.getDocumentElement();
p("doRequest: rsp=" + replyElement.getTagName());
}
catch (Throwable t)
{
throw new ClientException("Error in doRequest: " + t);
}
finally
{
}
return replyElement;
}
/**
* Util: print.
*/
private void p(String s)
{
if (debug)
{
Log.d(LOG_TAG, s);
}
}
/**
* Util: warn.
*/
private void warn(String s)
{
warn(s, null);
}
/**
* Util: warn with exception.
*/
private void warn(String s, Throwable t)
{
Log.e(LOG_TAG, s + " ex=" + t, t);
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
/**
* Generic exception wrapper. $Id: ClientException.java,v 1.2 2005/07/22 22:25:20 just Exp $
*
* @author $Author: Just van den Broecke$
* @version $Revision: $
*/
public class ClientException extends Exception
{
private int errorId;
String error;
protected ClientException()
{
}
public ClientException(String aMessage, Throwable t)
{
super(aMessage + "\n embedded exception=" + t.toString());
}
public ClientException(String aMessage)
{
super(aMessage);
}
public ClientException(int anErrorId, String anError, String someDetails)
{
super(someDetails);
errorId = anErrorId;
error = anError;
}
public ClientException(Throwable t)
{
this("ClientException: ", t);
}
public String toString()
{
return "ClientException: " + getMessage();
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker;
import android.net.Uri;
/**
* Various application wide constants
*
* @author Just van den Broecke
* @version $Id:$
*/
public class Constants
{
/**
* The authority of the track data provider
*/
public static final String AUTHORITY = "nl.sogeti.android.gpstracker";
/**
* The content:// style URL for the track data provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
/**
* Logging states, slightly adapted from GPSService states
*/
public static final int DOWN = 0;
public static final int LOGGING = 1;
public static final int PAUSED = 2;
public static final int STOPPED = 3;
public static final int UNKNOWN = 4;
public static String[] LOGGING_STATES = {"down", "logging", "paused", "stopped", "unknown"};
public static final String DISABLEBLANKING = "disableblanking";
public static final String PREF_ENABLE_SOUND = "pref_enablesound";
public static final String PREF_SERVER_URL = "pref_server_url";
public static final String PREF_SERVER_USER = "pref_server_user";
public static final String PREF_SERVER_PASSWORD = "pref_server_password";
public static final String SERVICE_GPS_LOGGING = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService";
public static final String EXTERNAL_DIR = "/OpenGPSTracker/";
public static final Uri NAME_URI = Uri.parse("content://" + AUTHORITY + ".string");
/**
* Activity Action: Pick a file through the file manager, or let user
* specify a custom file name.
* Data is the current file name or file name suggestion.
* Returns a new file name as file URI in data.
* <p/>
* <p>Constant Value: "org.openintents.action.PICK_FILE"</p>
*/
public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE";
public static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1;
/**
* Activity Action: Show an about dialog to display
* information about the application.
* <p/>
* The application information is retrieved from the
* application's manifest. In order to send the package
* you have to launch this activity through
* startActivityForResult().
* <p/>
* Alternatively, you can specify the package name
* manually through the extra EXTRA_PACKAGE.
* <p/>
* All data can be replaced using optional intent extras.
* <p/>
* <p>
* Constant Value: "org.openintents.action.SHOW_ABOUT_DIALOG"
* </p>
*/
public static final String OI_ACTION_SHOW_ABOUT_DIALOG =
"org.openintents.action.SHOW_ABOUT_DIALOG";
/**
* Definitions for tracks.
*
*/
public static final class Tracks implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "tracks";
/**
* The end time
*/
public static final String NAME = "name";
public static final String CREATION_TIME = "creationtime";
/**
* The MIME type of a CONTENT_URI subdirectory of a single track.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track";
/**
* The content:// style URL for this provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for segments.
*/
public static final class Segments implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "segments";
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
static final String TRACK_TYPE = "INTEGER NOT NULL";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
/**
* The MIME type of a CONTENT_URI subdirectory of a single segment.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment";
/**
* The MIME type of CONTENT_URI providing a directory of segments.
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for media URI's.
*
*/
public static final class Media implements android.provider.BaseColumns
{
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
public static final String SEGMENT = "segment";
public static final String WAYPOINT = "waypoint";
public static final String URI = "uri";
/**
* The name of this table
*/
public static final String TABLE = "media";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for waypoints.
*
*/
public static final class Waypoints implements android.provider.BaseColumns
{
/**
* The name of this table
*/
public static final String TABLE = "waypoints";
/**
* The latitude
*/
public static final String LATITUDE = "latitude";
/**
* The longitude
*/
public static final String LONGITUDE = "longitude";
/**
* The recorded time
*/
public static final String TIME = "time";
/**
* The speed in meters per second
*/
public static final String SPEED = "speed";
/**
* The segment _id to which this segment belongs
*/
public static final String SEGMENT = "tracksegment";
/**
* The accuracy of the fix
*/
public static final String ACCURACY = "accuracy";
/**
* The altitude
*/
public static final String ALTITUDE = "altitude";
/**
* the bearing of the fix
*/
public static final String BEARING = "bearing";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.content.SharedPreferences;
import android.location.Location;
import org.opentraces.metatracker.Constants;
public class TrackingState
{
public int loggingState;
public boolean newRoadRating;
public int roadRating;
public float distance;
public Track track = new Track();
public Segment segment = new Segment();
public Waypoint waypoint = new Waypoint();
private SharedPreferences sharedPreferences;
public TrackingState(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
reset();
}
public void load()
{
distance = sharedPreferences.getFloat("distance", 0.0f);
track.load();
waypoint.load();
}
public void save()
{
sharedPreferences.edit().putFloat("distance", distance).commit();
track.save();
waypoint.save();
}
public void reset()
{
loggingState = Constants.DOWN;
distance = 0.0f;
waypoint.reset();
track.reset();
}
public class Track
{
public int id = -1;
public String name = "NO TRACK";
public long creationTime;
public void load()
{
id = sharedPreferences.getInt("track.id", -1);
name = sharedPreferences.getString("track.name", "NO TRACK");
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("track.id", id);
editor.putString("track.name", name);
editor.commit();
}
public void reset()
{
name = "NO TRACK";
id = -1;
}
}
public static class Segment
{
public int id = -1;
}
public class Waypoint
{
public int id = -1;
public Location location;
public float speed;
public float accuracy;
public int count;
public void load()
{
id = sharedPreferences.getInt("waypoint.id", -1);
count = sharedPreferences.getInt("waypoint.count", 0);
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("waypoint.id", id);
editor.putInt("waypoint.count", count);
editor.commit();
}
public void reset()
{
count = 0;
id = -1;
location = null;
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import org.opentraces.metatracker.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
/**
* Dialog for setting preferences.
*
* @author Just van den Broecke
*/
public class SettingsActivity extends PreferenceActivity
{
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
addPreferencesFromResource( R.layout.settings );
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.Constants;
import org.opentraces.metatracker.R;
import org.opentraces.metatracker.net.OpenTracesClient;
public class UploadTrackActivity extends Activity
{
protected static final int DIALOG_FILENAME = 11;
protected static final int PROGRESS_STEPS = 10;
private static final int DIALOG_INSTALL_FILEMANAGER = 34;
private static final String TAG = "MT.UploadTrack";
private String filePath;
private TextView fileNameView;
private SharedPreferences sharedPreferences;
private final DialogInterface.OnClickListener mFileManagerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager");
Intent oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiFileManagerDownloadIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk");
oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiFileManagerDownloadIntent);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.uploaddialog);
fileNameView = (TextView) findViewById(R.id.filename);
filePath = null;
pickFile();
Button okay = (Button) findViewById(R.id.okayupload_button);
okay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (filePath == null) {
return;
}
uploadFile(filePath);
}
});
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_FILEMANAGER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nofilemanager)
.setMessage(R.string.dialog_nofilemanager_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mFileManagerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
// Bundle extras = intent.getExtras();
switch (requestCode)
{
case Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY:
if (resultCode == RESULT_OK && intent != null)
{
// obtain the filename
filePath = intent.getDataString();
if (filePath != null)
{
// Get rid of URI prefix:
if (filePath.startsWith("file://"))
{
filePath = filePath.substring(7);
}
fileNameView.setText(filePath);
}
}
break;
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void pickFile()
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
} catch (ActivityNotFoundException e)
{
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_FILEMANAGER);
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void uploadFile(String aFilePath)
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
;
OpenTracesClient openTracesClient = new OpenTracesClient(sharedPreferences.getString(Constants.PREF_SERVER_URL, "http://geotracing.com/tland"));
openTracesClient.createSession();
openTracesClient.login(sharedPreferences.getString(Constants.PREF_SERVER_USER, "no_user"), sharedPreferences.getString(Constants.PREF_SERVER_PASSWORD, "no_passwd"));
openTracesClient.uploadFile(aFilePath);
openTracesClient.logout();
} catch (Throwable e)
{
Log.e(TAG, "Error uploading file : ", e);
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.*;
import android.content.*;
import android.database.ContentObserver;
import android.database.Cursor;
import android.location.Location;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.*;
import org.opentraces.metatracker.logger.GPSLoggerServiceManager;
import java.text.DecimalFormat;
public class MainActivity extends Activity
{
// MENU'S
private static final int MENU_SETTINGS = 1;
private static final int MENU_TRACKING = 2;
private static final int MENU_UPLOAD = 3;
private static final int MENU_HELP = 4;
private static final int MENU_ABOUT = 5;
private static final int DIALOG_INSTALL_OPENGPSTRACKER = 1;
private static final int DIALOG_INSTALL_ABOUT = 2;
private static DecimalFormat REAL_FORMATTER1 = new DecimalFormat("0.#");
private static DecimalFormat REAL_FORMATTER2 = new DecimalFormat("0.##");
private static final String TAG = "MetaTracker.Main";
private TextView waypointCountView, timeView, distanceView, speedView, roadRatingView, accuracyView;
private GPSLoggerServiceManager loggerServiceManager;
private TrackingState trackingState;
private MediaPlayer mediaPlayer;
// private PowerManager.WakeLock wakeLock = null;
private static final int COLOR_WHITE = 0xFFFFFFFF;
private static final int[] ROAD_RATING_COLORS = {0xFF808080, 0xFFCC0099, 0xFFEE0000, 0xFFFF6600, 0xFFFFCC00, 0xFF33CC33};
private SharedPreferences sharedPreferences;
private Button[] roadRatingButtons = new Button[6];
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
trackingState = new TrackingState(sharedPreferences);
trackingState.load();
setContentView(R.layout.main);
getLastTrackingState();
getApplicationContext().getContentResolver().registerContentObserver(Constants.Tracks.CONTENT_URI, true, trackingObserver);
// mUnits = new UnitsI18n(this, mUnitsChangeListener);
speedView = (TextView) findViewById(R.id.currentSpeed);
timeView = (TextView) findViewById(R.id.currentTime);
distanceView = (TextView) findViewById(R.id.totalDist);
waypointCountView = (TextView) findViewById(R.id.waypointCount);
accuracyView = (TextView) findViewById(R.id.currentAccuracy);
roadRatingView = (TextView) findViewById(R.id.currentRoadRating);
// Capture our button from layout
roadRatingButtons[0] = (Button) findViewById(R.id.road_qual_none);
roadRatingButtons[1] = (Button) findViewById(R.id.road_qual_nogo);
roadRatingButtons[2] = (Button) findViewById(R.id.road_qual_bad);
roadRatingButtons[3] = (Button) findViewById(R.id.road_qual_poor);
roadRatingButtons[4] = (Button) findViewById(R.id.road_qual_good);
roadRatingButtons[5] = (Button) findViewById(R.id.road_qual_best);
for (Button button : roadRatingButtons)
{
button.setOnClickListener(roadRatingButtonListener);
}
bindGPSLoggingService();
}
/**
* Called when the activity is started.
*/
@Override
public void onStart()
{
Log.d(TAG, "onStart()");
super.onStart();
}
/**
* Called when the activity is started.
*/
@Override
public void onRestart()
{
Log.d(TAG, "onRestart()");
super.onRestart();
}
/**
* Called when the activity is resumed.
*/
@Override
public void onResume()
{
Log.d(TAG, "onResume()");
getLastTrackingState();
// updateBlankingBehavior();
drawScreen();
super.onResume();
}
/**
* Called when the activity is paused.
*/
@Override
public void onPause()
{
trackingState.save();
/* if (this.wakeLock != null && this.wakeLock.isHeld())
{
this.wakeLock.release();
Log.w(TAG, "onPause(): Released lock to keep screen on!");
} */
Log.d(TAG, "onPause()");
super.onPause();
}
@Override
protected void onDestroy()
{
Log.d(TAG, "onDestroy()");
trackingState.save();
/* if (wakeLock != null && wakeLock.isHeld())
{
wakeLock.release();
Log.w(TAG, "onDestroy(): Released lock to keep screen on!");
} */
getApplicationContext().getContentResolver().unregisterContentObserver(trackingObserver);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this.sharedPreferenceChangeListener);
unbindGPSLoggingService();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T');
menu.add(ContextMenu.NONE, MENU_UPLOAD, ContextMenu.NONE, R.string.menu_upload).setIcon(R.drawable.ic_menu_upload).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C');
menu.add(ContextMenu.NONE, MENU_HELP, ContextMenu.NONE, R.string.menu_help).setIcon(R.drawable.ic_menu_help).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A');
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MENU_TRACKING:
startOpenGPSTrackerActivity();
break;
case MENU_UPLOAD:
startActivityForClass("org.opentraces.metatracker", "org.opentraces.metatracker.activity.UploadTrackActivity");
break;
case MENU_SETTINGS:
startActivity(new Intent(this, SettingsActivity.class));
break;
case MENU_ABOUT:
try
{
startActivityForResult(new Intent(Constants.OI_ACTION_SHOW_ABOUT_DIALOG), MENU_ABOUT);
}
catch (ActivityNotFoundException e)
{
showDialog(DIALOG_INSTALL_ABOUT);
}
break;
default:
showAlert(R.string.menu_message_unsupported);
break;
}
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
AlertDialog.Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_OPENGPSTRACKER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_noopengpstracker)
.setMessage(R.string.dialog_noopengpstracker_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOpenGPSTrackerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
case DIALOG_INSTALL_ABOUT:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nooiabout)
.setMessage(R.string.dialog_nooiabout_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOiAboutDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
private void drawTitleBar(String s)
{
this.setTitle(s);
}
/**
* Called on any update to Tracks table.
*/
private void onTrackingUpdate()
{
getLastTrackingState();
if (trackingState.waypoint.count == 1)
{
sendRoadRating();
}
drawScreen();
}
/**
* Called on any update to Tracks table.
*/
private synchronized void playPingSound()
{
if (!sharedPreferences.getBoolean(Constants.PREF_ENABLE_SOUND, false)) {
return;
}
try
{
if (mediaPlayer == null)
{
mediaPlayer = MediaPlayer.create(this, R.raw.ping_short);
} else
{
mediaPlayer.stop();
mediaPlayer.prepare();
}
mediaPlayer.start();
} catch (Throwable t)
{
Log.e(TAG, "Error playing sound", t);
}
}
/**
* Retrieve the last point of the current track
*/
private void getLastWaypoint()
{
Cursor waypoint = null;
try
{
ContentResolver resolver = this.getContentResolver();
waypoint = resolver.query(Uri.withAppendedPath(Constants.Tracks.CONTENT_URI, trackingState.track.id + "/" + Constants.Waypoints.TABLE),
new String[]{"max(" + Constants.Waypoints.TABLE + "." + Constants.Waypoints._ID + ")", Constants.Waypoints.LONGITUDE, Constants.Waypoints.LATITUDE, Constants.Waypoints.SPEED, Constants.Waypoints.ACCURACY, Constants.Waypoints.SEGMENT
}, null, null, null);
if (waypoint != null && waypoint.moveToLast())
{
// New point: increase pointcount
int waypointId = waypoint.getInt(0);
if (waypointId > 0 && trackingState.waypoint.id != waypointId)
{
trackingState.waypoint.count++;
trackingState.waypoint.id = waypoint.getInt(0);
// Increase total distance
Location newLocation = new Location(this.getClass().getName());
newLocation.setLongitude(waypoint.getDouble(1));
newLocation.setLatitude(waypoint.getDouble(2));
if (trackingState.waypoint.location != null)
{
float delta = trackingState.waypoint.location.distanceTo(newLocation);
// Log.d(TAG, "trackingState.distance=" + trackingState.distance + " delta=" + delta + " ll=" + waypoint.getDouble(1) + ", " +waypoint.getDouble(2));
trackingState.distance += delta;
}
trackingState.waypoint.location = newLocation;
trackingState.waypoint.speed = waypoint.getFloat(3);
trackingState.waypoint.accuracy = waypoint.getFloat(4);
trackingState.segment.id = waypoint.getInt(5);
playPingSound();
}
}
}
finally
{
if (waypoint != null)
{
waypoint.close();
}
}
}
private void getLastTrack()
{
Cursor cursor = null;
try
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
cursor = resolver.query(Constants.Tracks.CONTENT_URI, new String[]{"max(" + Constants.Tracks._ID + ")", Constants.Tracks.NAME, Constants.Tracks.CREATION_TIME}, null, null, null);
if (cursor != null && cursor.moveToLast())
{
int trackId = cursor.getInt(0);
// Check if new track created
if (trackId != trackingState.track.id)
{
trackingState.reset();
trackingState.save();
}
trackingState.track.id = trackId;
trackingState.track.name = cursor.getString(1);
trackingState.track.creationTime = cursor.getLong(2);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
private void getLastTrackingState()
{
getLastTrack();
getLoggingState();
getLastWaypoint();
}
private void sendRoadRating()
{
if (trackingState.roadRating > 0 && trackingState.newRoadRating && loggerServiceManager != null)
{
Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(trackingState.roadRating + ""));
loggerServiceManager.storeMediaUri(media);
trackingState.newRoadRating = false;
}
}
private void startOpenGPSTrackerActivity()
{
try
{
startActivityForClass("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.viewer.LoggerMap");
}
catch (ActivityNotFoundException e)
{
Log.i(TAG, "Cannot find activity for open-gpstracker");
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_OPENGPSTRACKER);
}
sendRoadRating();
}
private void startActivityForClass(String aPackageName, String aClassName) throws ActivityNotFoundException
{
Intent intent = new Intent();
intent.setClassName(aPackageName, aClassName);
startActivity(intent);
}
private void bindGPSLoggingService()
{
unbindGPSLoggingService();
ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
getLoggingState();
drawTitleBar();
}
public void onServiceDisconnected(ComponentName className)
{
trackingState.loggingState = Constants.DOWN;
}
};
loggerServiceManager = new GPSLoggerServiceManager(this);
loggerServiceManager.startup(serviceConnection);
}
private void unbindGPSLoggingService()
{
if (loggerServiceManager == null)
{
return;
}
try
{
loggerServiceManager.shutdown();
} finally
{
loggerServiceManager = null;
trackingState.loggingState = Constants.DOWN;
}
}
private void getLoggingState()
{
// Get state from logger if bound
trackingState.loggingState = loggerServiceManager == null ? Constants.DOWN : loggerServiceManager.getLoggingState();
// protect for values outside array bounds (set to unknown)
if (trackingState.loggingState < 0 || trackingState.loggingState > Constants.LOGGING_STATES.length - 1)
{
trackingState.loggingState = Constants.UNKNOWN;
}
}
private String getLoggingStateStr()
{
return Constants.LOGGING_STATES[trackingState.loggingState];
}
private void drawTitleBar()
{
drawTitleBar("MT : " + trackingState.track.name + " : " + getLoggingStateStr());
}
private void drawScreen()
{
drawTitleBar();
drawTripStats();
drawRoadRating();
}
/**
* Retrieves the numbers of the measured speed and altitude
* from the most recent waypoint and
* updates UI components with this latest bit of information.
*/
private void drawTripStats()
{
try
{
waypointCountView.setText(trackingState.waypoint.count + "");
long secsDelta = 0L;
long hours = 0L;
long mins = 0L;
long secs = 0L;
if (trackingState.track.creationTime != 0)
{
secsDelta = (System.currentTimeMillis() - trackingState.track.creationTime) / 1000;
hours = secsDelta / 3600L;
mins = (secsDelta % 3600L) / 60L;
secs = ((secsDelta % 3600L) % 60);
}
timeView.setText(formatTimeNum(hours) + ":" + formatTimeNum(mins) + ":" + formatTimeNum(secs));
speedView.setText(REAL_FORMATTER1.format(3.6f * trackingState.waypoint.speed));
accuracyView.setText(REAL_FORMATTER1.format(trackingState.waypoint.accuracy));
distanceView.setText(REAL_FORMATTER2.format(trackingState.distance / 1000f));
}
finally
{
}
}
private String formatTimeNum(long n)
{
return n < 10 ? ("0" + n) : (n + "");
}
private void drawRoadRating()
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
roadRatingButtons[i].setBackgroundColor(COLOR_WHITE);
}
if (trackingState.roadRating >= 0)
{
roadRatingButtons[trackingState.roadRating].setBackgroundColor(ROAD_RATING_COLORS[trackingState.roadRating]);
}
String roadRatingStr = trackingState.roadRating + "";
roadRatingView.setText(roadRatingStr);
}
private void showAlert(int aMessage)
{
new AlertDialog.Builder(this)
.setMessage(aMessage)
.setPositiveButton("Ok", null)
.show();
}
private void updateBlankingBehavior()
{
boolean disableblanking = sharedPreferences.getBoolean(Constants.DISABLEBLANKING, false);
if (disableblanking)
{
/* if (wakeLock == null)
{
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
}
wakeLock.acquire();
Log.w(TAG, "Acquired lock to keep screen on!"); */
}
}
private final DialogInterface.OnClickListener mOiAboutDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.about");
Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiAboutIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/AboutApp-1.0.0.apk");
oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiAboutIntent);
}
}
};
private final DialogInterface.OnClickListener mOpenGPSTrackerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri marketUri = Uri.parse("market://details?id=nl.sogeti.android.gpstracker");
Intent downloadIntent = new Intent(Intent.ACTION_VIEW, marketUri);
try
{
startActivity(downloadIntent);
}
catch (ActivityNotFoundException e)
{
showAlert(R.string.dialog_failinstallopengpstracker_message);
}
}
};
// Create an anonymous implementation of OnClickListener
private View.OnClickListener roadRatingButtonListener = new View.OnClickListener()
{
public void onClick(View v)
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
if (v.getId() == roadRatingButtons[i].getId())
{
trackingState.roadRating = i;
}
}
trackingState.newRoadRating = true;
drawRoadRating();
sendRoadRating();
}
};
private final ContentObserver trackingObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
onTrackingUpdate();
Log.d(TAG, "trackingObserver onTrackingUpdate lastWaypointId=" + trackingState.waypoint.id);
} else
{
Log.w(TAG, "trackingObserver skipping change");
}
}
};
private final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(Constants.DISABLEBLANKING))
{
updateBlankingBehavior();
}
}
};
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched;
public class Config {
// General configuration
public static final int CONFERENCE_YEAR = 2013;
// OAuth 2.0 related config
public static final String APP_NAME = "GoogleIO-Android";
// TODO: Add your Google API key here.
public static final String API_KEY = "YOUR_API_KEY_HERE";
// Conference API-specific config
public static final String EVENT_ID = "googleio2013";
public static final String CONFERENCE_IMAGE_PREFIX_URL = "https://developers.google.com";
// Announcements
public static final String ANNOUNCEMENTS_PLUS_ID = "111395306401981598462";
// Static file host for the map data
public static final String GET_MAP_URL = "http://2013.ioschedmap.appspot.com/map.json";
// YouTube API config
// TODO: Add your YouTube API key here.
public static final String YOUTUBE_API_KEY = "YOUR_API_KEY_HERE";
// YouTube share URL
public static final String YOUTUBE_SHARE_URL_PREFIX = "http://youtu.be/";
// Livestream captions config
public static final String PRIMARY_LIVESTREAM_CAPTIONS_URL =
"http://io-captions.appspot.com/?event=e1&android=t";
public static final String SECONDARY_LIVESTREAM_CAPTIONS_URL =
"http://io-captions.appspot.com/?event=e2&android=t";
public static final String PRIMARY_LIVESTREAM_TRACK = "android";
public static final String SECONDARY_LIVESTREAM_TRACK = "chrome";
// Conference public WiFi AP parameters
public static final String WIFI_SSID = "Google5G";
public static final String WIFI_PASSPHRASE = "gomobileio";
// GCM config
// TODO: Add your GCM information here.
public static final String GCM_SERVER_URL = "https://YOUR_GCM_APP_ID_HERE.appspot.com";
public static final String GCM_SENDER_ID = "YOUR_GCM_SENDER_ID_HERE";
public static final String GCM_API_KEY = "YOUR_GCM_API_KEY_HERE";
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.service;
import android.app.Service;
import android.content.Intent;
import android.os.*;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.gcm.ServerUtilities;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.util.AccountUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.turbomanage.httpclient.AsyncCallback;
import com.turbomanage.httpclient.HttpResponse;
import com.turbomanage.httpclient.ParameterMap;
import com.turbomanage.httpclient.android.AndroidHttpClient;
import static com.google.android.apps.iosched.util.LogUtils.*;
/**
* Background {@link android.app.Service} that adds or removes sessions from your calendar via the
* Conference API.
*
* @see com.google.android.apps.iosched.sync.SyncHelper
*/
public class ScheduleUpdaterService extends Service {
private static final String TAG = makeLogTag(ScheduleUpdaterService.class);
public static final String EXTRA_SESSION_ID
= "com.google.android.apps.iosched.extra.SESSION_ID";
public static final String EXTRA_IN_SCHEDULE
= "com.google.android.apps.iosched.extra.IN_SCHEDULE";
private static final int SCHEDULE_UPDATE_DELAY_MILLIS = 5000;
private volatile Looper mServiceLooper;
private volatile ServiceHandler mServiceHandler;
private final LinkedList<Intent> mScheduleUpdates = new LinkedList<Intent>();
// Handler pattern copied from IntentService
private final class ServiceHandler extends Handler {
public ServiceHandler(Looper looper) {
super(looper);
}
@Override
public void handleMessage(Message msg) {
processPendingScheduleUpdates();
int numRemainingUpdates;
synchronized (mScheduleUpdates) {
numRemainingUpdates = mScheduleUpdates.size();
}
if (numRemainingUpdates == 0) {
notifyGcmDevices();
stopSelf();
} else {
// More updates were added since the current pending set was processed. Reschedule
// another pass.
removeMessages(0);
sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS);
}
}
}
// private static class NotifyGcmDevicesTask extends AsyncTask<String, Void, Void> {
//
// @Override
// protected Void doInBackground(String... params) {
// BasicHttp
// String gPlusID = params[0];
// Uri uri = new Uri(Config.GCM_SERVER_URL + "/send/" + gPlusID + "/sync_user");
// connection = (HttpURLConnection) url.openConnection();
// connection.setDoOutput(true);
// connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");
// connection.setRequestMethod("POST");
//
// request = new OutputStreamWriter(connection.getOutputStream());
// request.write(parameters);
// request.flush();
// request.close();
//
// }
// }
private void notifyGcmDevices() {
String plusID = AccountUtils.getPlusProfileId(getApplicationContext());
if (plusID != null) {
LOGI(TAG, "Sending device sync notification");
AndroidHttpClient httpClient = new AndroidHttpClient(Config.GCM_SERVER_URL);
httpClient.setMaxRetries(1);
ParameterMap params = httpClient.newParams()
.add("key", Config.GCM_API_KEY)
.add("squelch", ServerUtilities.getGcmId(this));
String path = "/send/" + plusID + "/sync_user";
httpClient.post(path, params, new AsyncCallback() {
@Override
public void onComplete(HttpResponse httpResponse) {
LOGI(TAG, "Device sync notification sent");
}
@Override
public void onError(Exception e) {
LOGW(TAG, "Device sync notification failed", e);
}
});
} else {
LOGI(TAG, "No gPlusID, skipping device sync notification");
}
}
public ScheduleUpdaterService() {
}
@Override
public void onCreate() {
super.onCreate();
HandlerThread thread = new HandlerThread(ScheduleUpdaterService.class.getSimpleName());
thread.start();
mServiceLooper = thread.getLooper();
mServiceHandler = new ServiceHandler(mServiceLooper);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// When receiving a new intent, delay the schedule until 5 seconds from now.
mServiceHandler.removeMessages(0);
mServiceHandler.sendEmptyMessageDelayed(0, SCHEDULE_UPDATE_DELAY_MILLIS);
// Remove pending updates involving this session ID.
String sessionId = intent.getStringExtra(EXTRA_SESSION_ID);
Iterator<Intent> updatesIterator = mScheduleUpdates.iterator();
while (updatesIterator.hasNext()) {
Intent existingIntent = updatesIterator.next();
if (sessionId.equals(existingIntent.getStringExtra(EXTRA_SESSION_ID))) {
updatesIterator.remove();
}
}
// Queue this schedule update.
synchronized (mScheduleUpdates) {
mScheduleUpdates.add(intent);
}
return START_REDELIVER_INTENT;
}
@Override
public void onDestroy() {
mServiceLooper.quit();
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
void processPendingScheduleUpdates() {
try {
// Operate on a local copy of the schedule update list so as not to block
// the main thread adding to this list
List<Intent> scheduleUpdates = new ArrayList<Intent>();
synchronized (mScheduleUpdates) {
scheduleUpdates.addAll(mScheduleUpdates);
mScheduleUpdates.clear();
}
SyncHelper syncHelper = new SyncHelper(this);
for (Intent updateIntent : scheduleUpdates) {
String sessionId = updateIntent.getStringExtra(EXTRA_SESSION_ID);
boolean inSchedule = updateIntent.getBooleanExtra(EXTRA_IN_SCHEDULE, false);
LOGI(TAG, "addOrRemoveSessionFromSchedule:"
+ " sessionId=" + sessionId
+ " inSchedule=" + inSchedule);
syncHelper.addOrRemoveSessionFromSchedule(this, sessionId, inSchedule);
}
} catch (IOException e) {
// TODO: do something useful here, like revert the changes locally in the
// content provider to maintain client/server sync
LOGE(TAG, "Error processing schedule update", e);
}
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.service;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.text.format.DateUtils;
import com.google.android.apps.dashclock.api.ExtensionData;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.UIUtils;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import static com.google.android.apps.iosched.util.LogUtils.LOGD;
import static com.google.android.apps.iosched.util.LogUtils.LOGE;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* An I/O 2013 extension for DashClock.
*/
public class DashClockExtension extends com.google.android.apps.dashclock.api.DashClockExtension {
private static final String TAG = makeLogTag(DashClockExtension.class);
private static final long MINUTE_MILLIS = 60 * 1000;
private static final long NOW_BUFFER_TIME_MILLIS = 15 * MINUTE_MILLIS;
private static final int MAX_BLOCKS = 5;
private static final long CONTENT_CHANGE_DELAY_MILLIS = 5 * 1000;
private static long mLastChange = 0;
@Override
protected void onInitialize(boolean isReconnect) {
super.onInitialize(isReconnect);
setUpdateWhenScreenOn(true);
addWatchContentUris(new String[]{
ScheduleContract.Sessions.CONTENT_URI.toString()
});
}
@Override
protected void onUpdateData(int reason) {
if (reason == DashClockExtension.UPDATE_REASON_CONTENT_CHANGED) {
long time = System.currentTimeMillis();
if (time < mLastChange + CONTENT_CHANGE_DELAY_MILLIS) {
return;
}
mLastChange = time;
}
long currentTime = UIUtils.getCurrentTime(this);
if (currentTime >= UIUtils.CONFERENCE_END_MILLIS) {
publishUpdate(new ExtensionData()
.visible(true)
.icon(R.drawable.dashclock_extension)
.status(getString(R.string.whats_on_thank_you_short))
.expandedTitle(getString(R.string.whats_on_thank_you_title))
.expandedBody(getString(R.string.whats_on_thank_you_subtitle))
.clickIntent(new Intent(this, HomeActivity.class)));
return;
}
Cursor cursor = tryOpenBlocksCursor();
if (cursor == null) {
LOGE(TAG, "Null blocks cursor, short-circuiting.");
return;
}
StringBuilder buffer = new StringBuilder();
Formatter formatter = new Formatter(buffer, Locale.getDefault());
String firstBlockStartTime = null;
List<String> blocks = new ArrayList<String>();
long lastBlockStart = 0;
while (cursor.moveToNext()) {
if (blocks.size() >= MAX_BLOCKS) {
break;
}
final String type = cursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockTitle = cursor.getString(BlocksQuery.BLOCK_TITLE);
final String blockType = cursor.getString(BlocksQuery.BLOCK_TYPE);
final long blockStart = cursor.getLong(BlocksQuery.BLOCK_START);
buffer.setLength(0);
boolean showWeekday = !DateUtils.isToday(blockStart)
&& !UIUtils.isSameDayDisplay(lastBlockStart, blockStart, this);
String blockStartTime = DateUtils.formatDateRange(this, formatter,
blockStart, blockStart,
DateUtils.FORMAT_SHOW_TIME | (showWeekday
? DateUtils.FORMAT_SHOW_WEEKDAY | DateUtils.FORMAT_ABBREV_WEEKDAY
: 0),
PrefUtils.getDisplayTimeZone(this).getID()).toString();
lastBlockStart = blockStart;
if (firstBlockStartTime == null) {
firstBlockStartTime = blockStartTime;
}
if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type)
|| ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type)
|| ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) {
final int numStarredSessions = cursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS);
if (numStarredSessions == 1) {
// exactly 1 session starred
String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
String room = cursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME);
if (room == null) {
room = getString(R.string.unknown_room);
}
blocks.add(blockStartTime + ", " + room + " — " + title);
} else {
// 2 or more sessions starred
String title = getString(R.string.schedule_conflict_title,
numStarredSessions);
blocks.add(blockStartTime + " — " + title);
}
} else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) {
final String title = cursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
blocks.add(blockStartTime + " — " + title);
} else {
blocks.add(blockStartTime + " — " + blockTitle);
}
}
cursor.close();
LOGD(TAG, blocks.size() + " blocks");
if (blocks.size() > 0) {
publishUpdate(new ExtensionData()
.visible(true)
.icon(R.drawable.dashclock_extension)
.status(firstBlockStartTime)
.expandedTitle(blocks.get(0))
.expandedBody(TextUtils.join("\n", blocks.subList(1, blocks.size())))
.clickIntent(new Intent(this, HomeActivity.class)));
} else {
publishUpdate(new ExtensionData().visible(false));
}
}
private Cursor tryOpenBlocksCursor() {
try {
String liveStreamedOnlyBlocksSelection = "("
+ (UIUtils.shouldShowLiveSessionsOnly(this)
? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('"
+ ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')"
+ " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 "
: "1==1") + ")";
String onlyStarredSelection = "("
+ ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('"
+ ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "') "
+ " OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)";
String excludeSandbox = ScheduleContract.Blocks.BLOCK_TYPE + " != '"
+ ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX + "'";
return getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI,
BlocksQuery.PROJECTION,
ScheduleContract.Blocks.BLOCK_START + " >= ? AND "
+ liveStreamedOnlyBlocksSelection + " AND "
+ onlyStarredSelection + " AND "
+ excludeSandbox,
new String[]{
Long.toString(UIUtils.getCurrentTime(this) - NOW_BUFFER_TIME_MILLIS)
},
ScheduleContract.Blocks.DEFAULT_SORT);
} catch (Exception e) {
LOGE(TAG, "Error querying I/O 2013 content provider", e);
return null;
}
}
public interface BlocksQuery {
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Blocks.BLOCK_TITLE,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_TYPE,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Blocks.STARRED_SESSION_TITLE,
ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME,
ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS,
};
int _ID = 0;
int BLOCK_TITLE = 1;
int BLOCK_START = 2;
int BLOCK_TYPE = 3;
int NUM_STARRED_SESSIONS = 4;
int STARRED_SESSION_TITLE = 5;
int STARRED_SESSION_ROOM_NAME = 6;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.service;
import android.graphics.Bitmap;
import android.provider.BaseColumns;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.ui.MapFragment;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.SessionsHelper;
import com.google.android.apps.iosched.util.UIUtils;
import android.app.AlarmManager;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.net.Uri;
import android.support.v4.app.NotificationCompat;
import android.support.v4.app.TaskStackBuilder;
import java.util.ArrayList;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* Background service to handle scheduling of starred session notification via
* {@link android.app.AlarmManager}.
*/
public class SessionAlarmService extends IntentService {
private static final String TAG = makeLogTag(SessionAlarmService.class);
public static final String ACTION_NOTIFY_SESSION =
"com.google.android.apps.iosched.action.NOTIFY_SESSION";
public static final String ACTION_SCHEDULE_STARRED_BLOCK =
"com.google.android.apps.iosched.action.SCHEDULE_STARRED_BLOCK";
public static final String ACTION_SCHEDULE_ALL_STARRED_BLOCKS =
"com.google.android.apps.iosched.action.SCHEDULE_ALL_STARRED_BLOCKS";
public static final String EXTRA_SESSION_START =
"com.google.android.apps.iosched.extra.SESSION_START";
public static final String EXTRA_SESSION_END =
"com.google.android.apps.iosched.extra.SESSION_END";
public static final String EXTRA_SESSION_ALARM_OFFSET =
"com.google.android.apps.iosched.extra.SESSION_ALARM_OFFSET";
private static final int NOTIFICATION_ID = 100;
// pulsate every 1 second, indicating a relatively high degree of urgency
private static final int NOTIFICATION_LED_ON_MS = 100;
private static final int NOTIFICATION_LED_OFF_MS = 1000;
private static final int NOTIFICATION_ARGB_COLOR = 0xff0088ff; // cyan
private static final long MILLI_TEN_MINUTES = 600000;
private static final long MILLI_ONE_MINUTE = 60000;
private static final long UNDEFINED_ALARM_OFFSET = -1;
private static final long UNDEFINED_VALUE = -1;
public SessionAlarmService() {
super(TAG);
}
@Override
protected void onHandleIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION_SCHEDULE_ALL_STARRED_BLOCKS.equals(action)) {
scheduleAllStarredBlocks();
return;
}
final long sessionStart =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_START, UNDEFINED_VALUE);
if (sessionStart == UNDEFINED_VALUE) return;
final long sessionEnd =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_END, UNDEFINED_VALUE);
if (sessionEnd == UNDEFINED_VALUE) return;
final long sessionAlarmOffset =
intent.getLongExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
UNDEFINED_ALARM_OFFSET);
if (ACTION_NOTIFY_SESSION.equals(action)) {
notifySession(sessionStart, sessionEnd, sessionAlarmOffset);
} else if (ACTION_SCHEDULE_STARRED_BLOCK.equals(action)) {
scheduleAlarm(sessionStart, sessionEnd, sessionAlarmOffset);
}
}
private void scheduleAlarm(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
NotificationManager nm =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.cancel(NOTIFICATION_ID);
final long currentTime = UIUtils.getCurrentTime(this);
// If the session is already started, do not schedule system notification.
if (currentTime > sessionStart) return;
// By default, sets alarm to go off at 10 minutes before session start time. If alarm
// offset is provided, alarm is set to go off by that much time from now.
long alarmTime;
if (alarmOffset == UNDEFINED_ALARM_OFFSET) {
alarmTime = sessionStart - MILLI_TEN_MINUTES;
} else {
alarmTime = currentTime + alarmOffset;
}
final Intent notifIntent = new Intent(
ACTION_NOTIFY_SESSION,
null,
this,
SessionAlarmService.class);
// Setting data to ensure intent's uniqueness for different session start times.
notifIntent.setData(
new Uri.Builder().authority("com.google.android.apps.iosched")
.path(String.valueOf(sessionStart)).build());
notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
notifIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET, alarmOffset);
PendingIntent pi = PendingIntent.getService(this,
0,
notifIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
final AlarmManager am = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
// Schedule an alarm to be fired to notify user of added sessions are about to begin.
am.set(AlarmManager.RTC_WAKEUP, alarmTime, pi);
}
// Starred sessions are about to begin. Constructs and triggers system notification.
private void notifySession(final long sessionStart,
final long sessionEnd, final long alarmOffset) {
long currentTime;
if (sessionStart < (currentTime = UIUtils.getCurrentTime(this))) return;
// Avoid repeated notifications.
if (alarmOffset == UNDEFINED_ALARM_OFFSET && UIUtils.isNotificationFiredForBlock(
this, ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd))) {
return;
}
final ContentResolver cr = getContentResolver();
final Uri starredBlockUri = ScheduleContract.Blocks.buildStarredSessionsUri(
ScheduleContract.Blocks.generateBlockId(sessionStart, sessionEnd)
);
Cursor c = cr.query(starredBlockUri,
SessionDetailQuery.PROJECTION,
null,
null,
null);
int starredCount = 0;
ArrayList<String> starredSessionTitles = new ArrayList<String>();
ArrayList<String> starredSessionRoomIds = new ArrayList<String>();
String sessionId = null; // needed to get session track icon
while (c.moveToNext()) {
sessionId = c.getString(SessionDetailQuery.SESSION_ID);
starredCount = c.getInt(SessionDetailQuery.NUM_STARRED_SESSIONS);
starredSessionTitles.add(c.getString(SessionDetailQuery.SESSION_TITLE));
starredSessionRoomIds.add(c.getString(SessionDetailQuery.ROOM_ID));
}
if (starredCount < 1) {
return;
}
// Generates the pending intent which gets fired when the user taps on the notification.
// NOTE: Use TaskStackBuilder to comply with Android's design guidelines
// related to navigation from notifications.
PendingIntent pi = TaskStackBuilder.create(this)
.addNextIntent(new Intent(this, HomeActivity.class))
.addNextIntent(new Intent(Intent.ACTION_VIEW, starredBlockUri))
.getPendingIntent(0, PendingIntent.FLAG_CANCEL_CURRENT);
final Resources res = getResources();
String contentText;
int minutesLeft = (int) (sessionStart - currentTime + 59000) / 60000;
if (minutesLeft < 1) {
minutesLeft = 1;
}
if (starredCount == 1) {
contentText = res.getString(R.string.session_notification_text_1, minutesLeft);
} else {
contentText = res.getQuantityString(R.plurals.session_notification_text,
starredCount - 1,
minutesLeft,
starredCount - 1);
}
NotificationCompat.Builder notifBuilder = new NotificationCompat.Builder(this)
.setContentTitle(starredSessionTitles.get(0))
.setContentText(contentText)
.setTicker(res.getQuantityString(R.plurals.session_notification_ticker,
starredCount,
starredCount))
.setDefaults(Notification.DEFAULT_SOUND | Notification.DEFAULT_VIBRATE)
.setLights(
SessionAlarmService.NOTIFICATION_ARGB_COLOR,
SessionAlarmService.NOTIFICATION_LED_ON_MS,
SessionAlarmService.NOTIFICATION_LED_OFF_MS)
.setSmallIcon(R.drawable.ic_stat_notification)
.setContentIntent(pi)
.setPriority(Notification.PRIORITY_MAX)
.setAutoCancel(true);
if (starredCount == 1) {
// get the track icon to show as the notification big picture
Uri tracksUri = ScheduleContract.Sessions.buildTracksDirUri(sessionId);
Cursor tracksCursor = cr.query(tracksUri, SessionTrackQuery.PROJECTION,
null, null, null);
if (tracksCursor.moveToFirst()) {
String trackName = tracksCursor.getString(SessionTrackQuery.TRACK_NAME);
int trackColour = tracksCursor.getInt(SessionTrackQuery.TRACK_COLOR);
Bitmap trackIcon = UIUtils.getTrackIconSync(getApplicationContext(),
trackName, trackColour);
if (trackIcon != null) {
notifBuilder.setLargeIcon(trackIcon);
}
}
}
if (minutesLeft > 5) {
notifBuilder.addAction(R.drawable.ic_alarm_holo_dark,
String.format(res.getString(R.string.snooze_x_min), 5),
createSnoozeIntent(sessionStart, sessionEnd, 5));
}
if (starredCount == 1 && PrefUtils.isAttendeeAtVenue(this)) {
notifBuilder.addAction(R.drawable.ic_map_holo_dark,
res.getString(R.string.title_map),
createRoomMapIntent(starredSessionRoomIds.get(0)));
}
NotificationCompat.InboxStyle richNotification = new NotificationCompat.InboxStyle(
notifBuilder)
.setBigContentTitle(res.getQuantityString(R.plurals.session_notification_title,
starredCount,
minutesLeft,
starredCount));
// Adds starred sessions starting at this time block to the notification.
for (int i = 0; i < starredCount; i++) {
richNotification.addLine(starredSessionTitles.get(i));
}
NotificationManager nm = (NotificationManager) getSystemService(
Context.NOTIFICATION_SERVICE);
nm.notify(NOTIFICATION_ID, richNotification.build());
}
private PendingIntent createSnoozeIntent(final long sessionStart, final long sessionEnd,
final int snoozeMinutes) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_STARRED_BLOCK,
null, this, SessionAlarmService.class);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_START, sessionStart);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_END, sessionEnd);
scheduleIntent.putExtra(SessionAlarmService.EXTRA_SESSION_ALARM_OFFSET,
snoozeMinutes * MILLI_ONE_MINUTE);
return PendingIntent.getService(this, 0, scheduleIntent,
PendingIntent.FLAG_CANCEL_CURRENT);
}
private PendingIntent createRoomMapIntent(final String roomId) {
Intent mapIntent = new Intent(getApplicationContext(),
UIUtils.getMapActivityClass(getApplicationContext()));
mapIntent.putExtra(MapFragment.EXTRA_ROOM, roomId);
return PendingIntent.getActivity(this, 0, mapIntent, 0);
}
private void scheduleAllStarredBlocks() {
final ContentResolver cr = getContentResolver();
final Cursor c = cr.query(ScheduleContract.Sessions.CONTENT_STARRED_URI,
new String[]{"distinct " + ScheduleContract.Sessions.BLOCK_START,
ScheduleContract.Sessions.BLOCK_END},
null,
null,
null);
if (c == null) {
return;
}
while (c.moveToNext()) {
final long sessionStart = c.getLong(0);
final long sessionEnd = c.getLong(1);
scheduleAlarm(sessionStart, sessionEnd, UNDEFINED_ALARM_OFFSET);
}
}
public interface SessionDetailQuery {
String[] PROJECTION = {
ScheduleContract.Sessions.SESSION_ID,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Sessions.SESSION_TITLE,
ScheduleContract.Sessions.ROOM_ID
};
int SESSION_ID = 0;
int NUM_STARRED_SESSIONS = 1;
int SESSION_TITLE = 2;
int ROOM_ID = 3;
}
public interface SessionTrackQuery {
String[] PROJECTION = {
ScheduleContract.Tracks.TRACK_ID,
ScheduleContract.Tracks.TRACK_NAME,
ScheduleContract.Tracks.TRACK_COLOR
};
int TRACK_ID = 0;
int TRACK_NAME = 1;
int TRACK_COLOR = 2;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.receiver;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import com.google.android.apps.iosched.service.SessionAlarmService;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* {@link BroadcastReceiver} to reinitialize {@link android.app.AlarmManager} for all starred
* session blocks.
*/
public class SessionAlarmReceiver extends BroadcastReceiver {
public static final String TAG = makeLogTag(SessionAlarmReceiver.class);
@Override
public void onReceive(Context context, Intent intent) {
Intent scheduleIntent = new Intent(
SessionAlarmService.ACTION_SCHEDULE_ALL_STARRED_BLOCKS,
null, context, SessionAlarmService.class);
context.startService(scheduleIntent);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
import android.accounts.Account;
import android.content.*;
import android.database.Cursor;
import android.net.ConnectivityManager;
import android.os.Bundle;
import android.os.RemoteException;
import android.preference.PreferenceManager;
import com.google.analytics.tracking.android.GAServiceManager;
import com.google.android.apps.iosched.Config;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.io.*;
import com.google.android.apps.iosched.io.map.model.Tile;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.*;
import com.google.api.client.googleapis.auth.oauth2.GoogleCredential;
import com.google.api.client.googleapis.json.GoogleJsonResponseException;
import com.google.api.client.googleapis.services.CommonGoogleClientRequestInitializer;
import com.google.api.client.http.HttpTransport;
import com.google.api.client.http.javanet.NetHttpTransport;
import com.google.api.client.json.JsonFactory;
import com.google.api.client.json.gson.GsonFactory;
import com.google.api.services.googledevelopers.Googledevelopers;
import java.io.*;
import java.net.HttpURLConnection;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import com.larvalabs.svgandroid.SVG;
import com.larvalabs.svgandroid.SVGParseException;
import com.larvalabs.svgandroid.SVGParser;
import com.turbomanage.httpclient.BasicHttpClient;
import com.turbomanage.httpclient.ConsoleRequestLogger;
import com.turbomanage.httpclient.HttpResponse;
import com.turbomanage.httpclient.RequestLogger;
import static com.google.android.apps.iosched.util.LogUtils.*;
/**
* A helper class for dealing with sync and other remote persistence operations.
* All operations occur on the thread they're called from, so it's best to wrap
* calls in an {@link android.os.AsyncTask}, or better yet, a
* {@link android.app.Service}.
*/
public class SyncHelper {
private static final String TAG = makeLogTag(SyncHelper.class);
public static final int FLAG_SYNC_LOCAL = 0x1;
public static final int FLAG_SYNC_REMOTE = 0x2;
private static final int LOCAL_VERSION_CURRENT = 25;
private static final String LOCAL_MAPVERSION_CURRENT = "\"vlh7Ig\"";
private Context mContext;
public SyncHelper(Context context) {
mContext = context;
}
public static void requestManualSync(Account mChosenAccount) {
Bundle b = new Bundle();
b.putBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, true);
ContentResolver.requestSync(
mChosenAccount,
ScheduleContract.CONTENT_AUTHORITY, b);
}
/**
* Loads conference information (sessions, rooms, tracks, speakers, etc.)
* from a local static cache data and then syncs down data from the
* Conference API.
*
* @param syncResult Optional {@link SyncResult} object to populate.
* @throws IOException
*/
public void performSync(SyncResult syncResult, int flags) throws IOException {
final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(mContext);
final int localVersion = prefs.getInt("local_data_version", 0);
// Bulk of sync work, performed by executing several fetches from
// local and online sources.
final ContentResolver resolver = mContext.getContentResolver();
ArrayList<ContentProviderOperation> batch = new ArrayList<ContentProviderOperation>();
LOGI(TAG, "Performing sync");
if ((flags & FLAG_SYNC_LOCAL) != 0) {
final long startLocal = System.currentTimeMillis();
final boolean localParse = localVersion < LOCAL_VERSION_CURRENT;
LOGD(TAG, "found localVersion=" + localVersion + " and LOCAL_VERSION_CURRENT="
+ LOCAL_VERSION_CURRENT);
// Only run local sync if there's a newer version of data available
// than what was last locally-sync'd.
if (localParse) {
// Load static local data
LOGI(TAG, "Local syncing rooms");
batch.addAll(new RoomsHandler(mContext).parse(
JSONHandler.parseResource(mContext, R.raw.rooms)));
LOGI(TAG, "Local syncing blocks");
batch.addAll(new BlocksHandler(mContext).parse(
JSONHandler.parseResource(mContext, R.raw.common_slots)));
LOGI(TAG, "Local syncing tracks");
batch.addAll(new TracksHandler(mContext).parse(
JSONHandler.parseResource(mContext, R.raw.tracks)));
LOGI(TAG, "Local syncing speakers");
batch.addAll(new SpeakersHandler(mContext).parseString(
JSONHandler.parseResource(mContext, R.raw.speakers)));
LOGI(TAG, "Local syncing sessions");
batch.addAll(new SessionsHandler(mContext).parseString(
JSONHandler.parseResource(mContext, R.raw.sessions),
JSONHandler.parseResource(mContext, R.raw.session_tracks)));
LOGI(TAG, "Local syncing search suggestions");
batch.addAll(new SearchSuggestHandler(mContext).parse(
JSONHandler.parseResource(mContext, R.raw.search_suggest)));
LOGI(TAG, "Local syncing map");
MapPropertyHandler mapHandler = new MapPropertyHandler(mContext);
batch.addAll(mapHandler.parse(
JSONHandler.parseResource(mContext, R.raw.map)));
//need to sync tile files before data is updated in content provider
syncMapTiles(mapHandler.getTiles());
prefs.edit().putInt("local_data_version", LOCAL_VERSION_CURRENT).commit();
prefs.edit().putString("local_mapdata_version", LOCAL_MAPVERSION_CURRENT).commit();
if (syncResult != null) {
++syncResult.stats.numUpdates; // TODO: better way of indicating progress?
++syncResult.stats.numEntries;
}
}
LOGD(TAG, "Local sync took " + (System.currentTimeMillis() - startLocal) + "ms");
try {
// Apply all queued up batch operations for local data.
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
batch = new ArrayList<ContentProviderOperation>();
}
if ((flags & FLAG_SYNC_REMOTE) != 0 && isOnline()) {
try {
Googledevelopers conferenceAPI = getConferenceAPIClient();
final long startRemote = System.currentTimeMillis();
LOGI(TAG, "Remote syncing announcements");
batch.addAll(new AnnouncementsFetcher(mContext).fetchAndParse());
LOGI(TAG, "Remote syncing speakers");
batch.addAll(new SpeakersHandler(mContext).fetchAndParse(conferenceAPI));
LOGI(TAG, "Remote syncing sessions");
batch.addAll(new SessionsHandler(mContext).fetchAndParse(conferenceAPI));
// Map sync
batch.addAll(remoteSyncMapData(Config.GET_MAP_URL,prefs));
LOGD(TAG, "Remote sync took " + (System.currentTimeMillis() - startRemote) + "ms");
if (syncResult != null) {
++syncResult.stats.numUpdates; // TODO: better way of indicating progress?
++syncResult.stats.numEntries;
}
GAServiceManager.getInstance().dispatch();
// Sync feedback stuff
LOGI(TAG, "Syncing session feedback");
batch.addAll(new FeedbackHandler(mContext).uploadNew(conferenceAPI));
} catch (GoogleJsonResponseException e) {
if (e.getStatusCode() == 401) {
LOGI(TAG, "Unauthorized; getting a new auth token.", e);
if (syncResult != null) {
++syncResult.stats.numAuthExceptions;
}
AccountUtils.refreshAuthToken(mContext);
}
}
// all other IOExceptions are thrown
LOGI(TAG, "Sync complete");
}
try {
// Apply all queued up remaining batch operations (only remote content at this point).
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
// Update search index
resolver.update(ScheduleContract.SearchIndex.CONTENT_URI, new ContentValues(),
null, null);
// Delete empty blocks
Cursor emptyBlocksCursor = resolver.query(ScheduleContract.Blocks.CONTENT_URI,
new String[]{ScheduleContract.Blocks.BLOCK_ID,ScheduleContract.Blocks.SESSIONS_COUNT},
ScheduleContract.Blocks.EMPTY_SESSIONS_SELECTION, null, null);
batch = new ArrayList<ContentProviderOperation>();
int numDeletedEmptyBlocks = 0;
while (emptyBlocksCursor.moveToNext()) {
batch.add(ContentProviderOperation
.newDelete(ScheduleContract.Blocks.buildBlockUri(
emptyBlocksCursor.getString(0)))
.build());
++numDeletedEmptyBlocks;
}
emptyBlocksCursor.close();
resolver.applyBatch(ScheduleContract.CONTENT_AUTHORITY, batch);
LOGD(TAG, "Deleted " + numDeletedEmptyBlocks + " empty session blocks.");
} catch (RemoteException e) {
throw new RuntimeException("Problem applying batch operation", e);
} catch (OperationApplicationException e) {
throw new RuntimeException("Problem applying batch operation", e);
}
}
public void addOrRemoveSessionFromSchedule(Context context, String sessionId,
boolean inSchedule) throws IOException {
LOGI(TAG, "Updating session on user schedule: " + sessionId);
Googledevelopers conferenceAPI = getConferenceAPIClient();
try {
sendScheduleUpdate(conferenceAPI, context, sessionId, inSchedule);
} catch (GoogleJsonResponseException e) {
if (e.getDetails().getCode() == 401) {
LOGI(TAG, "Unauthorized; getting a new auth token.", e);
AccountUtils.refreshAuthToken(mContext);
// Try request one more time with new credentials before giving up
conferenceAPI = getConferenceAPIClient();
sendScheduleUpdate(conferenceAPI, context, sessionId, inSchedule);
}
}
}
private void sendScheduleUpdate(Googledevelopers conferenceAPI,
Context context, String sessionId, boolean inSchedule) throws IOException {
if (inSchedule) {
conferenceAPI.users().events().sessions().update(Config.EVENT_ID, sessionId, null).execute();
} else {
conferenceAPI.users().events().sessions().delete(Config.EVENT_ID, sessionId).execute();
}
}
private ArrayList<ContentProviderOperation> remoteSyncMapData(String urlString,
SharedPreferences preferences) throws IOException {
final String localVersion = preferences.getString("local_mapdata_version", null);
ArrayList<ContentProviderOperation> batch = Lists.newArrayList();
BasicHttpClient httpClient = new BasicHttpClient();
httpClient.setRequestLogger(mQuietLogger);
httpClient.addHeader("If-None-Match", localVersion);
LOGD(TAG,"Local map version: "+localVersion);
HttpResponse response = httpClient.get(urlString, null);
final int status = response.getStatus();
if (status == HttpURLConnection.HTTP_OK) {
// Data has been updated, otherwise would have received HTTP_NOT_MODIFIED
LOGI(TAG, "Remote syncing map data");
final List<String> etag = response.getHeaders().get("ETag");
if (etag != null && etag.size() > 0) {
MapPropertyHandler handler = new MapPropertyHandler(mContext);
batch.addAll(handler.parse(response.getBodyAsString()));
syncMapTiles(handler.getTiles());
// save new etag as version
preferences.edit().putString("local_mapdata_version", etag.get(0)).commit();
}
} //else: no update
return batch;
}
private boolean isOnline() {
ConnectivityManager cm = (ConnectivityManager) mContext.getSystemService(
Context.CONNECTIVITY_SERVICE);
return cm.getActiveNetworkInfo() != null &&
cm.getActiveNetworkInfo().isConnectedOrConnecting();
}
/**
* Synchronise the map overlay files either from the local assets (if available) or from a remote url.
*
* @param collection Set of tiles containing a local filename and remote url.
* @throws IOException
*/
private void syncMapTiles(Collection<Tile> collection) throws IOException, SVGParseException {
//keep track of used files, unused files are removed
ArrayList<String> usedTiles = Lists.newArrayList();
for(Tile tile : collection){
final String filename = tile.filename;
final String url = tile.url;
usedTiles.add(filename);
if (!MapUtils.hasTile(mContext, filename)) {
// copy or download the tile if it is not stored yet
if (MapUtils.hasTileAsset(mContext, filename)) {
// file already exists as an asset, copy it
MapUtils.copyTileAsset(mContext, filename);
} else {
// download the file
File tileFile = MapUtils.getTileFile(mContext, filename);
BasicHttpClient httpClient = new BasicHttpClient();
httpClient.setRequestLogger(mQuietLogger);
HttpResponse httpResponse = httpClient.get(url, null);
writeFile(httpResponse.getBody(), tileFile);
// ensure the file is valid SVG
InputStream is = new FileInputStream(tileFile);
SVG svg = SVGParser.getSVGFromInputStream(is);
is.close();
}
}
}
MapUtils.removeUnusedTiles(mContext, usedTiles);
}
/**
* Write the byte array directly to a file.
* @throws IOException
*/
private void writeFile(byte[] data, File file) throws IOException {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(file, false));
bos.write(data);
bos.close();
}
/**
* A type of ConsoleRequestLogger that does not log requests and responses.
*/
private RequestLogger mQuietLogger = new ConsoleRequestLogger(){
@Override
public void logRequest(HttpURLConnection uc, Object content) throws IOException { }
@Override
public void logResponse(HttpResponse res) { }
};
private Googledevelopers getConferenceAPIClient() {
HttpTransport httpTransport = new NetHttpTransport();
JsonFactory jsonFactory = new GsonFactory();
GoogleCredential credential =
new GoogleCredential().setAccessToken(AccountUtils.getAuthToken(mContext));
// Note: The Googledevelopers API is unique, in that it requires an API key in addition to the client
// ID normally embedded an an OAuth token. Most apps will use one or the other.
return new Googledevelopers.Builder(httpTransport, jsonFactory, null)
.setApplicationName(NetUtils.getUserAgent(mContext))
.setGoogleClientRequestInitializer(new
CommonGoogleClientRequestInitializer(Config.API_KEY))
.setHttpRequestInitializer(credential)
.build();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
/**
* Service that handles sync. It simply instantiates a SyncAdapter and returns its IBinder.
*/
public class SyncService extends Service {
private static final Object sSyncAdapterLock = new Object();
private static SyncAdapter sSyncAdapter = null;
@Override
public void onCreate() {
synchronized (sSyncAdapterLock) {
if (sSyncAdapter == null) {
sSyncAdapter = new SyncAdapter(getApplicationContext(), false);
}
}
}
@Override
public IBinder onBind(Intent intent) {
return sSyncAdapter.getSyncAdapterBinder();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.gms.auth.GoogleAuthUtil;
import android.accounts.Account;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
/**
* A simple {@link BroadcastReceiver} that triggers a sync. This is used by the GCM code to trigger
* jittered syncs using {@link android.app.AlarmManager}.
*/
public class TriggerSyncReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String accountName = AccountUtils.getChosenAccountName(context);
if (TextUtils.isEmpty(accountName)) {
return;
}
ContentResolver.requestSync(
AccountUtils.getChosenAccount(context),
ScheduleContract.CONTENT_AUTHORITY, new Bundle());
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.sync;
import com.google.android.apps.iosched.BuildConfig;
import com.google.android.apps.iosched.util.AccountUtils;
import android.accounts.Account;
import android.content.AbstractThreadedSyncAdapter;
import android.content.ContentProviderClient;
import android.content.ContentResolver;
import android.content.Context;
import android.content.SyncResult;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.widget.Toast;
import java.io.IOException;
import java.util.regex.Pattern;
import static com.google.android.apps.iosched.util.LogUtils.*;
/**
* Sync adapter for Google I/O data
*/
public class SyncAdapter extends AbstractThreadedSyncAdapter {
private static final String TAG = makeLogTag(SyncAdapter.class);
private static final Pattern sSanitizeAccountNamePattern = Pattern.compile("(.).*?(.?)@");
private final Context mContext;
private SyncHelper mSyncHelper;
public SyncAdapter(Context context, boolean autoInitialize) {
super(context, autoInitialize);
mContext = context;
//noinspection ConstantConditions,PointlessBooleanExpression
if (!BuildConfig.DEBUG) {
Thread.setDefaultUncaughtExceptionHandler(new Thread.UncaughtExceptionHandler() {
@Override
public void uncaughtException(Thread thread, Throwable throwable) {
LOGE(TAG, "Uncaught sync exception, suppressing UI in release build.",
throwable);
}
});
}
}
@Override
public void onPerformSync(final Account account, Bundle extras, String authority,
final ContentProviderClient provider, final SyncResult syncResult) {
final boolean uploadOnly = extras.getBoolean(ContentResolver.SYNC_EXTRAS_UPLOAD, false);
final boolean manualSync = extras.getBoolean(ContentResolver.SYNC_EXTRAS_MANUAL, false);
final boolean initialize = extras.getBoolean(ContentResolver.SYNC_EXTRAS_INITIALIZE, false);
final String logSanitizedAccountName = sSanitizeAccountNamePattern
.matcher(account.name).replaceAll("$1...$2@");
if (uploadOnly) {
return;
}
LOGI(TAG, "Beginning sync for account " + logSanitizedAccountName + "," +
" uploadOnly=" + uploadOnly +
" manualSync=" + manualSync +
" initialize=" + initialize);
String chosenAccountName = AccountUtils.getChosenAccountName(mContext);
boolean isAccountSet = !TextUtils.isEmpty(chosenAccountName);
boolean isChosenAccount = isAccountSet && chosenAccountName.equals(account.name);
if (isAccountSet) {
ContentResolver.setIsSyncable(account, authority, isChosenAccount ? 1 : 0);
}
if (!isChosenAccount) {
LOGW(TAG, "Tried to sync account " + logSanitizedAccountName + " but the chosen " +
"account is actually " + chosenAccountName);
++syncResult.stats.numAuthExceptions;
return;
}
// Perform a sync using SyncHelper
if (mSyncHelper == null) {
mSyncHelper = new SyncHelper(mContext);
}
try {
mSyncHelper.performSync(syncResult,
SyncHelper.FLAG_SYNC_LOCAL | SyncHelper.FLAG_SYNC_REMOTE);
} catch (IOException e) {
++syncResult.stats.numIoExceptions;
LOGE(TAG, "Error syncing data for I/O 2013.", e);
}
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.appwidget;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.ui.SessionLivestreamActivity;
import com.google.android.apps.iosched.ui.SimpleSectionedListAdapter;
import com.google.android.apps.iosched.ui.SimpleSectionedListAdapter.Section;
import com.google.android.apps.iosched.ui.TaskStackBuilderProxyActivity;
import com.google.android.apps.iosched.util.AccountUtils;
import com.google.android.apps.iosched.util.PrefUtils;
import com.google.android.apps.iosched.util.UIUtils;
import android.annotation.TargetApi;
import android.content.Context;
import android.content.Intent;
import android.content.res.Resources;
import android.database.Cursor;
import android.os.Build;
import android.provider.BaseColumns;
import android.text.TextUtils;
import android.text.format.DateUtils;
import android.util.SparseBooleanArray;
import android.util.SparseIntArray;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.RemoteViewsService;
import java.util.ArrayList;
import java.util.Formatter;
import java.util.List;
import java.util.Locale;
import static com.google.android.apps.iosched.util.LogUtils.LOGV;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* This is the service that provides the factory to be bound to the collection service.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ScheduleWidgetRemoteViewsService extends RemoteViewsService {
@Override
public RemoteViewsFactory onGetViewFactory(Intent intent) {
return new WidgetRemoveViewsFactory(this.getApplicationContext());
}
/**
* This is the factory that will provide data to the collection widget.
*/
private static class WidgetRemoveViewsFactory implements RemoteViewsService.RemoteViewsFactory {
private static final String TAG = makeLogTag(WidgetRemoveViewsFactory.class);
private Context mContext;
private Cursor mCursor;
private SparseIntArray mPMap;
private List<SimpleSectionedListAdapter.Section> mSections;
private SparseBooleanArray mHeaderPositionMap;
StringBuilder mBuffer = new StringBuilder();
Formatter mFormatter = new Formatter(mBuffer, Locale.getDefault());
public WidgetRemoveViewsFactory(Context context) {
mContext = context;
}
public void onCreate() {
// Since we reload the cursor in onDataSetChanged() which gets called immediately after
// onCreate(), we do nothing here.
}
public void onDestroy() {
if (mCursor != null) {
mCursor.close();
}
}
public int getCount() {
if (mCursor == null || !AccountUtils.isAuthenticated(mContext)) {
return 0;
}
int size = mCursor.getCount() + mSections.size();
if (size < 10) {
init();
size = mCursor.getCount() + mSections.size();
}
LOGV(TAG, "size returned:" + size);
return size;
}
public RemoteViews getViewAt(int position) {
RemoteViews rv;
boolean isSectionHeader = mHeaderPositionMap.get(position);
int offset = mPMap.get(position);
Intent homeIntent = new Intent(mContext, HomeActivity.class);
if (isSectionHeader) {
rv = new RemoteViews(mContext.getPackageName(), R.layout.list_item_schedule_header);
Section section = mSections.get(offset - 1);
rv.setTextViewText(R.id.list_item_schedule_header_textview, section.getTitle());
} else {
int cursorPosition = position - offset;
mCursor.moveToPosition(cursorPosition);
rv = new RemoteViews(mContext.getPackageName(),
R.layout.list_item_schedule_block_widget);
final String type = mCursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockId = mCursor.getString(BlocksQuery.BLOCK_ID);
final String blockTitle = mCursor.getString(BlocksQuery.BLOCK_TITLE);
final String blockType = mCursor.getString(BlocksQuery.BLOCK_TYPE);
final String blockMeta = mCursor.getString(BlocksQuery.BLOCK_META);
final long blockStart = mCursor.getLong(BlocksQuery.BLOCK_START);
final long blockEnd = mCursor.getLong(BlocksQuery.BLOCK_END);
final Resources res = mContext.getResources();
rv.setTextViewText(R.id.block_endtime, null);
if (ScheduleContract.Blocks.BLOCK_TYPE_SESSION.equals(type)
|| ScheduleContract.Blocks.BLOCK_TYPE_CODELAB.equals(type)
|| ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS.equals(blockType)) {
final int numStarredSessions = mCursor.getInt(BlocksQuery.NUM_STARRED_SESSIONS);
final String starredSessionId = mCursor
.getString(BlocksQuery.STARRED_SESSION_ID);
if (numStarredSessions == 0) {
// No sessions starred
rv.setTextViewText(R.id.block_title, mContext.getString(
R.string.schedule_empty_slot_title_template,
TextUtils.isEmpty(blockTitle)
? ""
: (" " + blockTitle.toLowerCase())));
rv.setTextColor(R.id.block_title,
res.getColor(R.color.body_text_1_positive));
rv.setTextViewText(R.id.block_subtitle, mContext.getString(
R.string.schedule_empty_slot_subtitle));
rv.setViewVisibility(R.id.extra_button, View.GONE);
Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent(
homeIntent,
new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks
.buildSessionsUri(blockId)));
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent);
} else if (numStarredSessions == 1) {
// exactly 1 session starred
final String starredSessionTitle =
mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
String starredSessionSubtitle =
mCursor.getString(BlocksQuery.STARRED_SESSION_ROOM_NAME);
if (starredSessionSubtitle == null) {
starredSessionSubtitle = mContext.getString(R.string.unknown_room);
}
// Determine if the session is in the past
long currentTimeMillis = UIUtils.getCurrentTime(mContext);
boolean conferenceEnded = currentTimeMillis > UIUtils.CONFERENCE_END_MILLIS;
boolean blockEnded = currentTimeMillis > blockEnd;
if (blockEnded && !conferenceEnded) {
starredSessionSubtitle = mContext.getString(R.string.session_finished);
}
rv.setTextViewText(R.id.block_title, starredSessionTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle, starredSessionSubtitle);
rv.setViewVisibility(R.id.extra_button, View.VISIBLE);
Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent(
homeIntent,
new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions
.buildSessionUri(starredSessionId)));
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent);
fillIntent = TaskStackBuilderProxyActivity.getFillIntent(
homeIntent,
new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks
.buildSessionsUri(blockId)));
rv.setOnClickFillInIntent(R.id.extra_button, fillIntent);
} else {
// 2 or more sessions starred
rv.setTextViewText(R.id.block_title,
mContext.getString(R.string.schedule_conflict_title,
numStarredSessions));
rv.setTextColor(R.id.block_title,
res.getColor(R.color.body_text_1));
rv.setTextViewText(R.id.block_subtitle,
mContext.getString(R.string.schedule_conflict_subtitle));
rv.setViewVisibility(R.id.extra_button, View.VISIBLE);
Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent(
homeIntent,
new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks
.buildStarredSessionsUri(blockId)));
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent);
fillIntent = TaskStackBuilderProxyActivity.getFillIntent(
homeIntent,
new Intent(Intent.ACTION_VIEW, ScheduleContract.Blocks
.buildSessionsUri(blockId)));
rv.setOnClickFillInIntent(R.id.extra_button, fillIntent);
}
rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_2));
} else if (ScheduleContract.Blocks.BLOCK_TYPE_KEYNOTE.equals(type)) {
long currentTimeMillis = UIUtils.getCurrentTime(mContext);
boolean past = (currentTimeMillis > blockEnd
&& currentTimeMillis < UIUtils.CONFERENCE_END_MILLIS);
boolean present = !past && (currentTimeMillis >= blockStart);
boolean canViewStream = present && UIUtils.hasHoneycomb();
final String starredSessionId = mCursor
.getString(BlocksQuery.STARRED_SESSION_ID);
final String starredSessionTitle =
mCursor.getString(BlocksQuery.STARRED_SESSION_TITLE);
rv.setTextViewText(R.id.block_title, starredSessionTitle);
rv.setTextViewText(R.id.block_subtitle, res.getString(R.string.keynote_room));
rv.setTextColor(R.id.block_title, canViewStream
? res.getColor(R.color.body_text_1)
: res.getColor(R.color.body_text_disabled));
rv.setTextColor(R.id.block_subtitle, canViewStream
? res.getColor(R.color.body_text_2)
: res.getColor(R.color.body_text_disabled));
rv.setViewVisibility(R.id.extra_button, View.GONE);
if (canViewStream) {
Intent fillIntent = TaskStackBuilderProxyActivity.getFillIntent(
homeIntent,
new Intent(Intent.ACTION_VIEW, ScheduleContract.Sessions
.buildSessionUri(starredSessionId))
.setClass(mContext, SessionLivestreamActivity.class));
rv.setOnClickFillInIntent(R.id.list_item_middle_container, fillIntent);
} else {
rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent());
}
} else {
rv.setTextViewText(R.id.block_title, blockTitle);
rv.setTextColor(R.id.block_title, res.getColor(R.color.body_text_disabled));
rv.setTextViewText(R.id.block_subtitle, blockMeta);
rv.setTextColor(R.id.block_subtitle, res.getColor(R.color.body_text_disabled));
rv.setViewVisibility(R.id.extra_button, View.GONE);
mBuffer.setLength(0);
rv.setTextViewText(R.id.block_endtime,
DateUtils.formatDateRange(mContext, mFormatter,
blockEnd, blockEnd,
DateUtils.FORMAT_SHOW_TIME,
PrefUtils.getDisplayTimeZone(mContext).getID()).toString());
rv.setOnClickFillInIntent(R.id.list_item_middle_container, new Intent());
}
mBuffer.setLength(0);
rv.setTextViewText(R.id.block_time,
DateUtils.formatDateRange(mContext, mFormatter,
blockStart, blockStart,
DateUtils.FORMAT_SHOW_TIME,
PrefUtils.getDisplayTimeZone(mContext).getID()).toString());
}
return rv;
}
public RemoteViews getLoadingView() {
return null;
}
public int getViewTypeCount() {
return 2;
}
public long getItemId(int position) {
return position;
}
public boolean hasStableIds() {
return true;
}
public void onDataSetChanged() {
init();
}
private void init() {
if (mCursor != null) {
mCursor.close();
}
String liveStreamedOnlyBlocksSelection = "("
+ (UIUtils.shouldShowLiveSessionsOnly(mContext)
? ScheduleContract.Blocks.BLOCK_TYPE + " NOT IN ('"
+ ScheduleContract.Blocks.BLOCK_TYPE_SESSION + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_CODELAB + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS + "','"
+ ScheduleContract.Blocks.BLOCK_TYPE_FOOD + "')"
+ " OR " + ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS + ">1 "
: "1==1") + ")";
String onlyStarredOfficeHoursSelection = "("
+ ScheduleContract.Blocks.BLOCK_TYPE + " != '"
+ ScheduleContract.Blocks.BLOCK_TYPE_OFFICE_HOURS
+ "' OR " + ScheduleContract.Blocks.NUM_STARRED_SESSIONS + ">0)";
String excludeSandbox = "("+ScheduleContract.Blocks.BLOCK_TYPE + " != '"
+ ScheduleContract.Blocks.BLOCK_TYPE_SANDBOX +"')";
mCursor = mContext.getContentResolver().query(ScheduleContract.Blocks.CONTENT_URI,
BlocksQuery.PROJECTION,
ScheduleContract.Blocks.BLOCK_END + " >= ? AND "
+ liveStreamedOnlyBlocksSelection + " AND "
+ onlyStarredOfficeHoursSelection + " AND "
+ excludeSandbox,
new String[]{
Long.toString(UIUtils.getCurrentTime(mContext))
},
ScheduleContract.Blocks.DEFAULT_SORT);
String displayTimeZone = PrefUtils.getDisplayTimeZone(mContext).getID();
mSections = new ArrayList<SimpleSectionedListAdapter.Section>();
mCursor.moveToFirst();
long previousTime = -1;
long time;
mPMap = new SparseIntArray();
mHeaderPositionMap = new SparseBooleanArray();
int offset = 0;
int globalPosition = 0;
while (!mCursor.isAfterLast()) {
time = mCursor.getLong(BlocksQuery.BLOCK_START);
if (!UIUtils.isSameDayDisplay(previousTime, time, mContext)) {
mBuffer.setLength(0);
mSections.add(new SimpleSectionedListAdapter.Section(mCursor.getPosition(),
DateUtils.formatDateRange(
mContext, mFormatter,
time, time,
DateUtils.FORMAT_ABBREV_MONTH | DateUtils.FORMAT_SHOW_DATE
| DateUtils.FORMAT_SHOW_WEEKDAY,
displayTimeZone).toString()));
++offset;
mHeaderPositionMap.put(globalPosition, true);
mPMap.put(globalPosition, offset);
++globalPosition;
}
mHeaderPositionMap.put(globalPosition, false);
mPMap.put(globalPosition, offset);
++globalPosition;
previousTime = time;
mCursor.moveToNext();
}
LOGV(TAG, "Leaving init()");
}
}
public interface BlocksQuery {
String[] PROJECTION = {
BaseColumns._ID,
ScheduleContract.Blocks.BLOCK_ID,
ScheduleContract.Blocks.BLOCK_TITLE,
ScheduleContract.Blocks.BLOCK_START,
ScheduleContract.Blocks.BLOCK_END,
ScheduleContract.Blocks.BLOCK_TYPE,
ScheduleContract.Blocks.BLOCK_META,
ScheduleContract.Blocks.NUM_STARRED_SESSIONS,
ScheduleContract.Blocks.NUM_LIVESTREAMED_SESSIONS,
ScheduleContract.Blocks.STARRED_SESSION_ID,
ScheduleContract.Blocks.STARRED_SESSION_TITLE,
ScheduleContract.Blocks.STARRED_SESSION_ROOM_NAME,
};
int _ID = 0;
int BLOCK_ID = 1;
int BLOCK_TITLE = 2;
int BLOCK_START = 3;
int BLOCK_END = 4;
int BLOCK_TYPE = 5;
int BLOCK_META = 6;
int NUM_STARRED_SESSIONS = 7;
int NUM_LIVESTREAMED_SESSIONS = 8;
int STARRED_SESSION_ID = 9;
int STARRED_SESSION_TITLE = 10;
int STARRED_SESSION_ROOM_NAME = 11;
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.appwidget;
import com.google.android.apps.iosched.R;
import com.google.android.apps.iosched.provider.ScheduleContract;
import com.google.android.apps.iosched.sync.SyncHelper;
import com.google.android.apps.iosched.ui.HomeActivity;
import com.google.android.apps.iosched.ui.TaskStackBuilderProxyActivity;
import com.google.android.apps.iosched.util.AccountUtils;
import android.accounts.Account;
import android.annotation.TargetApi;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Build;
import android.os.Handler;
import android.os.HandlerThread;
import android.widget.RemoteViews;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
/**
* The app widget's AppWidgetProvider.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class ScheduleWidgetProvider extends AppWidgetProvider {
private static final String TAG = makeLogTag(ScheduleWidgetProvider.class);
private static final String REFRESH_ACTION =
"com.google.android.apps.iosched.appwidget.action.REFRESH";
private static final String EXTRA_PERFORM_SYNC =
"com.google.android.apps.iosched.appwidget.extra.PERFORM_SYNC";
public static Intent getRefreshBroadcastIntent(Context context, boolean performSync) {
return new Intent(REFRESH_ACTION)
.setComponent(new ComponentName(context, ScheduleWidgetProvider.class))
.putExtra(EXTRA_PERFORM_SYNC, performSync);
}
@Override
public void onReceive(final Context context, Intent widgetIntent) {
final String action = widgetIntent.getAction();
if (REFRESH_ACTION.equals(action)) {
final boolean shouldSync = widgetIntent.getBooleanExtra(EXTRA_PERFORM_SYNC, false);
// Trigger sync
Account chosenAccount = AccountUtils.getChosenAccount(context);
if (shouldSync && chosenAccount != null) {
SyncHelper.requestManualSync(chosenAccount);
}
// Notify the widget that the list view needs to be updated.
final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
final ComponentName cn = new ComponentName(context, ScheduleWidgetProvider.class);
mgr.notifyAppWidgetViewDataChanged(mgr.getAppWidgetIds(cn),
R.id.widget_schedule_list);
}
super.onReceive(context, widgetIntent);
}
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {
final boolean isAuthenticated = AccountUtils.isAuthenticated(context);
for (int appWidgetId : appWidgetIds) {
// Specify the service to provide data for the collection widget. Note that we need to
// embed the appWidgetId via the data otherwise it will be ignored.
final Intent intent = new Intent(context, ScheduleWidgetRemoteViewsService.class)
.putExtra(AppWidgetManager.EXTRA_APPWIDGET_ID, appWidgetId);
intent.setData(Uri.parse(intent.toUri(Intent.URI_INTENT_SCHEME)));
final RemoteViews rv = new RemoteViews(context.getPackageName(), R.layout.widget);
rv.setRemoteAdapter(appWidgetId, R.id.widget_schedule_list, intent);
// Set the empty view to be displayed if the collection is empty. It must be a sibling
// view of the collection view.
rv.setEmptyView(R.id.widget_schedule_list, android.R.id.empty);
rv.setTextViewText(android.R.id.empty, context.getResources().getString(isAuthenticated
? R.string.empty_widget_text
: R.string.empty_widget_text_signed_out));
final PendingIntent refreshPendingIntent = PendingIntent.getBroadcast(context, 0,
getRefreshBroadcastIntent(context, true), PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.widget_refresh_button, refreshPendingIntent);
final Intent onClickIntent = TaskStackBuilderProxyActivity.getTemplate(context);
final PendingIntent onClickPendingIntent = PendingIntent.getActivity(context, 0,
onClickIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setPendingIntentTemplate(R.id.widget_schedule_list, onClickPendingIntent);
final Intent openAppIntent = new Intent(context, HomeActivity.class)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
final PendingIntent openAppPendingIntent = PendingIntent.getActivity(context, 0,
openAppIntent, PendingIntent.FLAG_UPDATE_CURRENT);
rv.setOnClickPendingIntent(R.id.widget_logo, openAppPendingIntent);
appWidgetManager.updateAppWidget(appWidgetId, rv);
}
super.onUpdate(context, appWidgetManager, appWidgetIds);
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.gcm;
import com.google.android.gcm.GCMBroadcastReceiver;
import android.content.Context;
/**
* @author trevorjohns@google.com (Trevor Johns)
*/
public class GCMRedirectedBroadcastReceiver extends GCMBroadcastReceiver {
/**
* Gets the class name of the intent service that will handle GCM messages.
*
* Used to override class name, so that GCMIntentService can live in a
* subpackage.
*/
@Override
protected String getGCMIntentServiceClassName(Context context) {
return GCMIntentService.class.getCanonicalName();
}
}
| Java |
/*
* Copyright 2012 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.gcm;
import android.util.Log;
import com.google.android.apps.iosched.Config;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import com.google.android.apps.iosched.util.AccountUtils;
import java.io.IOException;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.*;
import java.util.Map.Entry;
import static com.google.android.apps.iosched.util.LogUtils.*;
/**
* Helper class used to communicate with the demo server.
*/
public final class ServerUtilities {
private static final String TAG = makeLogTag("GCMs");
private static final String PREFERENCES = "com.google.android.apps.iosched.gcm";
private static final String PROPERTY_REGISTERED_TS = "registered_ts";
private static final String PROPERTY_REG_ID = "reg_id";
private static final int MAX_ATTEMPTS = 5;
private static final int BACKOFF_MILLI_SECONDS = 2000;
private static final Random sRandom = new Random();
/**
* Register this account/device pair within the server.
*
* @param context Current context
* @param gcmId The GCM registration ID for this device
* @return whether the registration succeeded or not.
*/
public static boolean register(final Context context, final String gcmId) {
LOGI(TAG, "registering device (gcm_id = " + gcmId + ")");
String serverUrl = Config.GCM_SERVER_URL + "/register";
String plusProfileId = AccountUtils.getPlusProfileId(context);
if (plusProfileId == null) {
LOGW(TAG, "Profile ID: null");
} else {
LOGI(TAG, "Profile ID: " + plusProfileId);
}
Map<String, String> params = new HashMap<String, String>();
params.put("gcm_id", gcmId);
params.put("gplus_id", plusProfileId);
long backoff = BACKOFF_MILLI_SECONDS + sRandom.nextInt(1000);
// Once GCM returns a registration id, we need to register it in the
// demo server. As the server might be down, we will retry it a couple
// times.
for (int i = 1; i <= MAX_ATTEMPTS; i++) {
LOGV(TAG, "Attempt #" + i + " to register");
try {
post(serverUrl, params);
setRegisteredOnServer(context, true, gcmId);
return true;
} catch (IOException e) {
// Here we are simplifying and retrying on any error; in a real
// application, it should retry only on unrecoverable errors
// (like HTTP error code 503).
LOGE(TAG, "Failed to register on attempt " + i, e);
if (i == MAX_ATTEMPTS) {
break;
}
try {
LOGV(TAG, "Sleeping for " + backoff + " ms before retry");
Thread.sleep(backoff);
} catch (InterruptedException e1) {
// Activity finished before we complete - exit.
LOGD(TAG, "Thread interrupted: abort remaining retries!");
Thread.currentThread().interrupt();
return false;
}
// increase backoff exponentially
backoff *= 2;
}
}
return false;
}
/**
* Unregister this account/device pair within the server.
*
* @param context Current context
* @param gcmId The GCM registration ID for this device
*/
static void unregister(final Context context, final String gcmId) {
LOGI(TAG, "unregistering device (gcmId = " + gcmId + ")");
String serverUrl = Config.GCM_SERVER_URL + "/unregister";
Map<String, String> params = new HashMap<String, String>();
params.put("gcm_id", gcmId);
try {
post(serverUrl, params);
setRegisteredOnServer(context, false, gcmId);
} catch (IOException e) {
// At this point the device is unregistered from GCM, but still
// registered in the server.
// We could try to unregister again, but it is not necessary:
// if the server tries to send a message to the device, it will get
// a "NotRegistered" error message and should unregister the device.
LOGD(TAG, "Unable to unregister from application server", e);
} finally {
// Regardless of server success, clear local preferences
setRegisteredOnServer(context, false, null);
}
}
/**
* Sets whether the device was successfully registered in the server side.
*
* @param context Current context
* @param flag True if registration was successful, false otherwise
* @param gcmId True if registration was successful, false otherwise
*/
private static void setRegisteredOnServer(Context context, boolean flag, String gcmId) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCES, Context.MODE_PRIVATE);
LOGD(TAG, "Setting registered on server status as: " + flag);
Editor editor = prefs.edit();
if (flag) {
editor.putLong(PROPERTY_REGISTERED_TS, new Date().getTime());
editor.putString(PROPERTY_REG_ID, gcmId);
} else {
editor.remove(PROPERTY_REG_ID);
}
editor.commit();
}
/**
* Checks whether the device was successfully registered in the server side.
*
* @param context Current context
* @return True if registration was successful, false otherwise
*/
public static boolean isRegisteredOnServer(Context context) {
final SharedPreferences prefs = context.getSharedPreferences(
PREFERENCES, Context.MODE_PRIVATE);
// Find registration threshold
Calendar cal = Calendar.getInstance();
cal.add(Calendar.DATE, -1);
long yesterdayTS = cal.getTimeInMillis();
long regTS = prefs.getLong(PROPERTY_REGISTERED_TS, 0);
if (regTS > yesterdayTS) {
LOGV(TAG, "GCM registration current. regTS=" + regTS + " yesterdayTS=" + yesterdayTS);
return true;
} else {
LOGV(TAG, "GCM registration expired. regTS=" + regTS + " yesterdayTS=" + yesterdayTS);
return false;
}
}
public static String getGcmId(Context context) {
final SharedPreferences prefs = context.getSharedPreferences(PREFERENCES, Context.MODE_PRIVATE);
return prefs.getString(PROPERTY_REG_ID, null);
}
/**
* Unregister the current GCM ID when we sign-out
*
* @param context Current context
*/
public static void onSignOut(Context context) {
String gcmId = getGcmId(context);
if (gcmId != null) {
unregister(context, gcmId);
}
}
/**
* Issue a POST request to the server.
*
* @param endpoint POST address.
* @param params request parameters.
* @throws java.io.IOException propagated from POST.
*/
private static void post(String endpoint, Map<String, String> params)
throws IOException {
URL url;
try {
url = new URL(endpoint);
} catch (MalformedURLException e) {
throw new IllegalArgumentException("invalid url: " + endpoint);
}
StringBuilder bodyBuilder = new StringBuilder();
Iterator<Entry<String, String>> iterator = params.entrySet().iterator();
// constructs the POST body using the parameters
while (iterator.hasNext()) {
Entry<String, String> param = iterator.next();
bodyBuilder.append(param.getKey()).append('=')
.append(param.getValue());
if (iterator.hasNext()) {
bodyBuilder.append('&');
}
}
String body = bodyBuilder.toString();
LOGV(TAG, "Posting '" + body + "' to " + url);
HttpURLConnection conn = null;
try {
conn = (HttpURLConnection) url.openConnection();
conn.setDoOutput(true);
conn.setUseCaches(false);
conn.setChunkedStreamingMode(0);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type",
"application/x-www-form-urlencoded;charset=UTF-8");
conn.setRequestProperty("Content-Length",
Integer.toString(body.length()));
// post the request
OutputStream out = conn.getOutputStream();
out.write(body.getBytes());
out.close();
// handle the response
int status = conn.getResponseCode();
if (status != 200) {
throw new IOException("Post failed with error code " + status);
}
} finally {
if (conn != null) {
conn.disconnect();
}
}
}
}
| Java |
/*
* Copyright 2013 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.android.apps.iosched.gcm.command;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import com.google.android.apps.iosched.gcm.GCMCommand;
import com.google.android.apps.iosched.sync.TriggerSyncReceiver;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import java.util.Random;
import static com.google.android.apps.iosched.util.LogUtils.LOGI;
import static com.google.android.apps.iosched.util.LogUtils.makeLogTag;
public class SyncCommand extends GCMCommand {
private static final String TAG = makeLogTag("SyncCommand");
private static final int DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS = 15 * 60 * 1000; // 15 minutes
private static final Random RANDOM = new Random();
@Override
public void execute(Context context, String type, String extraData) {
LOGI(TAG, "Received GCM message: " + type);
int syncJitter;
SyncData syncData = null;
if (extraData != null) {
try {
Gson gson = new Gson();
syncData = gson.fromJson(extraData, SyncData.class);
} catch (JsonSyntaxException e) {
LOGI(TAG, "Error while decoding extraData: " + e.toString());
}
}
if (syncData != null && syncData.sync_jitter != 0) {
syncJitter = syncData.sync_jitter;
} else {
syncJitter = DEFAULT_TRIGGER_SYNC_MAX_JITTER_MILLIS;
}
scheduleSync(context, syncJitter);
}
private void scheduleSync(Context context, int syncJitter) {
int jitterMillis = (int) (RANDOM.nextFloat() * syncJitter);
final String debugMessage = "Scheduling next sync for " + jitterMillis + "ms";
LOGI(TAG, debugMessage);
((AlarmManager) context.getSystemService(Context.ALARM_SERVICE))
.set(
AlarmManager.RTC,
System.currentTimeMillis() + jitterMillis,
PendingIntent.getBroadcast(
context,
0,
new Intent(context, TriggerSyncReceiver.class),
PendingIntent.FLAG_CANCEL_CURRENT));
}
class SyncData {
private int sync_jitter;
SyncData() {}
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.