code stringlengths 1 2.01M | repo_name stringlengths 3 62 | path stringlengths 1 267 | language stringclasses 231 values | license stringclasses 13 values | size int64 1 2.01M |
|---|---|---|---|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.OutputStream;
import org.apache.ogt.http.io.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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/AbstractSessionOutputBuffer.java | Java | gpl3 | 7,925 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestFactory;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.RequestLine;
import org.apache.ogt.http.io.SessionInputBuffer;
import org.apache.ogt.http.message.LineParser;
import org.apache.ogt.http.message.ParserCursor;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* HTTP request parser that obtain its input from an instance
* of {@link SessionInputBuffer}.
* <p>
* The following parameters can be used to customize the behavior of this
* class:
* <ul>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_HEADER_COUNT}</li>
* <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li>
* </ul>
*
* @since 4.0
*/
public class HttpRequestParser extends AbstractMessageParser {
private final HttpRequestFactory requestFactory;
private final CharArrayBuffer lineBuf;
/**
* Creates an instance of this class.
*
* @param buffer the session input buffer.
* @param parser the line parser.
* @param requestFactory the factory to use to create
* {@link HttpRequest}s.
* @param params HTTP parameters.
*/
public HttpRequestParser(
final SessionInputBuffer buffer,
final LineParser parser,
final HttpRequestFactory requestFactory,
final HttpParams params) {
super(buffer, parser, params);
if (requestFactory == null) {
throw new IllegalArgumentException("Request factory may not be null");
}
this.requestFactory = requestFactory;
this.lineBuf = new CharArrayBuffer(128);
}
protected HttpMessage parseHead(
final SessionInputBuffer sessionBuffer)
throws IOException, HttpException, ParseException {
this.lineBuf.clear();
int i = sessionBuffer.readLine(this.lineBuf);
if (i == -1) {
throw new ConnectionClosedException("Client closed connection");
}
ParserCursor cursor = new ParserCursor(0, this.lineBuf.length());
RequestLine requestline = this.lineParser.parseRequestLine(this.lineBuf, cursor);
return this.requestFactory.newHttpRequest(requestline);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/HttpRequestParser.java | Java | gpl3 | 3,696 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import 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();
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/ChunkedOutputStream.java | Java | gpl3 | 6,315 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/HttpTransportMetricsImpl.java | Java | gpl3 | 1,891 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import java.io.InputStream;
import org.apache.ogt.http.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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/AbstractSessionInputBuffer.java | Java | gpl3 | 12,717 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/ContentLengthInputStream.java | Java | gpl3 | 7,804 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.io;
import java.io.IOException;
import 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();
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/ChunkedInputStream.java | Java | gpl3 | 9,948 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.impl.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");
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/io/AbstractMessageParser.java | Java | gpl3 | 10,978 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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();
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/impl/DefaultHttpClientConnection.java | Java | gpl3 | 3,243 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/MethodNotSupportedException.java | Java | gpl3 | 2,134 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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();
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpHost.java | Java | gpl3 | 6,407 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
/**
* 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);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/MalformedChunkCodingException.java | Java | gpl3 | 1,858 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpClientConnection.java | Java | gpl3 | 3,897 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* 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);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ProtocolException.java | Java | gpl3 | 2,306 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* 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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/StatusLine.java | Java | gpl3 | 1,831 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpResponse.java | Java | gpl3 | 5,400 |
/*
* $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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpEntityEnclosingRequest.java | Java | gpl3 | 2,036 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* 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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpRequest.java | Java | gpl3 | 1,896 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import 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);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpMessage.java | Java | gpl3 | 6,761 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/ByteArrayBuffer.java | Java | gpl3 | 11,788 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/EntityUtils.java | Java | gpl3 | 8,099 |
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
-->
</head>
<body>
Resizable
{@link org.apache.ogt.http.util.ByteArrayBuffer byte} and
{@link org.apache.ogt.http.util.CharArrayBuffer char} arrays
and various utility classes with static helper methods.
</body>
</html>
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/package.html | HTML | gpl3 | 1,423 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
/**
* 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;
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/LangUtils.java | Java | gpl3 | 3,576 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.Serializable;
import org.apache.ogt.http.protocol.HTTP;
/**
* A resizable char array.
*
* @since 4.0
*/
public final class CharArrayBuffer implements Serializable {
private static final long serialVersionUID = -6208952725094867135L;
private char[] buffer;
private int len;
/**
* Creates an instance of {@link CharArrayBuffer} with the given initial
* capacity.
*
* @param capacity the capacity
*/
public CharArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
this.buffer = new char[capacity];
}
private void expand(int newlen) {
char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)];
System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
this.buffer = newbuffer;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> chars.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final char[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int newlen = this.len + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newlen;
}
/**
* Appends chars of the given string to this buffer. The capacity of the
* buffer is increased, if necessary, to accommodate all chars.
*
* @param str the string.
*/
public void append(String str) {
if (str == null) {
str = "null";
}
int strlen = str.length();
int newlen = this.len + strlen;
if (newlen > this.buffer.length) {
expand(newlen);
}
str.getChars(0, strlen, this.buffer, this.len);
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* buffer starting at index <code>off</code>. The capacity of the
* destination buffer is increased, if necessary, to accommodate all
* <code>len</code> chars.
*
* @param b the source buffer to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final CharArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer, off, len);
}
/**
* Appends all chars to this buffer from the given source buffer starting
* at index <code>0</code>. The capacity of the destination buffer is
* increased, if necessary, to accommodate all {@link #length()} chars.
*
* @param b the source buffer to be appended.
*/
public void append(final CharArrayBuffer b) {
if (b == null) {
return;
}
append(b.buffer,0, b.len);
}
/**
* Appends <code>ch</code> char to this buffer. The capacity of the buffer
* is increased, if necessary, to accommodate the additional char.
*
* @param ch the char to be appended.
*/
public void append(char ch) {
int newlen = this.len + 1;
if (newlen > this.buffer.length) {
expand(newlen);
}
this.buffer[this.len] = ch;
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final byte[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int oldlen = this.len;
int newlen = oldlen + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {
this.buffer[i2] = (char) (b[i1] & 0xff);
}
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final ByteArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer(), off, len);
}
/**
* Appends chars of the textual representation of the given object to this
* buffer. The capacity of the buffer is increased, if necessary, to
* accommodate all chars.
*
* @param obj the object.
*/
public void append(final Object obj) {
append(String.valueOf(obj));
}
/**
* Clears content of the buffer. The underlying char array is not resized.
*/
public void clear() {
this.len = 0;
}
/**
* Converts the content of this buffer to an array of chars.
*
* @return char array
*/
public char[] toCharArray() {
char[] b = new char[this.len];
if (this.len > 0) {
System.arraycopy(this.buffer, 0, b, 0, this.len);
}
return b;
}
/**
* Returns the <code>char</code> value in this buffer at the specified
* index. The index argument must be greater than or equal to
* <code>0</code>, and less than the length of this buffer.
*
* @param i the index of the desired char value.
* @return the char value at the specified index.
* @throws IndexOutOfBoundsException if <code>index</code> is
* negative or greater than or equal to {@link #length()}.
*/
public char charAt(int i) {
return this.buffer[i];
}
/**
* Returns reference to the underlying char array.
*
* @return the char array.
*/
public char[] buffer() {
return this.buffer;
}
/**
* Returns the current capacity. The capacity is the amount of storage
* available for newly appended chars, beyond which an allocation will
* occur.
*
* @return the current capacity
*/
public int capacity() {
return this.buffer.length;
}
/**
* Returns the length of the buffer (char count).
*
* @return the length of the buffer
*/
public int length() {
return this.len;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. If the <code>required</code>
* argument is non-positive, this method takes no action.
*
* @param required the minimum required capacity.
*/
public void ensureCapacity(int required) {
if (required <= 0) {
return;
}
int available = this.buffer.length - this.len;
if (required > available) {
expand(this.len + required);
}
}
/**
* Sets the length of the buffer. The new length value is expected to be
* less than the current capacity and greater than or equal to
* <code>0</code>.
*
* @param len the new length
* @throws IndexOutOfBoundsException if the
* <code>len</code> argument is greater than the current
* capacity of the buffer or less than <code>0</code>.
*/
public void setLength(int len) {
if (len < 0 || len > this.buffer.length) {
throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);
}
this.len = len;
}
/**
* Returns <code>true</code> if this buffer is empty, that is, its
* {@link #length()} is equal to <code>0</code>.
* @return <code>true</code> if this buffer is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return this.len == 0;
}
/**
* Returns <code>true</code> if this buffer is full, that is, its
* {@link #length()} is equal to its {@link #capacity()}.
* @return <code>true</code> if this buffer is full, <code>false</code>
* otherwise.
*/
public boolean isFull() {
return this.len == this.buffer.length;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at the specified
* <code>beginIndex</code> and finishing at <code>endIndex</code>.
* If no such character occurs in this buffer within the specified bounds,
* <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>beginIndex</code> and
* <code>endIndex</code>. If <code>beginIndex</code> is negative,
* it has the same effect as if it were zero. If <code>endIndex</code> is
* greater than {@link #length()}, it has the same effect as if it were
* {@link #length()}. If the <code>beginIndex</code> is greater than
* the <code>endIndex</code>, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @param beginIndex the index to start the search from.
* @param endIndex the index to finish the search at.
* @return the index of the first occurrence of the character in the buffer
* within the given bounds, or <code>-1</code> if the character does
* not occur.
*/
public int indexOf(int ch, int beginIndex, int endIndex) {
if (beginIndex < 0) {
beginIndex = 0;
}
if (endIndex > this.len) {
endIndex = this.len;
}
if (beginIndex > endIndex) {
return -1;
}
for (int i = beginIndex; i < endIndex; i++) {
if (this.buffer[i] == ch) {
return i;
}
}
return -1;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at <code>0</code> and finishing
* at {@link #length()}. If no such character occurs in this buffer within
* those bounds, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @return the index of the first occurrence of the character in the
* buffer, or <code>-1</code> if the character does not occur.
*/
public int indexOf(int ch) {
return indexOf(ch, 0, this.len);
}
/**
* Returns a substring of this buffer. The substring begins at the specified
* <code>beginIndex</code> and extends to the character at index
* <code>endIndex - 1</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception StringIndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substring(int beginIndex, int endIndex) {
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
/**
* Returns a substring of this buffer with leading and trailing whitespace
* omitted. The substring begins with the first non-whitespace character
* from <code>beginIndex</code> and extends to the last
* non-whitespace character with the index lesser than
* <code>endIndex</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substringTrimmed(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new IndexOutOfBoundsException("Negative beginIndex: "+beginIndex);
}
if (endIndex > this.len) {
throw new IndexOutOfBoundsException("endIndex: "+endIndex+" > length: "+this.len);
}
if (beginIndex > endIndex) {
throw new IndexOutOfBoundsException("beginIndex: "+beginIndex+" > endIndex: "+endIndex);
}
while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) {
beginIndex++;
}
while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) {
endIndex--;
}
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
public String toString() {
return new String(this.buffer, 0, this.len);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/CharArrayBuffer.java | Java | gpl3 | 16,437 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.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() {
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/EncodingUtils.java | Java | gpl3 | 5,880 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/VersionInfo.java | Java | gpl3 | 10,766 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.lang.reflect.Method;
/**
* The home for utility methods that handle various exception-related tasks.
*
*
* @since 4.0
*/
public final class ExceptionUtils {
/** A reference to Throwable's initCause method, or null if it's not there in this JVM */
static private final Method INIT_CAUSE_METHOD = getInitCauseMethod();
/**
* Returns a <code>Method<code> allowing access to
* {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable},
* or <code>null</code> if the method
* does not exist.
*
* @return A <code>Method<code> for <code>Throwable.initCause</code>, or
* <code>null</code> if unavailable.
*/
static private Method getInitCauseMethod() {
try {
Class[] paramsClasses = new Class[] { Throwable.class };
return Throwable.class.getMethod("initCause", paramsClasses);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* If we're running on JDK 1.4 or later, initialize the cause for the given throwable.
*
* @param throwable The throwable.
* @param cause The cause of the throwable.
*/
public static void initCause(Throwable throwable, Throwable cause) {
if (INIT_CAUSE_METHOD != null) {
try {
INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause });
} catch (Exception e) {
// Well, with no logging, the only option is to munch the exception
}
}
}
private ExceptionUtils() {
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/util/ExceptionUtils.java | Java | gpl3 | 2,809 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* 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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpConnectionMetrics.java | Java | gpl3 | 2,301 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import 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);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpResponseFactory.java | Java | gpl3 | 2,520 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/SessionOutputBuffer.java | Java | gpl3 | 4,326 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/HttpMessageParser.java | Java | gpl3 | 1,814 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/EofSensor.java | Java | gpl3 | 1,312 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/HttpMessageWriter.java | Java | gpl3 | 1,817 |
<html>
<head>
<!--
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
-->
</head>
<body>
The blocking I/O abstraction of the HTTP components.
<p/>
This layer defines interfaces for transferring basic elements of
HTTP messages over connections.
</body>
</html>
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/package.html | HTML | gpl3 | 1,393 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/HttpTransportMetrics.java | Java | gpl3 | 1,549 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/SessionInputBuffer.java | Java | gpl3 | 6,390 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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();
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/io/BufferInfo.java | Java | gpl3 | 1,661 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HttpRequestInterceptor.java | Java | gpl3 | 2,716 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
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();
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/ProtocolVersion.java | Java | gpl3 | 9,206 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* 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);
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/main/java/org/apache/ogt/http/HeaderElement.java | Java | gpl3 | 3,225 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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) {}
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpServer.java | Java | gpl3 | 11,231 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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();
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpPost.java | Java | gpl3 | 6,296 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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) {}
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalReverseProxy.java | Java | gpl3 | 13,513 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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();
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/ElementalHttpGet.java | Java | gpl3 | 5,530 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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]);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/examples/org/apache/http/examples/PrintVersionInfo.java | Java | gpl3 | 2,907 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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());
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpMessageMockup.java | Java | gpl3 | 1,697 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.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[] {};
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/SessionOutputBufferMockup.java | Java | gpl3 | 2,935 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/SessionInputBufferMockup.java | Java | gpl3 | 3,868 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/TimeoutByteArrayInputStream.java | Java | gpl3 | 3,566 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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;
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpConnectionMockup.java | Java | gpl3 | 2,041 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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);
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpClient.java | Java | gpl3 | 4,836 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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 {
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpEntityMockup.java | Java | gpl3 | 1,979 |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf 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) {}
}
}
}
}
| zzhhhhh-android-gps | OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore/src/test/java/org/apache/ogt/http/mockup/HttpServer.java | Java | gpl3 | 7,786 |
/*------------------------------------------------------------------------------
** 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();
}
} | zzhhhhh-android-gps | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/utils/TelnetPositionSender.java | Java | gpl3 | 4,544 |
/*------------------------------------------------------------------------------
** 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" );
}
} | zzhhhhh-android-gps | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/utils/MockGPSLoggerDriver.java | Java | gpl3 | 10,654 |
/*------------------------------------------------------------------------------
** 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.demo.OpenGPSTrackerDemo;
import nl.sogeti.android.gpstracker.tests.gpsmock.MockGPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.logger.GPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.perf.MapStressTest;
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();
}
}
| zzhhhhh-android-gps | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/GPStrackingInstrumentation.java | Java | gpl3 | 3,442 |
/*------------------------------------------------------------------------------
** 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.GoogleLoggerMap;
import nl.sogeti.android.gpstracker.viewer.map.LoggerMap;
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<GoogleLoggerMap>
{
private static final int ZOOM_LEVEL = 16;
private static final Class<GoogleLoggerMap> CLASS = GoogleLoggerMap.class;
private static final String PACKAGE = "nl.sogeti.android.gpstracker";
private GoogleLoggerMap 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 );
}
}
| zzhhhhh-android-gps | OpenGPSTracker/test/src/nl/sogeti/android/gpstracker/tests/demo/OpenGPSTrackerDemo.java | Java | gpl3 | 10,239 |
package nl.sogeti.android.gpstracker.logger;
import android.net.Uri;
interface IGPSLoggerServiceRemote {
int loggingState();
long startLogging();
void pauseLogging();
long resumeLogging();
void stopLogging();
Uri storeMediaUri(in Uri mediaUri);
boolean isMediaPrepared();
} | zzhhhhh-android-gps | MetaTracker/application/src/nl/sogeti/android/gpstracker/logger/IGPSLoggerServiceRemote.aidl | AIDL | gpl3 | 295 |
/*
* 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
*
*
*/
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/xml/DOMUtil.java | Java | gpl3 | 7,126 |
/*
* 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
*
*
*/
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/xml/ElementCopyVisitor.java | Java | gpl3 | 3,342 |
/*
* 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)
{
}
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/xml/XMLPrintVisitor.java | Java | gpl3 | 5,835 |
/*
* 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
*
*
*/
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/xml/TreeWalker.java | Java | gpl3 | 3,723 |
/*
* 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
*
*
*/
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/xml/Visitor.java | Java | gpl3 | 1,671 |
/*
* 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
*
*
*/
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/xml/DefaultVisitor.java | Java | gpl3 | 1,669 |
/*
* 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);
}
}
} | zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/logger/GPSLoggerServiceManager.java | Java | gpl3 | 6,466 |
/*
* 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()
{
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/net/Protocol.java | Java | gpl3 | 5,814 |
/*
* 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);
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/net/OpenTracesClient.java | Java | gpl3 | 10,842 |
/*
* 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();
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/net/ClientException.java | Java | gpl3 | 1,533 |
/*
* 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);
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/Constants.java | Java | gpl3 | 6,401 |
/*
* 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;
}
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/activity/TrackingState.java | Java | gpl3 | 2,800 |
/*
* 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 );
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/activity/SettingsActivity.java | Java | gpl3 | 1,187 |
/*
* 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);
}
}
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/activity/UploadTrackActivity.java | Java | gpl3 | 6,069 |
/*
* 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();
}
}
};
}
| zzhhhhh-android-gps | MetaTracker/application/src/org/opentraces/metatracker/activity/MainActivity.java | Java | gpl3 | 18,582 |
ant clean; ant release; adb install -r bin/MetaTracker-release.apk
| zzhhhhh-android-gps | MetaTracker/application/build-install.sh | Shell | gpl3 | 67 |
using System;
using System.Collections.Generic;
using System.Linq;
using Samba.Domain.Models.Menus;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Infrastructure.Data;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
namespace Samba.Modules.SettingsModule
{
public class PrinterMapViewModel : ObservableObject
{
public PrinterMap Model { get; set; }
private const string NullLabel = "*";
private static readonly string NullPrinterLabel = string.Format("- {0} -", Localization.Properties.Resources.Select);
private readonly IWorkspace _workspace;
public PrinterMapViewModel(PrinterMap model, IWorkspace workspace)
{
Model = model;
_workspace = workspace;
}
public IEnumerable<Department> Departments { get { return GetAllDepartments(); } }
public IEnumerable<MenuItem> MenuItems { get { return GetAllMenuItems(MenuItemGroupCode); } }
public IEnumerable<Printer> Printers { get { return _workspace.All<Printer>(); } }
public IEnumerable<string> TicketTags { get { return GetTicketTags(); } }
public IEnumerable<string> MenuItemGroupCodes { get { return GetAllMenuItemGroupCodes(); } }
public IEnumerable<PrinterTemplate> PrinterTemplates { get { return _workspace.All<PrinterTemplate>(); } }
private static IEnumerable<string> GetAllMenuItemGroupCodes()
{
IList<string> result = new List<string>(Dao.Distinct<MenuItem>(x => x.GroupCode).OrderBy(x => x));
result.Insert(0, NullLabel);
return result;
}
private static IEnumerable<string> GetTicketTags()
{
IList<string> result = new List<string>(Dao.Distinct<TicketTagGroup>(x => x.Name).OrderBy(x => x));
result.Insert(0, NullLabel);
return result;
}
private IEnumerable<Department> GetAllDepartments()
{
IList<Department> result = new List<Department>(_workspace.All<Department>().OrderBy(x => x.Name));
result.Insert(0, Department.All);
return result;
}
private IEnumerable<MenuItem> GetAllMenuItems(string groupCode)
{
IList<MenuItem> result = string.IsNullOrEmpty(groupCode) || groupCode == NullLabel
? new List<MenuItem>(
_workspace.All<MenuItem>().OrderBy(x => x.Name))
: new List<MenuItem>(
_workspace.All<MenuItem>(x => x.GroupCode == groupCode).OrderBy(x => x.Name));
result.Insert(0, MenuItem.All);
return result;
}
public string PrinterTemplateLabel { get { return PrinterTemplate != null ? PrinterTemplate.Name : NullPrinterLabel; } }
public PrinterTemplate PrinterTemplate
{
get { return Model.PrinterTemplate; }
set
{
Model.PrinterTemplate = value;
RaisePropertyChanged("PrinterTemplate");
RaisePropertyChanged("PrinterTemplateLabel");
}
}
public string DepartmentLabel { get { return Department != null ? Department.Name : NullLabel; } }
public Department Department
{
get { return Model.Department ?? Department.All; }
set
{
Model.Department = value;
RaisePropertyChanged("Department");
RaisePropertyChanged("DepartmentLabel");
}
}
public int DepartmentId { get { return Model.Department.Id; } set { } }
public string MenuItemGroupCodeLabel
{
get { return string.IsNullOrEmpty(MenuItemGroupCode) ? NullLabel : MenuItemGroupCode; }
}
public string MenuItemGroupCode
{
get { return Model.MenuItemGroupCode ?? NullLabel; }
set
{
Model.MenuItemGroupCode = value;
RaisePropertyChanged("MenuItemGroupCode");
RaisePropertyChanged("MenuItemGroupCodeLabel");
RaisePropertyChanged("MenuItems");
}
}
public string TicketTagLabel
{
get
{
return TicketTag ?? NullLabel;
}
}
public string TicketTag
{
get
{
return Model.TicketTag ?? NullLabel;
}
set
{
Model.TicketTag = value;
RaisePropertyChanged("TicketTag");
RaisePropertyChanged("TicketTagLabel");
}
}
public string MenuItemLabel { get { return MenuItem != null ? MenuItem.Name : NullLabel; } }
public MenuItem MenuItem
{
get { return Model.MenuItem ?? MenuItem.All; }
set
{
Model.MenuItem = value;
RaisePropertyChanged("MenuItem");
RaisePropertyChanged("MenuItemLabel");
}
}
public string PrinterLabel { get { return Printer != null ? Printer.Name : NullPrinterLabel; } }
public Printer Printer
{
get { return Model.Printer; }
set
{
Model.Printer = value;
RaisePropertyChanged("Printer");
RaisePropertyChanged("PrinterLabel");
}
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrinterMapViewModel.cs | C# | gpl3 | 5,757 |
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.SettingsModule
{
public class NumeratorListViewModel:EntityCollectionViewModelBase<NumeratorViewModel,Numerator>
{
protected override NumeratorViewModel CreateNewViewModel(Numerator model)
{
return new NumeratorViewModel(model);
}
protected override Numerator CreateNewModel()
{
return new Numerator();
}
protected override string CanDeleteItem(Numerator model)
{
var count = Dao.Count<Department>(x => x.OrderNumerator.Id == model.Id);
if (count > 0) return Resources.DeleteErrorNumeratorIsOrderNumerator;
count = Dao.Count<Department>(x => x.TicketNumerator.Id == model.Id);
if (count > 0) return Resources.DeleteErrorNumeratorIsTicketNumerator;
count = Dao.Count<TicketTagGroup>(x => x.Numerator.Id == model.Id);
if (count > 0) return Resources.DeleteErrorNumeratorUsedInTicket;
return base.CanDeleteItem(model);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/NumeratorListViewModel.cs | C# | gpl3 | 1,257 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Samba.Domain.Models.Settings;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.SettingsModule
{
class PrintJobListViewModel : EntityCollectionViewModelBase<PrintJobViewModel, PrintJob>
{
protected override PrintJobViewModel CreateNewViewModel(PrintJob model)
{
return new PrintJobViewModel(model);
}
protected override PrintJob CreateNewModel()
{
return new PrintJob();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrintJobListViewModel.cs | C# | gpl3 | 597 |
using System;
using System.Collections.Generic;
using System.ComponentModel.Composition;
using System.Threading;
using System.Windows.Input;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Infrastructure;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.Services;
using Samba.Services;
using System.Linq;
namespace Samba.Modules.SettingsModule.WorkPeriods
{
[Export]
public class WorkPeriodsViewModel : ObservableObject
{
private IEnumerable<WorkPeriodViewModel> _workPeriods;
public IEnumerable<WorkPeriodViewModel> WorkPeriods
{
get
{
return _workPeriods ?? (_workPeriods = Dao.Last<WorkPeriod>(30)
.OrderByDescending(x => x.Id)
.Select(x => new WorkPeriodViewModel(x)));
}
}
public ICaptionCommand StartOfDayCommand { get; set; }
public ICaptionCommand EndOfDayCommand { get; set; }
public ICaptionCommand DisplayStartOfDayScreenCommand { get; set; }
public ICaptionCommand DisplayEndOfDayScreenCommand { get; set; }
public ICaptionCommand CancelCommand { get; set; }
public ICaptionCommand RequestShutdownCommand { get; set; }
public WorkPeriod LastWorkPeriod { get { return AppServices.MainDataContext.CurrentWorkPeriod; } }
public TimeSpan WorkPeriodTime { get; set; }
private int _openTicketCount;
public int OpenTicketCount
{
get { return _openTicketCount; }
set { _openTicketCount = value; RaisePropertyChanged("OpenTicketCount"); }
}
private string _openTicketLabel;
public string OpenTicketLabel
{
get { return _openTicketLabel; }
set { _openTicketLabel = value; RaisePropertyChanged("OpenTicketLabel"); }
}
private int _activeScreen;
public int ActiveScreen
{
get { return _activeScreen; }
set { _activeScreen = value; RaisePropertyChanged("ActiveScreen"); }
}
public string ConnectionCountLabel
{
get
{
return string.Format(Resources.ActiveConnections_f, AppServices.MessagingService.ConnectionCount);
}
}
public string StartDescription { get; set; }
public string EndDescription { get; set; }
public decimal CashAmount { get; set; }
public decimal CreditCardAmount { get; set; }
public decimal TicketAmount { get; set; }
public bool ShutdownRequested { get; set; }
public bool IsShutdownRequestVisible
{
get
{
if (AppServices.MainDataContext.IsCurrentWorkPeriodOpen)
return AppServices.MessagingService.ConnectionCount > 1;
return false;
}
}
public string LastEndOfDayLabel
{
get
{
if (AppServices.MainDataContext.IsCurrentWorkPeriodOpen)
{
var title1 = string.Format(Resources.WorkPeriodStartDate_f, LastWorkPeriod.StartDate.ToShortDateString());
var title2 = string.Format(Resources.WorkPeriodStartTime, LastWorkPeriod.StartDate.ToShortTimeString());
var title3 = string.Format(Resources.TotalWorkTimeDays_f, WorkPeriodTime.Days, WorkPeriodTime.Hours, WorkPeriodTime.Minutes);
if (WorkPeriodTime.Days == 0) title3 = string.Format(Resources.TotalWorkTimeHours_f, WorkPeriodTime.Hours, WorkPeriodTime.Minutes);
if (WorkPeriodTime.Hours == 0) title3 = string.Format(Resources.TotalWorkTimeMinutes_f, WorkPeriodTime.TotalMinutes);
return title1 + "\r\n" + title2 + "\r\n" + title3;
}
return Resources.StartWorkPeriodToEnablePos;
}
}
public WorkPeriodsViewModel()
{
StartOfDayCommand = new CaptionCommand<string>(Resources.StartWorkPeriod, OnStartOfDayExecute, CanStartOfDayExecute);
EndOfDayCommand = new CaptionCommand<string>(Resources.EndWorkPeriod, OnEndOfDayExecute, CanEndOfDayExecute);
DisplayStartOfDayScreenCommand = new CaptionCommand<string>(Resources.StartWorkPeriod, OnDisplayStartOfDayScreenCommand, CanStartOfDayExecute);
DisplayEndOfDayScreenCommand = new CaptionCommand<string>(Resources.EndWorkPeriod, OnDisplayEndOfDayScreenCommand, CanEndOfDayExecute);
CancelCommand = new CaptionCommand<string>(Resources.Cancel, OnCancel);
RequestShutdownCommand = new CaptionCommand<string>(Resources.RequestShutdown, OnShutDownRequested, CanRequestShutDown);
}
private bool CanRequestShutDown(string arg)
{
return _timer == null;
}
private Timer _timer;
private void OnShutDownRequested(string obj)
{
AppServices.MessagingService.SendMessage(Messages.ShutdownRequest, "0");
_timer = new Timer(OnTimer, null, 500, 5000);
}
private void OnTimer(object state)
{
AppServices.MessagingService.SendMessage(Messages.PingMessage, "1");
RaisePropertyChanged("ConnectionCountLabel");
if (AppServices.MessagingService.ConnectionCount < 2)
StopTimer();
AppServices.MainDispatcher.Invoke(new Action(Refresh));
}
private void StopTimer()
{
RaisePropertyChanged("IsShutdownRequestVisible");
if (_timer != null)
_timer.Change(Timeout.Infinite, Timeout.Infinite);
_timer = null;
}
private void OnCancel(string obj)
{
StopTimer();
ActiveScreen = 0;
}
private void OnDisplayEndOfDayScreenCommand(string obj)
{
ActiveScreen = 2;
}
private void OnDisplayStartOfDayScreenCommand(string obj)
{
ActiveScreen = 1;
}
private bool CanEndOfDayExecute(string arg)
{
return AppServices.ActiveAppScreen == AppScreens.WorkPeriods
&& OpenTicketCount == 0
&& (AppServices.MessagingService.ConnectionCount < 2 || AppServices.IsUserPermittedFor(PermissionNames.CloseActiveWorkPeriods))
&& WorkPeriodTime.TotalMinutes > 1
&& AppServices.MainDataContext.IsCurrentWorkPeriodOpen;
}
private void OnEndOfDayExecute(string obj)
{
StopTimer();
AppServices.MainDataContext.StopWorkPeriod(EndDescription);
Refresh();
AppServices.MainDataContext.CurrentWorkPeriod.PublishEvent(EventTopicNames.WorkPeriodStatusChanged);
RuleExecutor.NotifyEvent(RuleEventNames.WorkPeriodEnds, new { WorkPeriod = AppServices.MainDataContext.CurrentWorkPeriod, UserName = AppServices.CurrentLoggedInUser.Name });
InteractionService.UserIntraction.GiveFeedback(Resources.WorkPeriodEndsMessage);
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateNavigation);
}
private bool CanStartOfDayExecute(string arg)
{
return AppServices.ActiveAppScreen == AppScreens.WorkPeriods
&& (LastWorkPeriod == null || LastWorkPeriod.StartDate != LastWorkPeriod.EndDate);
}
private void OnStartOfDayExecute(string obj)
{
AppServices.MainDataContext.StartWorkPeriod(StartDescription, CashAmount, CreditCardAmount, TicketAmount);
Refresh();
AppServices.MainDataContext.CurrentWorkPeriod.PublishEvent(EventTopicNames.WorkPeriodStatusChanged);
RuleExecutor.NotifyEvent(RuleEventNames.WorkPeriodStarts, new { WorkPeriod = AppServices.MainDataContext.CurrentWorkPeriod, UserName = AppServices.CurrentLoggedInUser.Name });
InteractionService.UserIntraction.GiveFeedback(Resources.StartingWorkPeriodCompleted);
EventServiceFactory.EventService.PublishEvent(EventTopicNames.ActivateNavigation);
}
public void Refresh()
{
_workPeriods = null;
if (LastWorkPeriod != null)
WorkPeriodTime = new TimeSpan(DateTime.Now.Ticks - LastWorkPeriod.StartDate.Ticks);
OpenTicketCount = Dao.Count<Ticket>(x => !x.IsPaid);
if (OpenTicketCount > 0)
{
OpenTicketLabel = string.Format(Resources.ThereAreOpenTicketsWarning_f,
OpenTicketCount);
}
else OpenTicketLabel = "";
RaisePropertyChanged("WorkPeriods");
RaisePropertyChanged("LastEndOfDayLabel");
RaisePropertyChanged("WorkPeriods");
RaisePropertyChanged("IsShutdownRequestVisible");
RaisePropertyChanged("ConnectionCountLabel");
StartDescription = "";
EndDescription = "";
CashAmount = 0;
CreditCardAmount = 0;
TicketAmount = 0;
ActiveScreen = 0;
CommandManager.InvalidateRequerySuggested();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/WorkPeriods/WorkPeriodsViewModel.cs | C# | gpl3 | 9,632 |
using System.ComponentModel.Composition;
using System.Windows.Controls;
using Samba.Presentation.Common;
namespace Samba.Modules.SettingsModule.WorkPeriods
{
/// <summary>
/// Interaction logic for EndOfDayView.xaml
/// </summary>
///
[Export]
public partial class WorkPeriodsView : UserControl
{
[ImportingConstructor]
public WorkPeriodsView(WorkPeriodsViewModel viewModel)
{
InitializeComponent();
DataContext = viewModel;
}
private void StartDescriptionEditor_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
StartDescriptionEditor.BackgroundFocus();
}
private void EndDescriptionEditor_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
EndDescriptionEditor.BackgroundFocus();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/WorkPeriods/WorkPeriodsView.xaml.cs | C# | gpl3 | 901 |
using Samba.Domain.Models.Settings;
namespace Samba.Modules.SettingsModule.WorkPeriods
{
public class WorkPeriodViewModel
{
public WorkPeriod Model { get; set; }
public WorkPeriodViewModel(WorkPeriod model)
{
Model = model;
}
public string WorkPeriodLabel
{
get
{
if (Model.EndDate > Model.StartDate)
return
Model.StartDate.ToLongDateString() + " " + Model.StartDate.ToShortTimeString() + " - " +
Model.EndDate.ToLongDateString() + " " + Model.EndDate.ToShortTimeString();
return Model.StartDate.ToLongDateString() + " " + Model.StartDate.ToShortTimeString();
}
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/WorkPeriods/WorkPeriodViewModel.cs | C# | gpl3 | 818 |
using Samba.Domain.Models.Settings;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.SettingsModule
{
public class PrinterListViewModel : EntityCollectionViewModelBase<PrinterViewModel, Printer>
{
protected override PrinterViewModel CreateNewViewModel(Printer model)
{
return new PrinterViewModel(model);
}
protected override Printer CreateNewModel()
{
return new Printer();
}
protected override string CanDeleteItem(Printer model)
{
var count = Dao.Count<Terminal>(x => x.ReportPrinter.Id == model.Id || x.SlipReportPrinter.Id == model.Id);
if (count > 0) return Resources.DeleteErrorPrinterAssignedToTerminal;
count = Dao.Count<PrinterMap>(x => x.Printer.Id == model.Id);
if (count > 0) return Resources.DeleteErrorPrinterAssignedToPrinterMap;
return base.CanDeleteItem(model);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrinterListViewModel.cs | C# | gpl3 | 1,074 |
using System.Windows.Controls;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for NumeratorView.xaml
/// </summary>
public partial class NumeratorView : UserControl
{
public NumeratorView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/NumeratorView.xaml.cs | C# | gpl3 | 330 |
using System;
using System.ComponentModel.Composition;
using System.Linq;
using System.Net.Mail;
using Microsoft.Practices.Prism.MefExtensions.Modularity;
using Microsoft.Practices.Prism.Regions;
using Samba.Localization.Properties;
using Samba.Modules.SettingsModule.WorkPeriods;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.SettingsModule
{
[ModuleExport(typeof(SettingsModule))]
public class SettingsModule : ModuleBase
{
public ICategoryCommand ListProgramSettingsCommand { get; set; }
public ICategoryCommand ListTerminalsCommand { get; set; }
public ICategoryCommand ListPrintJobsCommand { get; set; }
public ICategoryCommand ListPrintersCommand { get; set; }
public ICategoryCommand ListPrinterTemplatesCommand { get; set; }
public ICategoryCommand ListNumeratorsCommand { get; set; }
public ICategoryCommand ListVoidReasonsCommand { get; set; }
public ICategoryCommand ListGiftReasonsCommand { get; set; }
public ICategoryCommand ListMenuItemSettingsCommand { get; set; }
public ICategoryCommand ListRuleActionsCommand { get; set; }
public ICategoryCommand ListRulesCommand { get; set; }
public ICategoryCommand ListTriggersCommand { get; set; }
public ICategoryCommand ShowBrowser { get; set; }
private BrowserViewModel _browserViewModel;
private SettingsViewModel _settingsViewModel;
private TerminalListViewModel _terminalListViewModel;
private PrintJobListViewModel _printJobsViewModel;
private PrinterListViewModel _printerListViewModel;
private PrinterTemplateCollectionViewModel _printerTemplateCollectionViewModel;
private NumeratorListViewModel _numeratorListViewModel;
private VoidReasonListViewModel _voidReasonListViewModel;
private GiftReasonListViewModel _giftReasonListViewModel;
private ProgramSettingsViewModel _menuItemSettingsViewModel;
private RuleActionListViewModel _ruleActionListViewModel;
private TriggerListViewModel _triggerListViewModel;
private RuleListViewModel _ruleListViewModel;
public ICategoryCommand NavigateWorkPeriodsCommand { get; set; }
private readonly IRegionManager _regionManager;
private readonly WorkPeriodsView _workPeriodsView;
protected override void OnInitialization()
{
_regionManager.RegisterViewWithRegion(RegionNames.MainRegion, typeof(WorkPeriodsView));
}
protected override void OnPostInitialization()
{
CommonEventPublisher.PublishDashboardCommandEvent(ShowBrowser);
CommonEventPublisher.PublishDashboardCommandEvent(ListProgramSettingsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListTerminalsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListPrintersCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListPrintJobsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListPrinterTemplatesCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListNumeratorsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListVoidReasonsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListGiftReasonsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListMenuItemSettingsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListRuleActionsCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListRulesCommand);
CommonEventPublisher.PublishDashboardCommandEvent(ListTriggersCommand);
CommonEventPublisher.PublishNavigationCommandEvent(NavigateWorkPeriodsCommand);
}
[ImportingConstructor]
public SettingsModule(IRegionManager regionManager, WorkPeriodsView workPeriodsView)
{
_regionManager = regionManager;
_workPeriodsView = workPeriodsView;
NavigateWorkPeriodsCommand = new CategoryCommand<string>(Resources.DayOperations, Resources.Common, "Images/Run.png", OnNavigateWorkPeriods, CanNavigateWorkPeriods);
ListProgramSettingsCommand = new CategoryCommand<string>(Resources.LocalSettings, Resources.Settings, OnListProgramSettings);
ListTerminalsCommand = new CategoryCommand<string>(Resources.Terminals, Resources.Settings, OnListTerminals);
ListPrintersCommand = new CategoryCommand<string>(Resources.Printers, Resources.Settings, OnListPrinters);
ListPrintJobsCommand = new CategoryCommand<string>(Resources.PrintJobs, Resources.Settings, OnListPrintJobs);
ListPrinterTemplatesCommand = new CategoryCommand<string>(Resources.PrinterTemplates, Resources.Settings, OnListPrinterTemplates);
ListNumeratorsCommand = new CategoryCommand<string>(Resources.Numerators, Resources.Settings, OnListNumerators);
ListVoidReasonsCommand = new CategoryCommand<string>(Resources.VoidReasons, Resources.Products, OnListVoidReasons);
ListGiftReasonsCommand = new CategoryCommand<string>(Resources.GiftReasons, Resources.Products, OnListGiftReasons);
ListMenuItemSettingsCommand = new CategoryCommand<string>(Resources.ProgramSettings, Resources.Settings, OnListMenuItemSettings) { Order = 10 };
ListRuleActionsCommand = new CategoryCommand<string>(Resources.RuleActions, Resources.Settings, OnListRuleActions);
ListRulesCommand = new CategoryCommand<string>(Resources.Rules, Resources.Settings, OnListRules);
ListTriggersCommand = new CategoryCommand<string>(Resources.Triggers, Resources.Settings, OnListTriggers);
ShowBrowser = new CategoryCommand<string>(Resources.SambaPosWebsite, Resources.SambaNetwork, OnShowBrowser) { Order = 99 };
PermissionRegistry.RegisterPermission(PermissionNames.OpenWorkPeriods, PermissionCategories.Navigation, Resources.CanStartEndOfDay);
PermissionRegistry.RegisterPermission(PermissionNames.CloseActiveWorkPeriods, PermissionCategories.Navigation, Resources.ForceClosingActiveWorkPeriod);
EventServiceFactory.EventService.GetEvent<GenericEvent<VisibleViewModelBase>>().Subscribe(s =>
{
if (s.Topic == EventTopicNames.ViewClosed)
{
if (s.Value == _settingsViewModel)
_settingsViewModel = null;
if (s.Value == _terminalListViewModel)
_terminalListViewModel = null;
if (s.Value == _printerListViewModel)
_printerListViewModel = null;
if (s.Value == _printerTemplateCollectionViewModel)
_printerTemplateCollectionViewModel = null;
if (s.Value == _printJobsViewModel)
_printJobsViewModel = null;
if (s.Value == _numeratorListViewModel)
_numeratorListViewModel = null;
if (s.Value == _voidReasonListViewModel)
_voidReasonListViewModel = null;
if (s.Value == _giftReasonListViewModel)
_giftReasonListViewModel = null;
if (s.Value == _ruleActionListViewModel)
_ruleActionListViewModel = null;
if (s.Value == _ruleListViewModel)
_ruleListViewModel = null;
if (s.Value == _triggerListViewModel)
_triggerListViewModel = null;
}
});
}
private void OnListTriggers(string obj)
{
if (_triggerListViewModel == null)
_triggerListViewModel = new TriggerListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_triggerListViewModel);
}
private void OnListRules(string obj)
{
if (_ruleListViewModel == null)
_ruleListViewModel = new RuleListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_ruleListViewModel);
}
private void OnListRuleActions(string obj)
{
if (_ruleActionListViewModel == null)
_ruleActionListViewModel = new RuleActionListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_ruleActionListViewModel);
}
private static bool CanNavigateWorkPeriods(string arg)
{
return AppServices.IsUserPermittedFor(PermissionNames.OpenWorkPeriods);
}
private void OnNavigateWorkPeriods(string obj)
{
AppServices.ActiveAppScreen = AppScreens.WorkPeriods;
_regionManager.Regions[RegionNames.MainRegion].Activate(_workPeriodsView);
((WorkPeriodsViewModel)_workPeriodsView.DataContext).Refresh();
}
private void OnListGiftReasons(string obj)
{
if (_giftReasonListViewModel == null)
_giftReasonListViewModel = new GiftReasonListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_giftReasonListViewModel);
}
private void OnListVoidReasons(string obj)
{
if (_voidReasonListViewModel == null)
_voidReasonListViewModel = new VoidReasonListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_voidReasonListViewModel);
}
private void OnListNumerators(string obj)
{
if (_numeratorListViewModel == null)
_numeratorListViewModel = new NumeratorListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_numeratorListViewModel);
}
private void OnListPrinterTemplates(string obj)
{
if (_printerTemplateCollectionViewModel == null)
_printerTemplateCollectionViewModel = new PrinterTemplateCollectionViewModel();
CommonEventPublisher.PublishViewAddedEvent(_printerTemplateCollectionViewModel);
}
private void OnListPrinters(string obj)
{
if (_printerListViewModel == null)
_printerListViewModel = new PrinterListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_printerListViewModel);
}
private void OnListPrintJobs(string obj)
{
if (_printJobsViewModel == null)
_printJobsViewModel = new PrintJobListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_printJobsViewModel);
}
private void OnListTerminals(string obj)
{
if (_terminalListViewModel == null)
_terminalListViewModel = new TerminalListViewModel();
CommonEventPublisher.PublishViewAddedEvent(_terminalListViewModel);
}
private void OnListMenuItemSettings(string obj)
{
if (_menuItemSettingsViewModel == null)
_menuItemSettingsViewModel = new ProgramSettingsViewModel();
CommonEventPublisher.PublishViewAddedEvent(_menuItemSettingsViewModel);
}
private void OnListProgramSettings(string obj)
{
if (_settingsViewModel == null)
_settingsViewModel = new SettingsViewModel();
CommonEventPublisher.PublishViewAddedEvent(_settingsViewModel);
}
private void OnShowBrowser(string obj)
{
if (_browserViewModel == null)
_browserViewModel = new BrowserViewModel();
CommonEventPublisher.PublishViewAddedEvent(_browserViewModel);
new Uri("http://network.sambapos.com").PublishEvent(EventTopicNames.BrowseUrl);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/SettingsModule.cs | C# | gpl3 | 12,135 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Samba.Domain.Models.Actions;
using Samba.Infrastructure.Data;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Presentation.Common.Services;
using Samba.Services;
namespace Samba.Modules.SettingsModule
{
public class RuleViewModel : EntityViewModelBase<AppRule>
{
private IWorkspace _workspace;
public RuleViewModel(AppRule model)
: base(model)
{
_actions = new ObservableCollection<ActionContainerViewModel>(Model.Actions.Select(x => new ActionContainerViewModel(x, this)));
SelectActionsCommand = new CaptionCommand<string>(Resources.SelectActions, OnSelectActions);
Constraints = new ObservableCollection<RuleConstraintViewModel>();
if (!string.IsNullOrEmpty(model.EventConstraints))
{
Constraints.AddRange(
model.EventConstraints.Split('#')
.Where(x => !x.StartsWith("SN$"))
.Select(x => new RuleConstraintViewModel(x)));
var settingData =
model.EventConstraints.Split('#').Where(x => x.StartsWith("SN$")).FirstOrDefault();
if (!string.IsNullOrEmpty(settingData))
{
var settingParts = settingData.Split(';');
if (settingParts.Length == 3)
{
SettingConstraintName = settingParts[0].Replace("SN$", "");
SettingConstraintOperation = settingParts[1];
SettingConstraintValue = settingParts[2];
}
}
}
}
private void OnSelectActions(string obj)
{
IList<IOrderable> selectedValues = new List<IOrderable>(Model.Actions);
var selectedIds = selectedValues.Select(x => ((ActionContainer)x).AppActionId);
IList<IOrderable> values = new List<IOrderable>(_workspace.All<AppAction>(x => !selectedIds.Contains(x.Id)).Select(x => new ActionContainer(x)));
var choosenValues = InteractionService.UserIntraction.ChooseValuesFrom(values, selectedValues, Resources.ActionList,
Resources.SelectActions, Resources.Action, Resources.Actions);
foreach (var action in Model.Actions.ToList())
{
var laction = action;
if (choosenValues.FirstOrDefault(x => ((ActionContainer)x).AppActionId == laction.AppActionId) == null)
{
if (action.Id > 0)
_workspace.Delete(action);
}
}
Model.Actions.Clear();
choosenValues.Cast<ActionContainer>().ToList().ForEach(x => Model.Actions.Add(x));
_actions = new ObservableCollection<ActionContainerViewModel>(Model.Actions.Select(x => new ActionContainerViewModel(x, this)));
RaisePropertyChanged("Actions");
}
private ObservableCollection<ActionContainerViewModel> _actions;
public ObservableCollection<ActionContainerViewModel> Actions
{
get { return _actions; }
}
private ObservableCollection<RuleConstraintViewModel> _constraints;
public ObservableCollection<RuleConstraintViewModel> Constraints
{
get { return _constraints; }
set
{
_constraints = value;
RaisePropertyChanged("Constraints");
}
}
public string SettingConstraintName { get; set; }
public string SettingConstraintOperation { get; set; }
public string SettingConstraintValue { get; set; }
public IEnumerable<string> Operations { get { return new[] { "=", ">", "<", "!=" }; } }
public IEnumerable<RuleEvent> Events { get { return RuleActionTypeRegistry.RuleEvents.Values; } }
public ICaptionCommand SelectActionsCommand { get; set; }
public string EventName
{
get { return Model.EventName; }
set
{
Model.EventName = value;
Constraints = new ObservableCollection<RuleConstraintViewModel>(
RuleActionTypeRegistry.GetEventConstraints(Model.EventName));
}
}
protected override void Initialize(IWorkspace workspace)
{
_workspace = workspace;
}
public override Type GetViewType()
{
return typeof(RuleView);
}
public override string GetModelTypeString()
{
return Resources.Rule;
}
protected override void OnSave(string value)
{
Model.EventConstraints = string.Join("#", Constraints
.Where(x => x.Value != null)
.Select(x => x.GetConstraintData()));
if (!string.IsNullOrEmpty(SettingConstraintName))
{
if (!string.IsNullOrEmpty(Model.EventConstraints))
Model.EventConstraints = Model.EventConstraints + "#";
Model.EventConstraints += "SN$" + SettingConstraintName + ";" + (SettingConstraintOperation ?? "=") + ";" + SettingConstraintValue;
}
base.OnSave(value);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/RuleViewModel.cs | C# | gpl3 | 5,672 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for BrowserView.xaml
/// </summary>
public partial class BrowserView : UserControl
{
public BrowserView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/BrowserView.xaml.cs | C# | gpl3 | 657 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using Samba.Domain.Models.Settings;
using Samba.Infrastructure.Settings;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.SettingsModule
{
public class SettingsViewModel : VisibleViewModelBase
{
public SettingsViewModel()
{
SaveSettingsCommand = new CaptionCommand<string>(Resources.Save, OnSaveSettings);
StartMessagingServerCommand = new CaptionCommand<string>(Resources.StartClientNow, OnStartMessagingServer, CanStartMessagingServer);
DisplayCommonAppPathCommand = new CaptionCommand<string>(Resources.DisplayAppPath, OnDisplayAppPath);
DisplayUserAppPathCommand = new CaptionCommand<string>(Resources.DisplayUserPath, OnDisplayUserPath);
EditCreditCardProcessorSettings = new CaptionCommand<string>("Credit Card Processor Settings", OnEditCreditCardProcessorSettings, CanEditCreditCardProcessorSettings);
}
private bool CanEditCreditCardProcessorSettings(string arg)
{
return CreditCardProcessingService.GetDefaultProcessor() != null;
}
public bool IsCreditCardProcessorEditorVisible { get { return CreditCardProcessorNames.Count() > 0; } }
private static void OnEditCreditCardProcessorSettings(string obj)
{
var defaultProcessor = CreditCardProcessingService.GetDefaultProcessor();
if (defaultProcessor != null) defaultProcessor.EditSettings();
}
public void OnDisplayUserPath(string obj)
{
var prc = new System.Diagnostics.Process { StartInfo = { FileName = LocalSettings.UserPath } };
prc.Start();
}
public void OnDisplayAppPath(string obj)
{
var prc = new System.Diagnostics.Process { StartInfo = { FileName = LocalSettings.DataPath } };
prc.Start();
}
private static bool CanStartMessagingServer(string arg)
{
return AppServices.MessagingService.CanStartMessagingClient();
}
private static void OnStartMessagingServer(string obj)
{
AppServices.MessagingService.StartMessagingClient();
}
private void OnSaveSettings(string obj)
{
LocalSettings.SaveSettings();
((VisibleViewModelBase)this).PublishEvent(EventTopicNames.ViewClosed);
}
public ICaptionCommand SaveSettingsCommand { get; set; }
public ICaptionCommand StartMessagingServerCommand { get; set; }
public ICaptionCommand DisplayCommonAppPathCommand { get; set; }
public ICaptionCommand DisplayUserAppPathCommand { get; set; }
public ICaptionCommand EditCreditCardProcessorSettings { get; set; }
public string TerminalName
{
get { return LocalSettings.TerminalName; }
set { LocalSettings.TerminalName = value; }
}
public string ConnectionString
{
get { return LocalSettings.ConnectionString; }
set { LocalSettings.ConnectionString = value; }
}
public string MessagingServerName
{
get { return LocalSettings.MessagingServerName; }
set { LocalSettings.MessagingServerName = value; }
}
public int MessagingServerPort
{
get { return LocalSettings.MessagingServerPort; }
set { LocalSettings.MessagingServerPort = value; }
}
public bool StartMessagingClient
{
get { return LocalSettings.StartMessagingClient; }
set { LocalSettings.StartMessagingClient = value; }
}
public string Language
{
get { return LocalSettings.CurrentLanguage; }
set
{
if (string.IsNullOrEmpty(value))
{
LocalSettings.CurrentLanguage = "";
}
else if (LocalSettings.SupportedLanguages.Contains(value))
{
LocalSettings.CurrentLanguage = value;
}
else
{
var ci = CultureInfo.GetCultureInfo(value);
if (LocalSettings.SupportedLanguages.Contains(ci.TwoLetterISOLanguageName))
{
LocalSettings.CurrentLanguage = ci.TwoLetterISOLanguageName;
}
}
}
}
public bool OverrideWindowsRegionalSettings
{
get { return LocalSettings.OverrideWindowsRegionalSettings; }
set
{
LocalSettings.OverrideWindowsRegionalSettings = value;
RaisePropertyChanged("OverrideWindowsRegionalSettings");
}
}
private IEnumerable<string> _terminalNames;
public IEnumerable<string> TerminalNames
{
get { return _terminalNames ?? (_terminalNames = Dao.Distinct<Terminal>(x => x.Name)); }
}
private IEnumerable<CultureInfo> _supportedLanguages;
public IEnumerable<CultureInfo> SupportedLanguages
{
get
{
return _supportedLanguages ?? (_supportedLanguages =
LocalSettings.SupportedLanguages.Select(CultureInfo.GetCultureInfo).ToList().OrderBy(x => x.DisplayName));
}
}
public string MajorCurrencyName
{
get { return LocalSettings.MajorCurrencyName; }
set { LocalSettings.MajorCurrencyName = value; }
}
public string MinorCurrencyName
{
get { return LocalSettings.MinorCurrencyName; }
set { LocalSettings.MinorCurrencyName = value; }
}
public string PluralCurrencySuffix
{
get { return LocalSettings.PluralCurrencySuffix; }
set { LocalSettings.PluralCurrencySuffix = value; }
}
public IEnumerable<string> CreditCardProcessorNames { get { return CreditCardProcessingService.GetProcessors().Select(x => x.Name); } }
public string DefaultCreditCardProcessorName
{
get { return LocalSettings.DefaultCreditCardProcessorName; }
set
{
LocalSettings.DefaultCreditCardProcessorName =
CreditCardProcessorNames.Contains(value) ? value : "";
RaisePropertyChanged("DefaultCreditCardProcessorName");
}
}
protected override string GetHeaderInfo()
{
return Resources.ProgramSettings;
}
public override Type GetViewType()
{
return typeof(SettingsView);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/SettingsViewModel.cs | C# | gpl3 | 7,133 |
using System;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.SettingsModule
{
public class GiftReasonViewModel : EntityViewModelBase<Reason>
{
public GiftReasonViewModel(Reason model)
: base(model)
{
}
public override Type GetViewType()
{
return typeof(GiftReasonView);
}
public override string GetModelTypeString()
{
return Resources.GiftReason;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/GiftReasonViewModel.cs | C# | gpl3 | 596 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Samba.Domain.Models.Actions;
using Samba.Localization.Properties;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.SettingsModule
{
internal class ParameterValue
{
private readonly PropertyInfo _parameterInfo;
public string Name { get { return _parameterInfo.Name; } }
public string NameDisplay
{
get
{
var result = Resources.ResourceManager.GetString(Name);
return !string.IsNullOrEmpty(result) ? result + ":" : Name;
}
}
public Type ValueType { get { return _parameterInfo.PropertyType; } }
public string Value { get; set; }
private IEnumerable<string> _values;
public ParameterValue(PropertyInfo propertyInfo)
{
_parameterInfo = propertyInfo;
}
public IEnumerable<string> Values
{
get
{
if (ValueType == typeof(bool)) return new[] { "True", "False" };
return _values ?? (_values = RuleActionTypeRegistry.GetParameterSource(Name));
}
}
}
class RuleActionViewModel : EntityViewModelBase<AppAction>
{
public RuleActionViewModel(AppAction model)
: base(model)
{
}
public Dictionary<string, string> Parameters
{
get
{
if (string.IsNullOrEmpty(Model.Parameter)) return new Dictionary<string, string>();
return Model.Parameter.Split('#').ToDictionary(x => x.Split('=')[0], x => x.Split('=')[1]);
}
}
public string SelectedActionType
{
get { return Model.ActionType; }
set
{
Model.ActionType = value;
ParameterValues = CreateParameterValues(value);
RaisePropertyChanged("IsParameterLabelVisible");
}
}
public bool IsParameterLabelVisible { get { return ParameterValues.Count > 0; } }
private List<ParameterValue> CreateParameterValues(string value)
{
if (string.IsNullOrEmpty(value)) return new List<ParameterValue>();
var result = CreateParemeterValues(RuleActionTypeRegistry.ActionTypes[value]).ToList();
result.ForEach(x =>
{
if (Parameters.ContainsKey(x.Name))
x.Value = Parameters[x.Name];
});
return result;
}
private List<ParameterValue> _parameterValues;
public List<ParameterValue> ParameterValues
{
get { return _parameterValues ?? (_parameterValues = CreateParameterValues(Model.ActionType)); }
set
{
_parameterValues = value;
RaisePropertyChanged("ParameterValues");
}
}
public IEnumerable<RuleActionType> ActionTypes { get { return RuleActionTypeRegistry.ActionTypes.Values; } }
private static IEnumerable<ParameterValue> CreateParemeterValues(RuleActionType actionType)
{
if (actionType.ParameterObject != null)
return actionType.ParameterObject.GetType().GetProperties().Select(x => new ParameterValue(x));
return new List<ParameterValue>();
}
protected override void OnSave(string value)
{
base.OnSave(value);
Model.Parameter = string.Join("#", ParameterValues.Select(x => x.Name + "=" + x.Value));
}
public override Type GetViewType()
{
return typeof(RuleActionView);
}
public override string GetModelTypeString()
{
return Resources.RuleAction;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/RuleActionViewModel.cs | C# | gpl3 | 4,140 |
using System.Windows.Controls;
using System.Windows.Documents;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for PrinterTemplateView.xaml
/// </summary>
public partial class PrinterTemplateView : UserControl
{
public PrinterTemplateView()
{
InitializeComponent();
Loaded += PrinterTemplateView_Loaded;
}
void PrinterTemplateView_Loaded(object sender, System.Windows.RoutedEventArgs e)
{
var content = DataContext as PrinterTemplateViewModel;
if (content != null)
{
var doc = content.Descriptions;
HelpDocument.Blocks.Clear();
var p = new Paragraph();
p.Inlines.Add(new Bold(new Run("Printer Template Token Documentation")));
p.Inlines.Add(new LineBreak());
p.Inlines.Add(new LineBreak());
foreach (var value in doc)
{
p.Inlines.Add(new Bold(new Run(value.Key)));
p.Inlines.Add(new Run(" " + value.Value));
p.Inlines.Add(new LineBreak());
}
HelpDocument.Blocks.Add(p);
}
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrinterTemplateView.xaml.cs | C# | gpl3 | 1,320 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for TriggerView.xaml
/// </summary>
public partial class TriggerView : UserControl
{
public TriggerView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/TriggerView.xaml.cs | C# | gpl3 | 657 |
using System;
using System.Linq;
using Samba.Domain.Models.Tickets;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Presentation.Common.Services;
using Samba.Services;
namespace Samba.Modules.SettingsModule
{
public class VoidReasonListViewModel : EntityCollectionViewModelBase<VoidReasonViewModel, Reason>
{
public ICaptionCommand CreateBatchVoidReasons { get; set; }
public VoidReasonListViewModel()
{
CreateBatchVoidReasons = new CaptionCommand<string>(Resources.BatchAddVoidReasons, OnCreateBatchVoidReasons);
CustomCommands.Add(CreateBatchVoidReasons);
}
private void OnCreateBatchVoidReasons(string obj)
{
var values = InteractionService.UserIntraction.GetStringFromUser(
Resources.BatchAddVoidReasons,
Resources.BatchAddVoidReasonsDialogHint);
var createdItems = new DataCreationService().BatchCreateReasons(values, 0, Workspace);
Workspace.CommitChanges();
foreach (var mv in createdItems.Select(CreateNewViewModel))
{
mv.Init(Workspace);
Items.Add(mv);
}
}
protected override VoidReasonViewModel CreateNewViewModel(Reason model)
{
return new VoidReasonViewModel(model);
}
protected override Reason CreateNewModel()
{
return new Reason { ReasonType = 0 };
}
protected override System.Collections.ObjectModel.ObservableCollection<VoidReasonViewModel> GetItemsList()
{
return BuildViewModelList(Workspace.All<Reason>(x => x.ReasonType == 0));
}
protected override string CanDeleteItem(Reason model)
{
var voids = Dao.Count<TicketItem>(x => x.Voided && x.ReasonId == model.Id);
return voids > 0 ? Resources.DeleteErrorVoidReasonUsed : "";
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/VoidReasonListViewModel.cs | C# | gpl3 | 2,113 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Services;
namespace Samba.Modules.SettingsModule
{
public class ProgramSettingsViewModel : VisibleViewModelBase
{
public string WeightBarcodePrefix { get; set; }
public int WeightBarcodeItemLength { get; set; }
public string WeightBarcodeItemFormat { get; set; }
public int WeightBarcodeQuantityLength { get; set; }
public decimal AutoRoundDiscount { get; set; }
public string PhoneNumberInputMask { get; set; }
public ICaptionCommand SaveCommand { get; set; }
public ProgramSettingsViewModel()
{
SaveCommand = new CaptionCommand<string>(Resources.Save, OnSave);
WeightBarcodePrefix = AppServices.SettingService.WeightBarcodePrefix;
WeightBarcodeItemLength = AppServices.SettingService.WeightBarcodeItemLength;
WeightBarcodeItemFormat = AppServices.SettingService.WeightBarcodeItemFormat;
WeightBarcodeQuantityLength = AppServices.SettingService.WeightBarcodeQuantityLength;
PhoneNumberInputMask = AppServices.SettingService.PhoneNumberInputMask;
AutoRoundDiscount = AppServices.SettingService.AutoRoundDiscount;
}
private void OnSave(object obj)
{
AppServices.SettingService.WeightBarcodePrefix = WeightBarcodePrefix;
AppServices.SettingService.WeightBarcodeItemLength = WeightBarcodeItemLength;
AppServices.SettingService.WeightBarcodeQuantityLength = WeightBarcodeQuantityLength;
AppServices.SettingService.AutoRoundDiscount = AutoRoundDiscount;
AppServices.SettingService.WeightBarcodeItemFormat = WeightBarcodeItemFormat;
AppServices.SettingService.PhoneNumberInputMask = PhoneNumberInputMask;
AppServices.SettingService.SaveChanges();
CommonEventPublisher.PublishViewClosedEvent(this);
}
protected override string GetHeaderInfo()
{
return Resources.ProgramSettings;
}
public override Type GetViewType()
{
return typeof(ProgramSettingsView);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/ProgramSettingsViewModel.cs | C# | gpl3 | 2,397 |
using System;
using System.Collections.Generic;
using Samba.Domain.Models.Settings;
using Samba.Localization.Properties;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.SettingsModule
{
public class PrinterTemplateViewModel : EntityViewModelBase<PrinterTemplate>
{
public PrinterTemplateViewModel(PrinterTemplate model)
: base(model)
{
}
public string HeaderTemplate { get { return Model.HeaderTemplate; } set { Model.HeaderTemplate = value; } }
public string LineTemplate { get { return Model.LineTemplate; } set { Model.LineTemplate = value; } }
public string VoidedLineTemplate { get { return Model.VoidedLineTemplate; } set { Model.VoidedLineTemplate = value; } }
public string GiftLineTemplate { get { return Model.GiftLineTemplate; } set { Model.GiftLineTemplate = value; } }
public string FooterTemplate { get { return Model.FooterTemplate; } set { Model.FooterTemplate = value; } }
public string GroupTemplate { get { return Model.GroupTemplate; } set { Model.GroupTemplate = value; } }
public bool MergeLines { get { return Model.MergeLines; } set { Model.MergeLines = value; } }
public override Type GetViewType()
{
return typeof(PrinterTemplateView);
}
public override string GetModelTypeString()
{
return Resources.PrinterTemplate;
}
private IDictionary<string, string> _descriptions;
public IDictionary<string, string> Descriptions
{
get { return _descriptions ?? (_descriptions = CreateDescriptions()); }
}
private static IDictionary<string, string> CreateDescriptions()
{
var result = new Dictionary<string, string>();
result.Add(Resources.TF_TicketDate, Resources.TicketDate);
result.Add(Resources.TF_TicketTime, Resources.TicketTime);
result.Add(Resources.TF_DayDate, Resources.DayDate);
result.Add(Resources.TF_DayTime, Resources.DayTime);
result.Add(Resources.TF_UniqueTicketId, Resources.UniqueTicketId);
result.Add(Resources.TF_TicketNumber, Resources.TicketNumber);
result.Add(Resources.TF_TicketTag, Resources.TicketTag);
result.Add("{DEPARTMENT}", Resources.DepartmentName);
result.Add(Resources.TF_OptionalTicketTag, Resources.OptionalTicketTag);
result.Add("{TICKETTAG:X}", Resources.ForPrintingTicketTagValue);
result.Add("{SETTING:X}", Resources.ForPrintingAppSettingValue);
result.Add(Resources.TF_TableOrUserName, Resources.TableOrUserName);
result.Add(Resources.TF_UserName, Resources.UserName);
result.Add(Resources.TF_TableName, Resources.TableName);
result.Add(Resources.TF_TicketNote, Resources.TicketNote);
result.Add(Resources.TF_AccountName, Resources.AccountName);
result.Add("{ACC GROUPCODE}", Resources.AccountGroupCode);
result.Add(Resources.TF_AccountAddress, Resources.AccountAddress);
result.Add(Resources.TF_AccountPhone, Resources.AccountPhone);
result.Add("{ACC NOTE}", Resources.AccountNote);
result.Add("{ACC BALANCE}", Resources.AccountBalance);
result.Add(Resources.TF_LineItemQuantity, Resources.LineItemQuantity);
result.Add(Resources.TF_LineItemName, Resources.LineItemName);
result.Add(Resources.TF_LineItemPrice, Resources.LineItemPrice);
result.Add(Resources.TF_LineItemPriceCents, Resources.LineItemPriceCents);
result.Add(Resources.TF_LineItemTotal, Resources.LineItemTotal);
result.Add(Resources.TF_LineItemTotalAndQuantity, Resources.LineItemQuantity);
result.Add(Resources.TF_LineItemTotalWithoutGifts, Resources.LineItemTotalWithoutGifts);
result.Add(Resources.TF_LineItemDetails, Resources.LineItemDetails);
result.Add(Resources.TF_LineItemDetailPrice, Resources.LineItemDetailPrice);
result.Add(Resources.TF_LineItemDetailQuantity, Resources.LineItemDetailQuantity);
result.Add(Resources.TF_LineOrderNumber, Resources.LineOrderNumber);
result.Add("{ITEM TAG}", Resources.ItemTag);
result.Add("{ITEM TAG:n}", Resources.nthItemTag);
result.Add("{PRODUCT TAG}", Resources.LineItemProductTag);
result.Add("{PRODUCT GROUP}", Resources.ProductGroup);
result.Add("{PRICE TAG}", Resources.LinePriceTag);
result.Add(Resources.TF_LineGiftOrVoidReason, Resources.LineGiftOrVoidReason);
result.Add(Resources.TF_TicketTotal, Resources.TicketTotal);
result.Add(Resources.TF_TicketPaidTotal, Resources.TicketPaidTotal);
result.Add("{PLAIN TOTAL}", Resources.TicketSubTotal);
result.Add("{DISCOUNT TOTAL}", Resources.DiscountTotal);
result.Add("{TAX TOTAL}", Resources.VatTotal);
result.Add("{TAX DETAILS}", Resources.VatTotalsGroupedByVatTemplate);
result.Add("{SERVICE TOTAL}", Resources.TaxServiceTotal);
result.Add("{SERVICE DETAILS}", Resources.TaxTotalsGroupedByTaxTemplate);
result.Add(Resources.TF_TicketRemainingAmount, Resources.TicketRemainingAmount);
result.Add(Resources.TF_RemainingAmountIfPaid, Resources.RemainingAmountIfPaid);
result.Add("{TOTAL TEXT}", Resources.TextWrittenTotalValue);
result.Add(Resources.TF_DiscountTotalAndTicketTotal, Resources.DiscountTotalAndTicketTotal);
return result;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrinterTemplateViewModel.cs | C# | gpl3 | 5,763 |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using System.Windows;
using Samba.Infrastructure.Cron;
using Samba.Localization.Properties;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Presentation.Common.Services;
using Samba.Services;
using Trigger = Samba.Domain.Models.Settings.Trigger;
namespace Samba.Modules.SettingsModule
{
internal class CommonCronSetting
{
public CommonCronSetting(string name, string minute, string hour, string day, string month, string weekday)
{
SettingName = name;
Minute = minute;
Hour = hour;
Day = day;
Month = month;
Weekday = weekday;
}
private string _settingName;
public string SettingName
{
get { return string.Format("{0} ({1})", _settingName, Expression.Trim()); }
set { _settingName = value; }
}
public string Minute { get; set; }
public string Hour { get; set; }
public string Day { get; set; }
public string Month { get; set; }
public string Weekday { get; set; }
public string Expression { get { return string.Format("{0} {1} {2} {3} {4}", Minute, Hour, Day, Month, Weekday); } }
}
class TriggerViewModel : EntityViewModelBase<Trigger>
{
public TriggerViewModel(Trigger model)
: base(model)
{
GenerateCommonSettings();
if (!string.IsNullOrEmpty(model.Expression))
{
var parts = Model.Expression.Split(' ');
if (parts.Length == 5)
{
Minute = parts[0];
Hour = parts[1];
Day = parts[2];
Month = parts[3];
Weekday = parts[4];
}
}
TestExpressionCommand = new CaptionCommand<string>("Test", OnTestExpression);
}
private DateTime? GetNextDateTime()
{
try
{
DateTime nextTime;
var cs = CronSchedule.Parse(Expression);
cs.GetNext(DateTime.Now, out nextTime);
return nextTime;
}
catch (Exception)
{
return null;
}
}
private string GetTestMessage()
{
var nextTime = GetNextDateTime();
if (nextTime != null)
{
var ts = nextTime.GetValueOrDefault() - DateTime.Now;
return Resources.ExpressionValid + "\r\n" + string.Format(Resources.TriggerTestResultMessage_f,
nextTime, ts.Days, ts.Hours, ts.Minutes);
}
return Resources.ErrorInExpression + "!";
}
private void OnTestExpression(string obj)
{
MessageBox.Show(GetTestMessage());
}
private void GenerateCommonSettings()
{
CommonCronSettings = new List<CommonCronSetting>
{
new CommonCronSetting(Resources.EveryMinute, "*", "*", "*", "*", "*"),
new CommonCronSetting(Resources.Every5Minutes, "*/5", "*", "*", "*", "*"),
new CommonCronSetting(Resources.TwiceAnHour, "0,30", "*", "*", "*", "*"),
new CommonCronSetting(Resources.OnceAnHour, "0", "*", "*", "*", "*"),
new CommonCronSetting(Resources.TwiceADay, "0", "0,12", "*", "*", "*"),
new CommonCronSetting(Resources.OnceADay, "0", "0", "*", "*", "*"),
new CommonCronSetting(Resources.OnceAWeek, "0", "0", "*", "*", "0"),
new CommonCronSetting(Resources.FirstAndFifteenth, "0", "0", "1,15", "*", "*"),
new CommonCronSetting(Resources.OnceAMonth, "0", "0", "1", "*", "*"),
new CommonCronSetting(Resources.OnceAYear, "0", "0", "1", "1", "*")
};
CommonMinuteCronSettings = new List<CommonCronSetting>
{
new CommonCronSetting(Resources.EveryMinute, "*", "", "", "", ""),
new CommonCronSetting(Resources.EveryOtherMinute, "*/2", "", "", "", ""),
new CommonCronSetting(Resources.Every5Minutes, "*/5", "", "", "", ""),
new CommonCronSetting(Resources.Every10Minutes, "*/10", "", "", "", ""),
new CommonCronSetting(Resources.Every15Minutes, "*/15", "", "", "", ""),
new CommonCronSetting(Resources.Every30Minutes, "0,30", "", "", "", "")
};
for (var i = 0; i < 59; i++)
{
if (i == 0) CommonMinuteCronSettings.Add(new CommonCronSetting(Resources.TopOfTheHour, "0", "", "", "", ""));
else if (i == 15) CommonMinuteCronSettings.Add(new CommonCronSetting(Resources.QuarterPast, "15", "", "", "", ""));
else if (i == 30) CommonMinuteCronSettings.Add(new CommonCronSetting(Resources.HalfPast, "30", "", "", "", ""));
else if (i == 15) CommonMinuteCronSettings.Add(new CommonCronSetting(Resources.QuarterTil, "45", "", "", "", ""));
else CommonMinuteCronSettings.Add(new CommonCronSetting(i.ToString("00"), i.ToString(), "", "", "", ""));
}
CommonHourCronSettings = new List<CommonCronSetting>
{
new CommonCronSetting(Resources.EveryHour, "", "*", "", "", ""),
new CommonCronSetting(Resources.EveryOtherHour, "", "*/2", "", "", ""),
new CommonCronSetting(Resources.Every3Hours, "", "*/3", "", "", ""),
new CommonCronSetting(Resources.Every4Hours, "", "*/4", "", "", ""),
new CommonCronSetting(Resources.Every6Hours, "", "*/6", "", "", ""),
new CommonCronSetting(Resources.Every12Hours, "", "0,12", "", "", ""),
new CommonCronSetting(Resources.TwelveAmMidnight, "", "0", "", "", "")
};
for (int i = 1; i < 24; i++)
{
if (i == 12) CommonHourCronSettings.Add(new CommonCronSetting(string.Format("{0} {1} {2}", i, Resources.PM, Resources.Noon), "", i.ToString(), "", "", ""));
else if (i > 12) CommonHourCronSettings.Add(new CommonCronSetting(string.Format("{0} {1}", i, Resources.PM), "", i.ToString(), "", "", ""));
else CommonHourCronSettings.Add(new CommonCronSetting(string.Format("{0} {1}", i, Resources.AM), "", i.ToString(), "", "", ""));
}
CommonDayCronSettings = new List<CommonCronSetting>
{
new CommonCronSetting(Resources.EveryDay, "", "", "*", "", ""),
new CommonCronSetting(Resources.EveryOtherDay, "", "", "*/2", "", ""),
new CommonCronSetting(Resources.FirstAndFifteenth, "", "", "1,15", "", "")
};
for (int i = 1; i < 32; i++)
{
if (i == 1 || i == 21 || i == 31) CommonDayCronSettings.Add(new CommonCronSetting(i + "st", "", "", i.ToString(), "", ""));
else if (i == 2 || i == 22) CommonDayCronSettings.Add(new CommonCronSetting(i + "nd", "", "", i.ToString(), "", ""));
else if (i == 3 || i == 23) CommonDayCronSettings.Add(new CommonCronSetting(i + "rd", "", "", i.ToString(), "", ""));
else CommonDayCronSettings.Add(new CommonCronSetting(i + "th", "", "", i.ToString(), "", ""));
}
CommonMonthCronSettings = new List<CommonCronSetting>
{
new CommonCronSetting(Resources.EveryMonth, "", "", "", "*", ""),
new CommonCronSetting(Resources.EveryOtherMonth, "", "", "", "*/2", ""),
new CommonCronSetting(Resources.Every3Months, "", "", "", "*/4", ""),
new CommonCronSetting(Resources.Every6Months, "", "", "", "1,7", "")
};
for (int i = 0; i < 12; i++)
{
CommonMonthCronSettings.Add(new CommonCronSetting(CultureInfo.CurrentCulture.DateTimeFormat.MonthNames[i], "", "", "", (i + 1).ToString(), ""));
}
CommonWeekdayCronSettings = new List<CommonCronSetting>
{
new CommonCronSetting(Resources.EveryWeekday, "", "", "", "", "*"),
new CommonCronSetting(Resources.MonThruFri, "", "", "", "", "1-5"),
new CommonCronSetting(Resources.SatAndSun, "", "", "", "", "6,0"),
new CommonCronSetting(Resources.MonWedFri, "", "", "", "", "1,3,5"),
new CommonCronSetting(Resources.TuesAndThurs, "", "", "", "", "2,4")
};
for (var i = 0; i < 7; i++)
{
CommonWeekdayCronSettings.Add(new CommonCronSetting(CultureInfo.CurrentCulture.DateTimeFormat.DayNames[i], "", "", "", "", i.ToString()));
}
}
public string Expression
{
get { return Model.Expression; }
set
{
Model.Expression = value;
RaisePropertyChanged("Expression");
}
}
public ICaptionCommand TestExpressionCommand { get; set; }
public List<CommonCronSetting> CommonCronSettings { get; set; }
public List<CommonCronSetting> CommonMinuteCronSettings { get; set; }
public List<CommonCronSetting> CommonHourCronSettings { get; set; }
public List<CommonCronSetting> CommonDayCronSettings { get; set; }
public List<CommonCronSetting> CommonMonthCronSettings { get; set; }
public List<CommonCronSetting> CommonWeekdayCronSettings { get; set; }
private CommonCronSetting _selectedCronSetting;
public CommonCronSetting SelectedCronSetting
{
get { return _selectedCronSetting; }
set { _selectedCronSetting = value; UpdateCronSetting(value); }
}
private CommonCronSetting _selectedMinuteCronSetting;
public CommonCronSetting SelectedMinuteCronSetting
{
get { return _selectedMinuteCronSetting; }
set { _selectedMinuteCronSetting = value; UpdateCronSetting(value); RaisePropertyChanged("SelectedMinuteCronSetting"); }
}
private CommonCronSetting _selectedHourCronSetting;
public CommonCronSetting SelectedHourCronSetting
{
get { return _selectedHourCronSetting; }
set { _selectedHourCronSetting = value; UpdateCronSetting(value); RaisePropertyChanged("SelectedHourCronSetting"); }
}
private CommonCronSetting _selectedDayCronSetting;
public CommonCronSetting SelectedDayCronSetting
{
get { return _selectedDayCronSetting; }
set { _selectedDayCronSetting = value; UpdateCronSetting(value); RaisePropertyChanged("SelectedDayCronSetting"); }
}
private CommonCronSetting _selectedMonthCronSetting;
public CommonCronSetting SelectedMonthCronSetting
{
get { return _selectedMonthCronSetting; }
set { _selectedMonthCronSetting = value; UpdateCronSetting(value); RaisePropertyChanged("SelectedMonthCronSetting"); }
}
private CommonCronSetting _selectedWeekdayCronSetting;
public CommonCronSetting SelectedWeekdayCronSetting
{
get { return _selectedWeekdayCronSetting; }
set { _selectedWeekdayCronSetting = value; UpdateCronSetting(value); RaisePropertyChanged("SelectedWeekdayCronSetting"); }
}
private string _minute;
public string Minute
{
get { return _minute; }
set { _minute = value; RaisePropertyChanged("Minute"); UpdateExpression(); }
}
private string _hour;
public string Hour
{
get { return _hour; }
set { _hour = value; RaisePropertyChanged("Hour"); UpdateExpression(); }
}
private string _day;
public string Day
{
get { return _day; }
set { _day = value; RaisePropertyChanged("Day"); UpdateExpression(); }
}
private string _month;
public string Month
{
get { return _month; }
set { _month = value; RaisePropertyChanged("Month"); UpdateExpression(); }
}
private string _weekday;
public string Weekday
{
get { return _weekday; }
set { _weekday = value; RaisePropertyChanged("Weekday"); UpdateExpression(); }
}
public DateTime LastTrigger { get { return Model.LastTrigger; } set { Model.LastTrigger = value; } }
public void UpdateCronSetting(CommonCronSetting cronSetting)
{
if (!string.IsNullOrEmpty(cronSetting.Minute)) Minute = cronSetting.Minute;
if (!string.IsNullOrEmpty(cronSetting.Hour)) Hour = cronSetting.Hour;
if (!string.IsNullOrEmpty(cronSetting.Day)) Day = cronSetting.Day;
if (!string.IsNullOrEmpty(cronSetting.Month)) Month = cronSetting.Month;
if (!string.IsNullOrEmpty(cronSetting.Weekday)) Weekday = cronSetting.Weekday;
}
public void UpdateExpression()
{
_selectedMinuteCronSetting = CommonMinuteCronSettings.FirstOrDefault(x => x.Minute == Minute);
_selectedHourCronSetting = CommonHourCronSettings.FirstOrDefault(x => x.Hour == Hour);
_selectedDayCronSetting = CommonDayCronSettings.FirstOrDefault(x => x.Day == Day);
_selectedMonthCronSetting = CommonMonthCronSettings.FirstOrDefault(x => x.Month == Month);
_selectedWeekdayCronSetting = CommonWeekdayCronSettings.FirstOrDefault(x => x.Weekday == Weekday);
RaisePropertyChanged("SelectedMinuteCronSetting");
RaisePropertyChanged("SelectedHourCronSetting");
RaisePropertyChanged("SelectedDayCronSetting");
RaisePropertyChanged("SelectedMonthCronSetting");
RaisePropertyChanged("SelectedWeekdayCronSetting");
Expression = string.Format("{0} {1} {2} {3} {4}", Minute, Hour, Day, Month, Weekday);
_selectedCronSetting = CommonCronSettings.FirstOrDefault(x => x.Expression == Expression);
RaisePropertyChanged("SelectedCronSetting");
}
public override Type GetViewType()
{
return typeof(TriggerView);
}
public override string GetModelTypeString()
{
return Resources.Trigger;
}
protected override void OnSave(string value)
{
LastTrigger = DateTime.Now;
base.OnSave(value);
MethodQueue.Queue("UpdateCronObjects", TriggerService.UpdateCronObjects);
}
protected override string GetSaveErrorMessage()
{
var nextTime = GetNextDateTime();
if (nextTime == null)
return Resources.ErrorInExpression + "!";
return base.GetSaveErrorMessage();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/TriggerViewModel.cs | C# | gpl3 | 16,784 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for CustomPrinterView.xaml
/// </summary>
public partial class PrintJobView : UserControl
{
public PrintJobView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrintJobView.xaml.cs | C# | gpl3 | 665 |
using Samba.Domain.Models.Settings;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common.ModelBase;
namespace Samba.Modules.SettingsModule
{
public class PrinterTemplateCollectionViewModel : EntityCollectionViewModelBase<PrinterTemplateViewModel, PrinterTemplate>
{
protected override PrinterTemplateViewModel CreateNewViewModel(PrinterTemplate model)
{
return new PrinterTemplateViewModel(model);
}
protected override PrinterTemplate CreateNewModel()
{
return new PrinterTemplate();
}
protected override string CanDeleteItem(PrinterTemplate model)
{
var count = Dao.Count<PrinterMap>(x => x.PrinterTemplate.Id == model.Id);
if (count > 0) return Resources.DeleteErrorTemplateUsedInPrintJob;
return base.CanDeleteItem(model);
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrinterTemplateCollectionViewModel.cs | C# | gpl3 | 955 |
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using Samba.Domain.Models.Settings;
using Samba.Domain.Models.Tickets;
using Samba.Infrastructure.Data;
using Samba.Localization.Properties;
using Samba.Persistance.Data;
using Samba.Presentation.Common;
using Samba.Presentation.Common.ModelBase;
using Samba.Presentation.Common.Services;
namespace Samba.Modules.SettingsModule
{
public class TerminalViewModel : EntityViewModelBase<Terminal>
{
public TerminalViewModel(Terminal model)
: base(model)
{
SelectPrintJobsCommand = new CaptionCommand<string>(Resources.SelectPrintJob, OnAddPrintJob);
}
private IWorkspace _workspace;
public bool IsDefault { get { return Model.IsDefault; } set { Model.IsDefault = value; } }
public bool AutoLogout { get { return Model.AutoLogout; } set { Model.AutoLogout = value; } }
public bool HideExitButton { get { return Model.HideExitButton; } set { Model.HideExitButton = value; } }
public int? DepartmentId { get { return Model.DepartmentId; } set { Model.DepartmentId = value.GetValueOrDefault(0); } }
public Printer SlipReportPrinter { get { return Model.SlipReportPrinter; } set { Model.SlipReportPrinter = value; } }
public Printer ReportPrinter { get { return Model.ReportPrinter; } set { Model.ReportPrinter = value; } }
public ObservableCollection<PrintJob> PrintJobs { get; set; }
public ObservableCollection<Department> Departments { get; set; }
public IEnumerable<Printer> Printers { get; private set; }
public IEnumerable<PrinterTemplate> PrinterTemplates { get; private set; }
public ICaptionCommand SelectPrintJobsCommand { get; set; }
public override Type GetViewType()
{
return typeof(TerminalView);
}
public override string GetModelTypeString()
{
return Resources.Terminal;
}
protected override void Initialize(IWorkspace workspace)
{
_workspace = workspace;
Printers = workspace.All<Printer>();
PrinterTemplates = workspace.All<PrinterTemplate>();
PrintJobs = new ObservableCollection<PrintJob>(Model.PrintJobs);
Departments = new ObservableCollection<Department>(workspace.All<Department>());
}
private void OnAddPrintJob(string obj)
{
IList<IOrderable> values = new List<IOrderable>(_workspace.All<PrintJob>()
.Where(x => PrintJobs.SingleOrDefault(y => y.Id == x.Id) == null));
IList<IOrderable> selectedValues = new List<IOrderable>(PrintJobs.Select(x => x));
var choosenValues =
InteractionService.UserIntraction.ChooseValuesFrom(values, selectedValues, Resources.PrintJobList,
string.Format(Resources.SelectPrintJobsForTerminalHint_f, Model.Name), Resources.PrintJob, Resources.PrintJobs);
PrintJobs.Clear();
Model.PrintJobs.Clear();
foreach (PrintJob choosenValue in choosenValues)
{
Model.PrintJobs.Add(choosenValue);
PrintJobs.Add(choosenValue);
}
}
protected override string GetSaveErrorMessage()
{
if (Model.IsDefault)
{
var terminal = Dao.Query<Terminal>(x => x.IsDefault).SingleOrDefault();
if (terminal != null && terminal.Id != Model.Id)
return Resources.SaveErrorMultipleDefaultTerminals;
}
return base.GetSaveErrorMessage();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/TerminalViewModel.cs | C# | gpl3 | 3,799 |
using System.Windows.Controls;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for TerminalView.xaml
/// </summary>
public partial class TerminalView : UserControl
{
public TerminalView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/TerminalView.xaml.cs | C# | gpl3 | 327 |
using System.Windows.Controls;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for PrinterView.xaml
/// </summary>
public partial class PrinterView : UserControl
{
public PrinterView()
{
InitializeComponent();
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/PrinterView.xaml.cs | C# | gpl3 | 324 |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
namespace Samba.Modules.SettingsModule
{
/// <summary>
/// Interaction logic for RuleActionView.xaml
/// </summary>
public partial class RuleActionView : UserControl
{
public RuleActionView()
{
InitializeComponent();
}
}
public class PropertyEditorTemplateSelector : DataTemplateSelector
{
public DataTemplate TextTemplate { get; set; }
public DataTemplate ValueTemplate { get; set; }
public DataTemplate PasswordTemplate { get; set; }
public override DataTemplate SelectTemplate(object item,
DependencyObject container)
{
var pv = item as ParameterValue;
if (pv != null)
{
if (pv.Name.Contains("Password")) return PasswordTemplate;
if (pv.Values.Count() > 0) return ValueTemplate;
}
return TextTemplate;
}
}
}
| zzgaminginc-pointofssale | Samba.Modules.SettingsModule/RuleActionView.xaml.cs | C# | gpl3 | 1,337 |