code stringlengths 3 1.18M | language stringclasses 1 value |
|---|---|
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* A request message from a client to a server includes, within the
* first line of that message, the method to be applied to the resource,
* the identifier of the resource, and the protocol version in use.
* <pre>
* Request = Request-Line
* *(( general-header
* | request-header
* | entity-header ) CRLF)
* CRLF
* [ message-body ]
* </pre>
*
* @since 4.0
*/
public interface HttpRequest extends HttpMessage {
/**
* Returns the request line of this request.
* @return the request line.
*/
RequestLine getRequestLine();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import org.apache.ogt.http.params.HttpParams;
/**
* HTTP messages consist of requests from client to server and responses
* from server to client.
* <pre>
* HTTP-message = Request | Response ; HTTP/1.1 messages
* </pre>
* <p>
* HTTP messages use the generic message format of RFC 822 for
* transferring entities (the payload of the message). Both types
* of message consist of a start-line, zero or more header fields
* (also known as "headers"), an empty line (i.e., a line with nothing
* preceding the CRLF) indicating the end of the header fields,
* and possibly a message-body.
* </p>
* <pre>
* generic-message = start-line
* *(message-header CRLF)
* CRLF
* [ message-body ]
* start-line = Request-Line | Status-Line
* </pre>
*
* @since 4.0
*/
public interface HttpMessage {
/**
* Returns the protocol version this message is compatible with.
*/
ProtocolVersion getProtocolVersion();
/**
* Checks if a certain header is present in this message. Header values are
* ignored.
*
* @param name the header name to check for.
* @return true if at least one header with this name is present.
*/
boolean containsHeader(String name);
/**
* Returns all the headers with a specified name of this message. Header values
* are ignored. Headers are orderd in the sequence they will be sent over a
* connection.
*
* @param name the name of the headers to return.
* @return the headers whose name property equals <code>name</code>.
*/
Header[] getHeaders(String name);
/**
* Returns the first header with a specified name of this message. Header
* values are ignored. If there is more than one matching header in the
* message the first element of {@link #getHeaders(String)} is returned.
* If there is no matching header in the message <code>null</code> is
* returned.
*
* @param name the name of the header to return.
* @return the first header whose name property equals <code>name</code>
* or <code>null</code> if no such header could be found.
*/
Header getFirstHeader(String name);
/**
* Returns the last header with a specified name of this message. Header values
* are ignored. If there is more than one matching header in the message the
* last element of {@link #getHeaders(String)} is returned. If there is no
* matching header in the message <code>null</code> is returned.
*
* @param name the name of the header to return.
* @return the last header whose name property equals <code>name</code>.
* or <code>null</code> if no such header could be found.
*/
Header getLastHeader(String name);
/**
* Returns all the headers of this message. Headers are orderd in the sequence
* they will be sent over a connection.
*
* @return all the headers of this message
*/
Header[] getAllHeaders();
/**
* Adds a header to this message. The header will be appended to the end of
* the list.
*
* @param header the header to append.
*/
void addHeader(Header header);
/**
* Adds a header to this message. The header will be appended to the end of
* the list.
*
* @param name the name of the header.
* @param value the value of the header.
*/
void addHeader(String name, String value);
/**
* Overwrites the first header with the same name. The new header will be appended to
* the end of the list, if no header with the given name can be found.
*
* @param header the header to set.
*/
void setHeader(Header header);
/**
* Overwrites the first header with the same name. The new header will be appended to
* the end of the list, if no header with the given name can be found.
*
* @param name the name of the header.
* @param value the value of the header.
*/
void setHeader(String name, String value);
/**
* Overwrites all the headers in the message.
*
* @param headers the array of headers to set.
*/
void setHeaders(Header[] headers);
/**
* Removes a header from this message.
*
* @param header the header to remove.
*/
void removeHeader(Header header);
/**
* Removes all headers with a certain name from this message.
*
* @param name The name of the headers to remove.
*/
void removeHeaders(String name);
/**
* Returns an iterator of all the headers.
*
* @return Iterator that returns Header objects in the sequence they are
* sent over a connection.
*/
HeaderIterator headerIterator();
/**
* Returns an iterator of the headers with a given name.
*
* @param name the name of the headers over which to iterate, or
* <code>null</code> for all headers
*
* @return Iterator that returns Header objects with the argument name
* in the sequence they are sent over a connection.
*/
HeaderIterator headerIterator(String name);
/**
* Returns the parameters effective for this message as set by
* {@link #setParams(HttpParams)}.
*/
HttpParams getParams();
/**
* Provides parameters to be used for the processing of this message.
* @param params the parameters
*/
void setParams(HttpParams params);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.Serializable;
/**
* A resizable byte array.
*
* @since 4.0
*/
public final class ByteArrayBuffer implements Serializable {
private static final long serialVersionUID = 4359112959524048036L;
private byte[] buffer;
private int len;
/**
* Creates an instance of {@link ByteArrayBuffer} with the given initial
* capacity.
*
* @param capacity the capacity
*/
public ByteArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
this.buffer = new byte[capacity];
}
private void expand(int newlen) {
byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, newlen)];
System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
this.buffer = newbuffer;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final byte[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int newlen = this.len + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newlen;
}
/**
* Appends <code>b</code> byte to this buffer. The capacity of the buffer
* is increased, if necessary, to accommodate the additional byte.
*
* @param b the byte to be appended.
*/
public void append(int b) {
int newlen = this.len + 1;
if (newlen > this.buffer.length) {
expand(newlen);
}
this.buffer[this.len] = (byte)b;
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased if necessary to accommodate all <code>len</code> chars.
* <p>
* The chars are converted to bytes using simple cast.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final char[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int oldlen = this.len;
int newlen = oldlen + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {
this.buffer[i2] = (byte) b[i1];
}
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* char array buffer starting at index <code>off</code>. The capacity
* of the buffer is increased if necessary to accommodate all
* <code>len</code> chars.
* <p>
* The chars are converted to bytes using simple cast.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> if out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final CharArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer(), off, len);
}
/**
* Clears content of the buffer. The underlying byte array is not resized.
*/
public void clear() {
this.len = 0;
}
/**
* Converts the content of this buffer to an array of bytes.
*
* @return byte array
*/
public byte[] toByteArray() {
byte[] b = new byte[this.len];
if (this.len > 0) {
System.arraycopy(this.buffer, 0, b, 0, this.len);
}
return b;
}
/**
* Returns the <code>byte</code> value in this buffer at the specified
* index. The index argument must be greater than or equal to
* <code>0</code>, and less than the length of this buffer.
*
* @param i the index of the desired byte value.
* @return the byte value at the specified index.
* @throws IndexOutOfBoundsException if <code>index</code> is
* negative or greater than or equal to {@link #length()}.
*/
public int byteAt(int i) {
return this.buffer[i];
}
/**
* Returns the current capacity. The capacity is the amount of storage
* available for newly appended bytes, beyond which an allocation
* will occur.
*
* @return the current capacity
*/
public int capacity() {
return this.buffer.length;
}
/**
* Returns the length of the buffer (byte count).
*
* @return the length of the buffer
*/
public int length() {
return this.len;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. If the <code>required</code>
* argument is non-positive, this method takes no action.
*
* @param required the minimum required capacity.
*
* @since 4.1
*/
public void ensureCapacity(int required) {
if (required <= 0) {
return;
}
int available = this.buffer.length - this.len;
if (required > available) {
expand(this.len + required);
}
}
/**
* Returns reference to the underlying byte array.
*
* @return the byte array.
*/
public byte[] buffer() {
return this.buffer;
}
/**
* Sets the length of the buffer. The new length value is expected to be
* less than the current capacity and greater than or equal to
* <code>0</code>.
*
* @param len the new length
* @throws IndexOutOfBoundsException if the
* <code>len</code> argument is greater than the current
* capacity of the buffer or less than <code>0</code>.
*/
public void setLength(int len) {
if (len < 0 || len > this.buffer.length) {
throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);
}
this.len = len;
}
/**
* Returns <code>true</code> if this buffer is empty, that is, its
* {@link #length()} is equal to <code>0</code>.
* @return <code>true</code> if this buffer is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return this.len == 0;
}
/**
* Returns <code>true</code> if this buffer is full, that is, its
* {@link #length()} is equal to its {@link #capacity()}.
* @return <code>true</code> if this buffer is full, <code>false</code>
* otherwise.
*/
public boolean isFull() {
return this.len == this.buffer.length;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified byte, starting the search at the specified
* <code>beginIndex</code> and finishing at <code>endIndex</code>.
* If no such byte occurs in this buffer within the specified bounds,
* <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>beginIndex</code> and
* <code>endIndex</code>. If <code>beginIndex</code> is negative,
* it has the same effect as if it were zero. If <code>endIndex</code> is
* greater than {@link #length()}, it has the same effect as if it were
* {@link #length()}. If the <code>beginIndex</code> is greater than
* the <code>endIndex</code>, <code>-1</code> is returned.
*
* @param b the byte to search for.
* @param beginIndex the index to start the search from.
* @param endIndex the index to finish the search at.
* @return the index of the first occurrence of the byte in the buffer
* within the given bounds, or <code>-1</code> if the byte does
* not occur.
*
* @since 4.1
*/
public int indexOf(byte b, int beginIndex, int endIndex) {
if (beginIndex < 0) {
beginIndex = 0;
}
if (endIndex > this.len) {
endIndex = this.len;
}
if (beginIndex > endIndex) {
return -1;
}
for (int i = beginIndex; i < endIndex; i++) {
if (this.buffer[i] == b) {
return i;
}
}
return -1;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified byte, starting the search at <code>0</code> and finishing
* at {@link #length()}. If no such byte occurs in this buffer within
* those bounds, <code>-1</code> is returned.
*
* @param b the byte to search for.
* @return the index of the first occurrence of the byte in the
* buffer, or <code>-1</code> if the byte does not occur.
*
* @since 4.1
*/
public int indexOf(byte b) {
return indexOf(b, 0, this.len);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import org.apache.ogt.http.HeaderElement;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.NameValuePair;
import org.apache.ogt.http.ParseException;
import org.apache.ogt.http.protocol.HTTP;
/**
* Static helpers for dealing with {@link HttpEntity}s.
*
* @since 4.0
*/
public final class EntityUtils {
private EntityUtils() {
}
/**
* Ensures that the entity content is fully consumed and the content stream, if exists,
* is closed.
*
* @param entity
* @throws IOException if an error occurs reading the input stream
*
* @since 4.1
*/
public static void consume(final HttpEntity entity) throws IOException {
if (entity == null) {
return;
}
if (entity.isStreaming()) {
InputStream instream = entity.getContent();
if (instream != null) {
instream.close();
}
}
}
/**
* Read the contents of an entity and return it as a byte array.
*
* @param entity
* @return byte array containing the entity content. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws IOException if an error occurs reading the input stream
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
*/
public static byte[] toByteArray(final HttpEntity entity) throws IOException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
ByteArrayBuffer buffer = new ByteArrayBuffer(i);
byte[] tmp = new byte[4096];
int l;
while((l = instream.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toByteArray();
} finally {
instream.close();
}
}
/**
* Obtains character set of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*/
public static String getContentCharSet(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String charset = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
NameValuePair param = values[0].getParameterByName("charset");
if (param != null) {
charset = param.getValue();
}
}
}
return charset;
}
/**
* Obtains mime type of the entity, if known.
*
* @param entity must not be null
* @return the character set, or null if not found
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null
*
* @since 4.1
*/
public static String getContentMimeType(final HttpEntity entity) throws ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
String mimeType = null;
if (entity.getContentType() != null) {
HeaderElement values[] = entity.getContentType().getElements();
if (values.length > 0) {
mimeType = values[0].getName();
}
}
return mimeType;
}
/**
* Get the entity content as a String, using the provided default character set
* if none is found in the entity.
* If defaultCharset is null, the default "ISO-8859-1" is used.
*
* @param entity must not be null
* @param defaultCharset character set to be applied if none found in the entity
* @return the entity content as a String. May be null if
* {@link HttpEntity#getContent()} is null.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
*/
public static String toString(
final HttpEntity entity, final String defaultCharset) throws IOException, ParseException {
if (entity == null) {
throw new IllegalArgumentException("HTTP entity may not be null");
}
InputStream instream = entity.getContent();
if (instream == null) {
return null;
}
try {
if (entity.getContentLength() > Integer.MAX_VALUE) {
throw new IllegalArgumentException("HTTP entity too large to be buffered in memory");
}
int i = (int)entity.getContentLength();
if (i < 0) {
i = 4096;
}
String charset = getContentCharSet(entity);
if (charset == null) {
charset = defaultCharset;
}
if (charset == null) {
charset = HTTP.DEFAULT_CONTENT_CHARSET;
}
Reader reader = new InputStreamReader(instream, charset);
CharArrayBuffer buffer = new CharArrayBuffer(i);
char[] tmp = new char[1024];
int l;
while((l = reader.read(tmp)) != -1) {
buffer.append(tmp, 0, l);
}
return buffer.toString();
} finally {
instream.close();
}
}
/**
* Read the contents of an entity and return it as a String.
* The content is converted using the character set from the entity (if any),
* failing that, "ISO-8859-1" is used.
*
* @param entity
* @return String containing the content.
* @throws ParseException if header elements cannot be parsed
* @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE
* @throws IOException if an error occurs reading the input stream
*/
public static String toString(final HttpEntity entity)
throws IOException, ParseException {
return toString(entity, null);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
/**
* A set of utility methods to help produce consistent
* {@link Object#equals equals} and {@link Object#hashCode hashCode} methods.
*
*
* @since 4.0
*/
public final class LangUtils {
public static final int HASH_SEED = 17;
public static final int HASH_OFFSET = 37;
/** Disabled default constructor. */
private LangUtils() {
}
public static int hashCode(final int seed, final int hashcode) {
return seed * HASH_OFFSET + hashcode;
}
public static int hashCode(final int seed, final boolean b) {
return hashCode(seed, b ? 1 : 0);
}
public static int hashCode(final int seed, final Object obj) {
return hashCode(seed, obj != null ? obj.hashCode() : 0);
}
/**
* Check if two objects are equal.
*
* @param obj1 first object to compare, may be {@code null}
* @param obj2 second object to compare, may be {@code null}
* @return {@code true} if the objects are equal or both null
*/
public static boolean equals(final Object obj1, final Object obj2) {
return obj1 == null ? obj2 == null : obj1.equals(obj2);
}
/**
* Check if two object arrays are equal.
* <p>
* <ul>
* <li>If both parameters are null, return {@code true}</li>
* <li>If one parameter is null, return {@code false}</li>
* <li>If the array lengths are different, return {@code false}</li>
* <li>Compare array elements using .equals(); return {@code false} if any comparisons fail.</li>
* <li>Return {@code true}</li>
* </ul>
*
* @param a1 first array to compare, may be {@code null}
* @param a2 second array to compare, may be {@code null}
* @return {@code true} if the arrays are equal or both null
*/
public static boolean equals(final Object[] a1, final Object[] a2) {
if (a1 == null) {
if (a2 == null) {
return true;
} else {
return false;
}
} else {
if (a2 != null && a1.length == a2.length) {
for (int i = 0; i < a1.length; i++) {
if (!equals(a1[i], a2[i])) {
return false;
}
}
return true;
} else {
return false;
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.Serializable;
import org.apache.ogt.http.protocol.HTTP;
/**
* A resizable char array.
*
* @since 4.0
*/
public final class CharArrayBuffer implements Serializable {
private static final long serialVersionUID = -6208952725094867135L;
private char[] buffer;
private int len;
/**
* Creates an instance of {@link CharArrayBuffer} with the given initial
* capacity.
*
* @param capacity the capacity
*/
public CharArrayBuffer(int capacity) {
super();
if (capacity < 0) {
throw new IllegalArgumentException("Buffer capacity may not be negative");
}
this.buffer = new char[capacity];
}
private void expand(int newlen) {
char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)];
System.arraycopy(this.buffer, 0, newbuffer, 0, this.len);
this.buffer = newbuffer;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> chars.
*
* @param b the chars to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final char[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int newlen = this.len + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
System.arraycopy(b, off, this.buffer, this.len, len);
this.len = newlen;
}
/**
* Appends chars of the given string to this buffer. The capacity of the
* buffer is increased, if necessary, to accommodate all chars.
*
* @param str the string.
*/
public void append(String str) {
if (str == null) {
str = "null";
}
int strlen = str.length();
int newlen = this.len + strlen;
if (newlen > this.buffer.length) {
expand(newlen);
}
str.getChars(0, strlen, this.buffer, this.len);
this.len = newlen;
}
/**
* Appends <code>len</code> chars to this buffer from the given source
* buffer starting at index <code>off</code>. The capacity of the
* destination buffer is increased, if necessary, to accommodate all
* <code>len</code> chars.
*
* @param b the source buffer to be appended.
* @param off the index of the first char to append.
* @param len the number of chars to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final CharArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer, off, len);
}
/**
* Appends all chars to this buffer from the given source buffer starting
* at index <code>0</code>. The capacity of the destination buffer is
* increased, if necessary, to accommodate all {@link #length()} chars.
*
* @param b the source buffer to be appended.
*/
public void append(final CharArrayBuffer b) {
if (b == null) {
return;
}
append(b.buffer,0, b.len);
}
/**
* Appends <code>ch</code> char to this buffer. The capacity of the buffer
* is increased, if necessary, to accommodate the additional char.
*
* @param ch the char to be appended.
*/
public void append(char ch) {
int newlen = this.len + 1;
if (newlen > this.buffer.length) {
expand(newlen);
}
this.buffer[this.len] = ch;
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final byte[] b, int off, int len) {
if (b == null) {
return;
}
if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) < 0) || ((off + len) > b.length)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (len == 0) {
return;
}
int oldlen = this.len;
int newlen = oldlen + len;
if (newlen > this.buffer.length) {
expand(newlen);
}
for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) {
this.buffer[i2] = (char) (b[i1] & 0xff);
}
this.len = newlen;
}
/**
* Appends <code>len</code> bytes to this buffer from the given source
* array starting at index <code>off</code>. The capacity of the buffer
* is increased, if necessary, to accommodate all <code>len</code> bytes.
* <p>
* The bytes are converted to chars using simple cast.
*
* @param b the bytes to be appended.
* @param off the index of the first byte to append.
* @param len the number of bytes to append.
* @throws IndexOutOfBoundsException if <code>off</code> is out of
* range, <code>len</code> is negative, or
* <code>off</code> + <code>len</code> is out of range.
*/
public void append(final ByteArrayBuffer b, int off, int len) {
if (b == null) {
return;
}
append(b.buffer(), off, len);
}
/**
* Appends chars of the textual representation of the given object to this
* buffer. The capacity of the buffer is increased, if necessary, to
* accommodate all chars.
*
* @param obj the object.
*/
public void append(final Object obj) {
append(String.valueOf(obj));
}
/**
* Clears content of the buffer. The underlying char array is not resized.
*/
public void clear() {
this.len = 0;
}
/**
* Converts the content of this buffer to an array of chars.
*
* @return char array
*/
public char[] toCharArray() {
char[] b = new char[this.len];
if (this.len > 0) {
System.arraycopy(this.buffer, 0, b, 0, this.len);
}
return b;
}
/**
* Returns the <code>char</code> value in this buffer at the specified
* index. The index argument must be greater than or equal to
* <code>0</code>, and less than the length of this buffer.
*
* @param i the index of the desired char value.
* @return the char value at the specified index.
* @throws IndexOutOfBoundsException if <code>index</code> is
* negative or greater than or equal to {@link #length()}.
*/
public char charAt(int i) {
return this.buffer[i];
}
/**
* Returns reference to the underlying char array.
*
* @return the char array.
*/
public char[] buffer() {
return this.buffer;
}
/**
* Returns the current capacity. The capacity is the amount of storage
* available for newly appended chars, beyond which an allocation will
* occur.
*
* @return the current capacity
*/
public int capacity() {
return this.buffer.length;
}
/**
* Returns the length of the buffer (char count).
*
* @return the length of the buffer
*/
public int length() {
return this.len;
}
/**
* Ensures that the capacity is at least equal to the specified minimum.
* If the current capacity is less than the argument, then a new internal
* array is allocated with greater capacity. If the <code>required</code>
* argument is non-positive, this method takes no action.
*
* @param required the minimum required capacity.
*/
public void ensureCapacity(int required) {
if (required <= 0) {
return;
}
int available = this.buffer.length - this.len;
if (required > available) {
expand(this.len + required);
}
}
/**
* Sets the length of the buffer. The new length value is expected to be
* less than the current capacity and greater than or equal to
* <code>0</code>.
*
* @param len the new length
* @throws IndexOutOfBoundsException if the
* <code>len</code> argument is greater than the current
* capacity of the buffer or less than <code>0</code>.
*/
public void setLength(int len) {
if (len < 0 || len > this.buffer.length) {
throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length);
}
this.len = len;
}
/**
* Returns <code>true</code> if this buffer is empty, that is, its
* {@link #length()} is equal to <code>0</code>.
* @return <code>true</code> if this buffer is empty, <code>false</code>
* otherwise.
*/
public boolean isEmpty() {
return this.len == 0;
}
/**
* Returns <code>true</code> if this buffer is full, that is, its
* {@link #length()} is equal to its {@link #capacity()}.
* @return <code>true</code> if this buffer is full, <code>false</code>
* otherwise.
*/
public boolean isFull() {
return this.len == this.buffer.length;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at the specified
* <code>beginIndex</code> and finishing at <code>endIndex</code>.
* If no such character occurs in this buffer within the specified bounds,
* <code>-1</code> is returned.
* <p>
* There is no restriction on the value of <code>beginIndex</code> and
* <code>endIndex</code>. If <code>beginIndex</code> is negative,
* it has the same effect as if it were zero. If <code>endIndex</code> is
* greater than {@link #length()}, it has the same effect as if it were
* {@link #length()}. If the <code>beginIndex</code> is greater than
* the <code>endIndex</code>, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @param beginIndex the index to start the search from.
* @param endIndex the index to finish the search at.
* @return the index of the first occurrence of the character in the buffer
* within the given bounds, or <code>-1</code> if the character does
* not occur.
*/
public int indexOf(int ch, int beginIndex, int endIndex) {
if (beginIndex < 0) {
beginIndex = 0;
}
if (endIndex > this.len) {
endIndex = this.len;
}
if (beginIndex > endIndex) {
return -1;
}
for (int i = beginIndex; i < endIndex; i++) {
if (this.buffer[i] == ch) {
return i;
}
}
return -1;
}
/**
* Returns the index within this buffer of the first occurrence of the
* specified character, starting the search at <code>0</code> and finishing
* at {@link #length()}. If no such character occurs in this buffer within
* those bounds, <code>-1</code> is returned.
*
* @param ch the char to search for.
* @return the index of the first occurrence of the character in the
* buffer, or <code>-1</code> if the character does not occur.
*/
public int indexOf(int ch) {
return indexOf(ch, 0, this.len);
}
/**
* Returns a substring of this buffer. The substring begins at the specified
* <code>beginIndex</code> and extends to the character at index
* <code>endIndex - 1</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception StringIndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substring(int beginIndex, int endIndex) {
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
/**
* Returns a substring of this buffer with leading and trailing whitespace
* omitted. The substring begins with the first non-whitespace character
* from <code>beginIndex</code> and extends to the last
* non-whitespace character with the index lesser than
* <code>endIndex</code>.
*
* @param beginIndex the beginning index, inclusive.
* @param endIndex the ending index, exclusive.
* @return the specified substring.
* @exception IndexOutOfBoundsException if the
* <code>beginIndex</code> is negative, or
* <code>endIndex</code> is larger than the length of this
* buffer, or <code>beginIndex</code> is larger than
* <code>endIndex</code>.
*/
public String substringTrimmed(int beginIndex, int endIndex) {
if (beginIndex < 0) {
throw new IndexOutOfBoundsException("Negative beginIndex: "+beginIndex);
}
if (endIndex > this.len) {
throw new IndexOutOfBoundsException("endIndex: "+endIndex+" > length: "+this.len);
}
if (beginIndex > endIndex) {
throw new IndexOutOfBoundsException("beginIndex: "+beginIndex+" > endIndex: "+endIndex);
}
while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) {
beginIndex++;
}
while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) {
endIndex--;
}
return new String(this.buffer, beginIndex, endIndex - beginIndex);
}
public String toString() {
return new String(this.buffer, 0, this.len);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.protocol.HTTP;
/**
* The home for utility methods that handle various encoding tasks.
*
*
* @since 4.0
*/
public final class EncodingUtils {
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(
final byte[] data,
int offset,
int length,
String charset
) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
if (charset == null || charset.length() == 0) {
throw new IllegalArgumentException("charset may not be null or empty");
}
try {
return new String(data, offset, length, charset);
} catch (UnsupportedEncodingException e) {
return new String(data, offset, length);
}
}
/**
* Converts the byte array of HTTP content characters to a string. If
* the specified charset is not supported, default system encoding
* is used.
*
* @param data the byte array to be encoded
* @param charset the desired character encoding
* @return The result of the conversion.
*/
public static String getString(final byte[] data, final String charset) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
return getString(data, 0, data.length, charset);
}
/**
* Converts the specified string to a byte array. If the charset is not supported the
* default system charset is used.
*
* @param data the string to be encoded
* @param charset the desired character encoding
* @return The resulting byte array.
*/
public static byte[] getBytes(final String data, final String charset) {
if (data == null) {
throw new IllegalArgumentException("data may not be null");
}
if (charset == null || charset.length() == 0) {
throw new IllegalArgumentException("charset may not be null or empty");
}
try {
return data.getBytes(charset);
} catch (UnsupportedEncodingException e) {
return data.getBytes();
}
}
/**
* Converts the specified string to byte array of ASCII characters.
*
* @param data the string to be encoded
* @return The string as a byte array.
*/
public static byte[] getAsciiBytes(final String data) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
try {
return data.getBytes(HTTP.US_ASCII);
} catch (UnsupportedEncodingException e) {
throw new Error("HttpClient requires ASCII support");
}
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @param offset the index of the first byte to encode
* @param length the number of bytes to encode
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data, int offset, int length) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
try {
return new String(data, offset, length, HTTP.US_ASCII);
} catch (UnsupportedEncodingException e) {
throw new Error("HttpClient requires ASCII support");
}
}
/**
* Converts the byte array of ASCII characters to a string. This method is
* to be used when decoding content of HTTP elements (such as response
* headers)
*
* @param data the byte array to be encoded
* @return The string representation of the byte array
*/
public static String getAsciiString(final byte[] data) {
if (data == null) {
throw new IllegalArgumentException("Parameter may not be null");
}
return getAsciiString(data, 0, data.length);
}
/**
* This class should not be instantiated.
*/
private EncodingUtils() {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.io.IOException;
import java.io.InputStream;
import java.util.Map;
import java.util.Properties;
import java.util.ArrayList;
/**
* Provides access to version information for HTTP components.
* Static methods are used to extract version information from property
* files that are automatically packaged with HTTP component release JARs.
* <br/>
* All available version information is provided in strings, where
* the string format is informal and subject to change without notice.
* Version information is provided for debugging output and interpretation
* by humans, not for automated processing in applications.
*
* @since 4.0
*/
public class VersionInfo {
/** A string constant for unavailable information. */
public final static String UNAVAILABLE = "UNAVAILABLE";
/** The filename of the version information files. */
public final static String VERSION_PROPERTY_FILE = "version.properties";
// the property names
public final static String PROPERTY_MODULE = "info.module";
public final static String PROPERTY_RELEASE = "info.release";
public final static String PROPERTY_TIMESTAMP = "info.timestamp";
/** The package that contains the version information. */
private final String infoPackage;
/** The module from the version info. */
private final String infoModule;
/** The release from the version info. */
private final String infoRelease;
/** The timestamp from the version info. */
private final String infoTimestamp;
/** The classloader from which the version info was obtained. */
private final String infoClassloader;
/**
* Instantiates version information.
*
* @param pckg the package
* @param module the module, or <code>null</code>
* @param release the release, or <code>null</code>
* @param time the build time, or <code>null</code>
* @param clsldr the class loader, or <code>null</code>
*/
protected VersionInfo(String pckg, String module,
String release, String time, String clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
infoPackage = pckg;
infoModule = (module != null) ? module : UNAVAILABLE;
infoRelease = (release != null) ? release : UNAVAILABLE;
infoTimestamp = (time != null) ? time : UNAVAILABLE;
infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE;
}
/**
* Obtains the package name.
* The package name identifies the module or informal unit.
*
* @return the package name, never <code>null</code>
*/
public final String getPackage() {
return infoPackage;
}
/**
* Obtains the name of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the module name, never <code>null</code>
*/
public final String getModule() {
return infoModule;
}
/**
* Obtains the release of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the release version, never <code>null</code>
*/
public final String getRelease() {
return infoRelease;
}
/**
* Obtains the timestamp of the versioned module or informal unit.
* This data is read from the version information for the package.
*
* @return the timestamp, never <code>null</code>
*/
public final String getTimestamp() {
return infoTimestamp;
}
/**
* Obtains the classloader used to read the version information.
* This is just the <code>toString</code> output of the classloader,
* since the version information should not keep a reference to
* the classloader itself. That could prevent garbage collection.
*
* @return the classloader description, never <code>null</code>
*/
public final String getClassloader() {
return infoClassloader;
}
/**
* Provides the version information in human-readable format.
*
* @return a string holding this version information
*/
public String toString() {
StringBuffer sb = new StringBuffer
(20 + infoPackage.length() + infoModule.length() +
infoRelease.length() + infoTimestamp.length() +
infoClassloader.length());
sb.append("VersionInfo(")
.append(infoPackage).append(':').append(infoModule);
// If version info is missing, a single "UNAVAILABLE" for the module
// is sufficient. Everything else just clutters the output.
if (!UNAVAILABLE.equals(infoRelease))
sb.append(':').append(infoRelease);
if (!UNAVAILABLE.equals(infoTimestamp))
sb.append(':').append(infoTimestamp);
sb.append(')');
if (!UNAVAILABLE.equals(infoClassloader))
sb.append('@').append(infoClassloader);
return sb.toString();
}
/**
* Loads version information for a list of packages.
*
* @param pckgs the packages for which to load version info
* @param clsldr the classloader to load from, or
* <code>null</code> for the thread context classloader
*
* @return the version information for all packages found,
* never <code>null</code>
*/
public final static VersionInfo[] loadVersionInfo(String[] pckgs,
ClassLoader clsldr) {
if (pckgs == null) {
throw new IllegalArgumentException
("Package identifier list must not be null.");
}
ArrayList vil = new ArrayList(pckgs.length);
for (int i=0; i<pckgs.length; i++) {
VersionInfo vi = loadVersionInfo(pckgs[i], clsldr);
if (vi != null)
vil.add(vi);
}
return (VersionInfo[]) vil.toArray(new VersionInfo[vil.size()]);
}
/**
* Loads version information for a package.
*
* @param pckg the package for which to load version information,
* for example "org.apache.ogt.http".
* The package name should NOT end with a dot.
* @param clsldr the classloader to load from, or
* <code>null</code> for the thread context classloader
*
* @return the version information for the argument package, or
* <code>null</code> if not available
*/
public final static VersionInfo loadVersionInfo(final String pckg,
ClassLoader clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
if (clsldr == null)
clsldr = Thread.currentThread().getContextClassLoader();
Properties vip = null; // version info properties, if available
try {
// org.apache.ogt.http becomes
// org/apache/http/version.properties
InputStream is = clsldr.getResourceAsStream
(pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE);
if (is != null) {
try {
Properties props = new Properties();
props.load(is);
vip = props;
} finally {
is.close();
}
}
} catch (IOException ex) {
// shamelessly munch this exception
}
VersionInfo result = null;
if (vip != null)
result = fromMap(pckg, vip, clsldr);
return result;
}
/**
* Instantiates version information from properties.
*
* @param pckg the package for the version information
* @param info the map from string keys to string values,
* for example {@link java.util.Properties}
* @param clsldr the classloader, or <code>null</code>
*
* @return the version information
*/
protected final static VersionInfo fromMap(String pckg, Map info,
ClassLoader clsldr) {
if (pckg == null) {
throw new IllegalArgumentException
("Package identifier must not be null.");
}
String module = null;
String release = null;
String timestamp = null;
if (info != null) {
module = (String) info.get(PROPERTY_MODULE);
if ((module != null) && (module.length() < 1))
module = null;
release = (String) info.get(PROPERTY_RELEASE);
if ((release != null) && ((release.length() < 1) ||
(release.equals("${pom.version}"))))
release = null;
timestamp = (String) info.get(PROPERTY_TIMESTAMP);
if ((timestamp != null) &&
((timestamp.length() < 1) ||
(timestamp.equals("${mvn.timestamp}")))
)
timestamp = null;
} // if info
String clsldrstr = null;
if (clsldr != null)
clsldrstr = clsldr.toString();
return new VersionInfo(pckg, module, release, timestamp, clsldrstr);
}
} // class VersionInfo
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.util;
import java.lang.reflect.Method;
/**
* The home for utility methods that handle various exception-related tasks.
*
*
* @since 4.0
*/
public final class ExceptionUtils {
/** A reference to Throwable's initCause method, or null if it's not there in this JVM */
static private final Method INIT_CAUSE_METHOD = getInitCauseMethod();
/**
* Returns a <code>Method<code> allowing access to
* {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable},
* or <code>null</code> if the method
* does not exist.
*
* @return A <code>Method<code> for <code>Throwable.initCause</code>, or
* <code>null</code> if unavailable.
*/
static private Method getInitCauseMethod() {
try {
Class[] paramsClasses = new Class[] { Throwable.class };
return Throwable.class.getMethod("initCause", paramsClasses);
} catch (NoSuchMethodException e) {
return null;
}
}
/**
* If we're running on JDK 1.4 or later, initialize the cause for the given throwable.
*
* @param throwable The throwable.
* @param cause The cause of the throwable.
*/
public static void initCause(Throwable throwable, Throwable cause) {
if (INIT_CAUSE_METHOD != null) {
try {
INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause });
} catch (Exception e) {
// Well, with no logging, the only option is to munch the exception
}
}
}
private ExceptionUtils() {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* The point of access to the statistics of an {@link HttpConnection}.
*
* @since 4.0
*/
public interface HttpConnectionMetrics {
/**
* Returns the number of requests transferred over the connection,
* 0 if not available.
*/
long getRequestCount();
/**
* Returns the number of responses transferred over the connection,
* 0 if not available.
*/
long getResponseCount();
/**
* Returns the number of bytes transferred over the connection,
* 0 if not available.
*/
long getSentBytesCount();
/**
* Returns the number of bytes transferred over the connection,
* 0 if not available.
*/
long getReceivedBytesCount();
/**
* Return the value for the specified metric.
*
*@param metricName the name of the metric to query.
*
*@return the object representing the metric requested,
* <code>null</code> if the metric cannot not found.
*/
Object getMetric(String metricName);
/**
* Resets the counts
*
*/
void reset();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import org.apache.ogt.http.protocol.HttpContext;
/**
* A factory for {@link HttpResponse HttpResponse} objects.
*
* @since 4.0
*/
public interface HttpResponseFactory {
/**
* Creates a new response from status line elements.
*
* @param ver the protocol version
* @param status the status code
* @param context the context from which to determine the locale
* for looking up a reason phrase to the status code, or
* <code>null</code> to use the default locale
*
* @return the new response with an initialized status line
*/
HttpResponse newHttpResponse(ProtocolVersion ver, int status,
HttpContext context);
/**
* Creates a new response from a status line.
*
* @param statusline the status line
* @param context the context from which to determine the locale
* for looking up a reason phrase if the status code
* is updated, or
* <code>null</code> to use the default locale
*
* @return the new response with the argument status line
*/
HttpResponse newHttpResponse(StatusLine statusline,
HttpContext context);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Session output buffer for blocking connections. This interface is similar to
* OutputStream class, but it also provides methods for writing lines of text.
* <p>
* Implementing classes are also expected to manage intermediate data buffering
* for optimal output performance.
*
* @since 4.0
*/
public interface SessionOutputBuffer {
/**
* Writes <code>len</code> bytes from the specified byte array
* starting at offset <code>off</code> to this session buffer.
* <p>
* If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown.
*
* @param b the data.
* @param off the start offset in the data.
* @param len the number of bytes to write.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b, int off, int len) throws IOException;
/**
* Writes <code>b.length</code> bytes from the specified byte array
* to this session buffer.
*
* @param b the data.
* @exception IOException if an I/O error occurs.
*/
void write(byte[] b) throws IOException;
/**
* Writes the specified byte to this session buffer.
*
* @param b the <code>byte</code>.
* @exception IOException if an I/O error occurs.
*/
void write(int b) throws IOException;
/**
* Writes characters from the specified string followed by a line delimiter
* to this session buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param s the line.
* @exception IOException if an I/O error occurs.
*/
void writeLine(String s) throws IOException;
/**
* Writes characters from the specified char array followed by a line
* delimiter to this session buffer.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param buffer the buffer containing chars of the line.
* @exception IOException if an I/O error occurs.
*/
void writeLine(CharArrayBuffer buffer) throws IOException;
/**
* Flushes this session buffer and forces any buffered output bytes
* to be written out. The general contract of <code>flush</code> is
* that calling it is an indication that, if any bytes previously
* written have been buffered by the implementation of the output
* stream, such bytes should immediately be written to their
* intended destination.
*
* @exception IOException if an I/O error occurs.
*/
void flush() throws IOException;
/**
* Returns {@link HttpTransportMetrics} for this session buffer.
*
* @return transport metrics.
*/
HttpTransportMetrics getMetrics();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
/**
* Abstract message parser intended to build HTTP messages from an arbitrary
* data source.
*
* @since 4.0
*/
public interface HttpMessageParser {
/**
* Generates an instance of {@link HttpMessage} from the underlying data
* source.
*
* @return HTTP message
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
HttpMessage parse()
throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* EOF sensor.
*
* @since 4.0
*/
public interface EofSensor {
boolean isEof();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpMessage;
/**
* Abstract message writer intended to serialize HTTP messages to an arbitrary
* data sink.
*
* @since 4.0
*/
public interface HttpMessageWriter {
/**
* Serializes an instance of {@link HttpMessage} to the underlying data
* sink.
*
* @param message
* @throws IOException in case of an I/O error
* @throws HttpException in case of HTTP protocol violation
*/
void write(HttpMessage message)
throws IOException, HttpException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* The point of access to the statistics of {@link SessionInputBuffer} or
* {@link SessionOutputBuffer}.
*
* @since 4.0
*/
public interface HttpTransportMetrics {
/**
* Returns the number of bytes transferred.
*/
long getBytesTransferred();
/**
* Resets the counts
*/
void reset();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
import java.io.IOException;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Session input buffer for blocking connections. This interface is similar to
* InputStream class, but it also provides methods for reading lines of text.
* <p>
* Implementing classes are also expected to manage intermediate data buffering
* for optimal input performance.
*
* @since 4.0
*/
public interface SessionInputBuffer {
/**
* Reads up to <code>len</code> bytes of data from the session buffer into
* an array of bytes. An attempt is made to read as many as
* <code>len</code> bytes, but a smaller number may be read, possibly
* zero. The number of bytes actually read is returned as an integer.
*
* <p> This method blocks until input data is available, end of file is
* detected, or an exception is thrown.
*
* <p> If <code>off</code> is negative, or <code>len</code> is negative, or
* <code>off+len</code> is greater than the length of the array
* <code>b</code>, then an <code>IndexOutOfBoundsException</code> is
* thrown.
*
* @param b the buffer into which the data is read.
* @param off the start offset in array <code>b</code>
* at which the data is written.
* @param len the maximum number of bytes to read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> if there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b, int off, int len) throws IOException;
/**
* Reads some number of bytes from the session buffer and stores them into
* the buffer array <code>b</code>. The number of bytes actually read is
* returned as an integer. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
*
* @param b the buffer into which the data is read.
* @return the total number of bytes read into the buffer, or
* <code>-1</code> is there is no more data because the end of
* the stream has been reached.
* @exception IOException if an I/O error occurs.
*/
int read(byte[] b) throws IOException;
/**
* Reads the next byte of data from this session buffer. The value byte is
* returned as an <code>int</code> in the range <code>0</code> to
* <code>255</code>. If no byte is available because the end of the stream
* has been reached, the value <code>-1</code> is returned. This method
* blocks until input data is available, the end of the stream is detected,
* or an exception is thrown.
*
* @return the next byte of data, or <code>-1</code> if the end of the
* stream is reached.
* @exception IOException if an I/O error occurs.
*/
int read() throws IOException;
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer into the given line buffer. The number of chars actually
* read is returned as an integer. The line delimiter itself is discarded.
* If no char is available because the end of the stream has been reached,
* the value <code>-1</code> is returned. This method blocks until input
* data is available, end of file is detected, or an exception is thrown.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @param buffer the line buffer.
* @return one line of characters
* @exception IOException if an I/O error occurs.
*/
int readLine(CharArrayBuffer buffer) throws IOException;
/**
* Reads a complete line of characters up to a line delimiter from this
* session buffer. The line delimiter itself is discarded. If no char is
* available because the end of the stream has been reached,
* <code>null</code> is returned. This method blocks until input data is
* available, end of file is detected, or an exception is thrown.
* <p>
* The choice of a char encoding and line delimiter sequence is up to the
* specific implementations of this interface.
*
* @return HTTP line as a string
* @exception IOException if an I/O error occurs.
*/
String readLine() throws IOException;
/** Blocks until some data becomes available in the session buffer or the
* given timeout period in milliseconds elapses. If the timeout value is
* <code>0</code> this method blocks indefinitely.
*
* @param timeout in milliseconds.
* @return <code>true</code> if some data is available in the session
* buffer or <code>false</code> otherwise.
* @exception IOException if an I/O error occurs.
*/
boolean isDataAvailable(int timeout) throws IOException;
/**
* Returns {@link HttpTransportMetrics} for this session buffer.
*
* @return transport metrics.
*/
HttpTransportMetrics getMetrics();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.io;
/**
* Basic buffer properties.
*
* @since 4.1
*/
public interface BufferInfo {
/**
* Return length data stored in the buffer
*
* @return data length
*/
int length();
/**
* Returns total capacity of the buffer
*
* @return total capacity
*/
int capacity();
/**
* Returns available space in the buffer.
*
* @return available space.
*/
int available();
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.IOException;
import org.apache.ogt.http.protocol.HttpContext;
/**
* HTTP protocol interceptor is a routine that implements a specific aspect of
* the HTTP protocol. Usually protocol interceptors are expected to act upon
* one specific header or a group of related headers of the incoming message
* or populate the outgoing message with one specific header or a group of
* related headers.
* <p>
* Protocol Interceptors can also manipulate content entities enclosed with messages.
* Usually this is accomplished by using the 'Decorator' pattern where a wrapper
* entity class is used to decorate the original entity.
* <p>
* Protocol interceptors must be implemented as thread-safe. Similarly to
* servlets, protocol interceptors should not use instance variables unless
* access to those variables is synchronized.
*
* @since 4.0
*/
public interface HttpRequestInterceptor {
/**
* Processes a request.
* On the client side, this step is performed before the request is
* sent to the server. On the server side, this step is performed
* on incoming messages before the message body is evaluated.
*
* @param request the request to preprocess
* @param context the context for the request
*
* @throws HttpException in case of an HTTP protocol violation
* @throws IOException in case of an I/O error
*/
void process(HttpRequest request, HttpContext context)
throws HttpException, IOException;
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
import java.io.Serializable;
import org.apache.ogt.http.util.CharArrayBuffer;
/**
* Represents a protocol version. The "major.minor" numbering
* scheme is used to indicate versions of the protocol.
* <p>
* This class defines a protocol version as a combination of
* protocol name, major version number, and minor version number.
* Note that {@link #equals} and {@link #hashCode} are defined as
* final here, they cannot be overridden in derived classes.
* </p>
*
* @since 4.0
*/
public class ProtocolVersion implements Serializable, Cloneable {
private static final long serialVersionUID = 8950662842175091068L;
/** Name of the protocol. */
protected final String protocol;
/** Major version number of the protocol */
protected final int major;
/** Minor version number of the protocol */
protected final int minor;
/**
* Create a protocol version designator.
*
* @param protocol the name of the protocol, for example "HTTP"
* @param major the major version number of the protocol
* @param minor the minor version number of the protocol
*/
public ProtocolVersion(String protocol, int major, int minor) {
if (protocol == null) {
throw new IllegalArgumentException
("Protocol name must not be null.");
}
if (major < 0) {
throw new IllegalArgumentException
("Protocol major version number must not be negative.");
}
if (minor < 0) {
throw new IllegalArgumentException
("Protocol minor version number may not be negative");
}
this.protocol = protocol;
this.major = major;
this.minor = minor;
}
/**
* Returns the name of the protocol.
*
* @return the protocol name
*/
public final String getProtocol() {
return protocol;
}
/**
* Returns the major version number of the protocol.
*
* @return the major version number.
*/
public final int getMajor() {
return major;
}
/**
* Returns the minor version number of the HTTP protocol.
*
* @return the minor version number.
*/
public final int getMinor() {
return minor;
}
/**
* Obtains a specific version of this protocol.
* This can be used by derived classes to instantiate themselves instead
* of the base class, and to define constants for commonly used versions.
* <br/>
* The default implementation in this class returns <code>this</code>
* if the version matches, and creates a new {@link ProtocolVersion}
* otherwise.
*
* @param major the major version
* @param minor the minor version
*
* @return a protocol version with the same protocol name
* and the argument version
*/
public ProtocolVersion forVersion(int major, int minor) {
if ((major == this.major) && (minor == this.minor)) {
return this;
}
// argument checking is done in the constructor
return new ProtocolVersion(this.protocol, major, minor);
}
/**
* Obtains a hash code consistent with {@link #equals}.
*
* @return the hashcode of this protocol version
*/
public final int hashCode() {
return this.protocol.hashCode() ^ (this.major * 100000) ^ this.minor;
}
/**
* Checks equality of this protocol version with an object.
* The object is equal if it is a protocl version with the same
* protocol name, major version number, and minor version number.
* The specific class of the object is <i>not</i> relevant,
* instances of derived classes with identical attributes are
* equal to instances of the base class and vice versa.
*
* @param obj the object to compare with
*
* @return <code>true</code> if the argument is the same protocol version,
* <code>false</code> otherwise
*/
public final boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (!(obj instanceof ProtocolVersion)) {
return false;
}
ProtocolVersion that = (ProtocolVersion) obj;
return ((this.protocol.equals(that.protocol)) &&
(this.major == that.major) &&
(this.minor == that.minor));
}
/**
* Checks whether this protocol can be compared to another one.
* Only protocol versions with the same protocol name can be
* {@link #compareToVersion compared}.
*
* @param that the protocol version to consider
*
* @return <code>true</code> if {@link #compareToVersion compareToVersion}
* can be called with the argument, <code>false</code> otherwise
*/
public boolean isComparable(ProtocolVersion that) {
return (that != null) && this.protocol.equals(that.protocol);
}
/**
* Compares this protocol version with another one.
* Only protocol versions with the same protocol name can be compared.
* This method does <i>not</i> define a total ordering, as it would be
* required for {@link java.lang.Comparable}.
*
* @param that the protocl version to compare with
*
* @return a negative integer, zero, or a positive integer
* as this version is less than, equal to, or greater than
* the argument version.
*
* @throws IllegalArgumentException
* if the argument has a different protocol name than this object,
* or if the argument is <code>null</code>
*/
public int compareToVersion(ProtocolVersion that) {
if (that == null) {
throw new IllegalArgumentException
("Protocol version must not be null.");
}
if (!this.protocol.equals(that.protocol)) {
throw new IllegalArgumentException
("Versions for different protocols cannot be compared. " +
this + " " + that);
}
int delta = getMajor() - that.getMajor();
if (delta == 0) {
delta = getMinor() - that.getMinor();
}
return delta;
}
/**
* Tests if this protocol version is greater or equal to the given one.
*
* @param version the version against which to check this version
*
* @return <code>true</code> if this protocol version is
* {@link #isComparable comparable} to the argument
* and {@link #compareToVersion compares} as greater or equal,
* <code>false</code> otherwise
*/
public final boolean greaterEquals(ProtocolVersion version) {
return isComparable(version) && (compareToVersion(version) >= 0);
}
/**
* Tests if this protocol version is less or equal to the given one.
*
* @param version the version against which to check this version
*
* @return <code>true</code> if this protocol version is
* {@link #isComparable comparable} to the argument
* and {@link #compareToVersion compares} as less or equal,
* <code>false</code> otherwise
*/
public final boolean lessEquals(ProtocolVersion version) {
return isComparable(version) && (compareToVersion(version) <= 0);
}
/**
* Converts this protocol version to a string.
*
* @return a protocol version string, like "HTTP/1.1"
*/
public String toString() {
CharArrayBuffer buffer = new CharArrayBuffer(16);
buffer.append(this.protocol);
buffer.append('/');
buffer.append(Integer.toString(this.major));
buffer.append('.');
buffer.append(Integer.toString(this.minor));
return buffer.toString();
}
public Object clone() throws CloneNotSupportedException {
return super.clone();
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http;
/**
* One element of an HTTP {@link Header header} value consisting of
* a name / value pair and a number of optional name / value parameters.
* <p>
* Some HTTP headers (such as the set-cookie header) have values that
* can be decomposed into multiple elements. Such headers must be in the
* following form:
* </p>
* <pre>
* header = [ element ] *( "," [ element ] )
* element = name [ "=" [ value ] ] *( ";" [ param ] )
* param = name [ "=" [ value ] ]
*
* name = token
* value = ( token | quoted-string )
*
* token = 1*<any char except "=", ",", ";", <"> and
* white space>
* quoted-string = <"> *( text | quoted-char ) <">
* text = any char except <">
* quoted-char = "\" char
* </pre>
* <p>
* Any amount of white space is allowed between any part of the
* header, element or param and is ignored. A missing value in any
* element or param will be stored as the empty {@link String};
* if the "=" is also missing <var>null</var> will be stored instead.
*
* @since 4.0
*/
public interface HeaderElement {
/**
* Returns header element name.
*
* @return header element name
*/
String getName();
/**
* Returns header element value.
*
* @return header element value
*/
String getValue();
/**
* Returns an array of name / value pairs.
*
* @return array of name / value pairs
*/
NameValuePair[] getParameters();
/**
* Returns the first parameter with the given name.
*
* @param name parameter name
*
* @return name / value pair
*/
NameValuePair getParameterByName(String name);
/**
* Returns the total count of parameters.
*
* @return parameter count
*/
int getParameterCount();
/**
* Returns parameter with the given index.
*
* @param index
* @return name / value pair
*/
NameValuePair getParameter(int index);
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.File;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URLDecoder;
import java.util.Locale;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpEntityEnclosingRequest;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.HttpStatus;
import org.apache.ogt.http.MethodNotSupportedException;
import org.apache.ogt.http.entity.ContentProducer;
import org.apache.ogt.http.entity.EntityTemplate;
import org.apache.ogt.http.entity.FileEntity;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
import org.apache.ogt.http.util.EntityUtils;
/**
* Basic, yet fully functional and spec compliant, HTTP/1.1 file server.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP file server.
*
*
*/
public class ElementalHttpServer {
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specify document root directory");
System.exit(1);
}
Thread t = new RequestListenerThread(8080, args[0]);
t.setDaemon(false);
t.start();
}
static class HttpFileHandler implements HttpRequestHandler {
private final String docRoot;
public HttpFileHandler(final String docRoot) {
super();
this.docRoot = docRoot;
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
String method = request.getRequestLine().getMethod().toUpperCase(Locale.ENGLISH);
if (!method.equals("GET") && !method.equals("HEAD") && !method.equals("POST")) {
throw new MethodNotSupportedException(method + " method not supported");
}
String target = request.getRequestLine().getUri();
if (request instanceof HttpEntityEnclosingRequest) {
HttpEntity entity = ((HttpEntityEnclosingRequest) request).getEntity();
byte[] entityContent = EntityUtils.toByteArray(entity);
System.out.println("Incoming entity content (bytes): " + entityContent.length);
}
final File file = new File(this.docRoot, URLDecoder.decode(target));
if (!file.exists()) {
response.setStatusCode(HttpStatus.SC_NOT_FOUND);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("File ");
writer.write(file.getPath());
writer.write(" not found");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("File " + file.getPath() + " not found");
} else if (!file.canRead() || file.isDirectory()) {
response.setStatusCode(HttpStatus.SC_FORBIDDEN);
EntityTemplate body = new EntityTemplate(new ContentProducer() {
public void writeTo(final OutputStream outstream) throws IOException {
OutputStreamWriter writer = new OutputStreamWriter(outstream, "UTF-8");
writer.write("<html><body><h1>");
writer.write("Access denied");
writer.write("</h1></body></html>");
writer.flush();
}
});
body.setContentType("text/html; charset=UTF-8");
response.setEntity(body);
System.out.println("Cannot read file " + file.getPath());
} else {
response.setStatusCode(HttpStatus.SC_OK);
FileEntity body = new FileEntity(file, "text/html");
response.setEntity(body);
System.out.println("Serving file " + file.getPath());
}
}
}
static class RequestListenerThread extends Thread {
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final String docroot) throws IOException {
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up the HTTP protocol processor
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up request handlers
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new HttpFileHandler(docroot));
// Set up the HTTP service
this.httpService = new HttpService(
httpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up HTTP connection
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + socket.getInetAddress());
conn.bind(socket, this.params);
// Start worker thread
Thread t = new WorkerThread(this.httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.ByteArrayInputStream;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpEntity;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.entity.ByteArrayEntity;
import org.apache.ogt.http.entity.InputStreamEntity;
import org.apache.ogt.http.entity.StringEntity;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpEntityEnclosingRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a POST request.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*
*/
public class ElementalHttpPost {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
HttpEntity[] requestBodies = {
new StringEntity(
"This is the first test request", "UTF-8"),
new ByteArrayEntity(
"This is the second test request".getBytes("UTF-8")),
new InputStreamEntity(
new ByteArrayInputStream(
"This is the third test request (will be chunked)"
.getBytes("UTF-8")), -1)
};
for (int i = 0; i < requestBodies.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpEntityEnclosingRequest request = new BasicHttpEntityEnclosingRequest("POST",
"/servlets-examples/servlet/RequestInfoExample");
request.setEntity(requestBodies[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HTTP;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
/**
* Rudimentary HTTP/1.1 reverse proxy.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP reverse proxy.
*
*
*/
public class ElementalReverseProxy {
private static final String HTTP_IN_CONN = "http.proxy.in-conn";
private static final String HTTP_OUT_CONN = "http.proxy.out-conn";
private static final String HTTP_CONN_KEEPALIVE = "http.proxy.conn-keepalive";
public static void main(String[] args) throws Exception {
if (args.length < 1) {
System.err.println("Please specified target hostname and port");
System.exit(1);
}
String hostname = args[0];
int port = 80;
if (args.length > 1) {
port = Integer.parseInt(args[1]);
}
HttpHost target = new HttpHost(hostname, port);
Thread t = new RequestListenerThread(8888, target);
t.setDaemon(false);
t.start();
}
static class ProxyHandler implements HttpRequestHandler {
private final HttpHost target;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
public ProxyHandler(
final HttpHost target,
final HttpProcessor httpproc,
final HttpRequestExecutor httpexecutor) {
super();
this.target = target;
this.httpproc = httpproc;
this.httpexecutor = httpexecutor;
this.connStrategy = new DefaultConnectionReuseStrategy();
}
public void handle(
final HttpRequest request,
final HttpResponse response,
final HttpContext context) throws HttpException, IOException {
HttpClientConnection conn = (HttpClientConnection) context.getAttribute(
HTTP_OUT_CONN);
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, this.target);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
// Remove hop-by-hop headers
request.removeHeaders(HTTP.CONTENT_LEN);
request.removeHeaders(HTTP.TRANSFER_ENCODING);
request.removeHeaders(HTTP.CONN_DIRECTIVE);
request.removeHeaders("Keep-Alive");
request.removeHeaders("Proxy-Authenticate");
request.removeHeaders("TE");
request.removeHeaders("Trailers");
request.removeHeaders("Upgrade");
this.httpexecutor.preProcess(request, this.httpproc, context);
HttpResponse targetResponse = this.httpexecutor.execute(request, conn, context);
this.httpexecutor.postProcess(response, this.httpproc, context);
// Remove hop-by-hop headers
targetResponse.removeHeaders(HTTP.CONTENT_LEN);
targetResponse.removeHeaders(HTTP.TRANSFER_ENCODING);
targetResponse.removeHeaders(HTTP.CONN_DIRECTIVE);
targetResponse.removeHeaders("Keep-Alive");
targetResponse.removeHeaders("TE");
targetResponse.removeHeaders("Trailers");
targetResponse.removeHeaders("Upgrade");
response.setStatusLine(targetResponse.getStatusLine());
response.setHeaders(targetResponse.getAllHeaders());
response.setEntity(targetResponse.getEntity());
System.out.println("<< Response: " + response.getStatusLine());
boolean keepalive = this.connStrategy.keepAlive(response, context);
context.setAttribute(HTTP_CONN_KEEPALIVE, new Boolean(keepalive));
}
}
static class RequestListenerThread extends Thread {
private final HttpHost target;
private final ServerSocket serversocket;
private final HttpParams params;
private final HttpService httpService;
public RequestListenerThread(int port, final HttpHost target) throws IOException {
this.target = target;
this.serversocket = new ServerSocket(port);
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "HttpComponents/1.1");
// Set up HTTP protocol processor for incoming connections
HttpProcessor inhttpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
// Set up HTTP protocol processor for outgoing connections
HttpProcessor outhttpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
// Set up outgoing request executor
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
// Set up incoming request handler
HttpRequestHandlerRegistry reqistry = new HttpRequestHandlerRegistry();
reqistry.register("*", new ProxyHandler(
this.target,
outhttpproc,
httpexecutor));
// Set up the HTTP service
this.httpService = new HttpService(
inhttpproc,
new DefaultConnectionReuseStrategy(),
new DefaultHttpResponseFactory(),
reqistry,
this.params);
}
public void run() {
System.out.println("Listening on port " + this.serversocket.getLocalPort());
while (!Thread.interrupted()) {
try {
// Set up incoming HTTP connection
Socket insocket = this.serversocket.accept();
DefaultHttpServerConnection inconn = new DefaultHttpServerConnection();
System.out.println("Incoming connection from " + insocket.getInetAddress());
inconn.bind(insocket, this.params);
// Set up outgoing HTTP connection
Socket outsocket = new Socket(this.target.getHostName(), this.target.getPort());
DefaultHttpClientConnection outconn = new DefaultHttpClientConnection();
outconn.bind(outsocket, this.params);
System.out.println("Outgoing connection to " + outsocket.getInetAddress());
// Start worker thread
Thread t = new ProxyThread(this.httpService, inconn, outconn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
System.err.println("I/O error initialising connection thread: "
+ e.getMessage());
break;
}
}
}
}
static class ProxyThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection inconn;
private final HttpClientConnection outconn;
public ProxyThread(
final HttpService httpservice,
final HttpServerConnection inconn,
final HttpClientConnection outconn) {
super();
this.httpservice = httpservice;
this.inconn = inconn;
this.outconn = outconn;
}
public void run() {
System.out.println("New connection thread");
HttpContext context = new BasicHttpContext(null);
// Bind connection objects to the execution context
context.setAttribute(HTTP_IN_CONN, this.inconn);
context.setAttribute(HTTP_OUT_CONN, this.outconn);
try {
while (!Thread.interrupted()) {
if (!this.inconn.isOpen()) {
this.outconn.close();
break;
}
this.httpservice.handleRequest(this.inconn, context);
Boolean keepalive = (Boolean) context.getAttribute(HTTP_CONN_KEEPALIVE);
if (!Boolean.TRUE.equals(keepalive)) {
this.outconn.close();
this.inconn.close();
break;
}
}
} catch (ConnectionClosedException ex) {
System.err.println("Client closed connection");
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.inconn.shutdown();
} catch (IOException ignore) {}
try {
this.outconn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import java.net.Socket;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpClientConnection;
import org.apache.ogt.http.message.BasicHttpRequest;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.HttpProtocolParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
import org.apache.ogt.http.util.EntityUtils;
/**
* Elemental example for executing a GET request.
* <p>
* Please note the purpose of this application is demonstrate the usage of HttpCore APIs.
* It is NOT intended to demonstrate the most efficient way of building an HTTP client.
*
*
*
*/
public class ElementalHttpGet {
public static void main(String[] args) throws Exception {
HttpParams params = new SyncBasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, "UTF-8");
HttpProtocolParams.setUserAgent(params, "HttpComponents/1.1");
HttpProtocolParams.setUseExpectContinue(params, true);
HttpProcessor httpproc = new ImmutableHttpProcessor(new HttpRequestInterceptor[] {
// Required protocol interceptors
new RequestContent(),
new RequestTargetHost(),
// Recommended protocol interceptors
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()});
HttpRequestExecutor httpexecutor = new HttpRequestExecutor();
HttpContext context = new BasicHttpContext(null);
HttpHost host = new HttpHost("localhost", 8080);
DefaultHttpClientConnection conn = new DefaultHttpClientConnection();
ConnectionReuseStrategy connStrategy = new DefaultConnectionReuseStrategy();
context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, host);
try {
String[] targets = {
"/",
"/servlets-examples/servlet/RequestInfoExample",
"/somewhere%20in%20pampa"};
for (int i = 0; i < targets.length; i++) {
if (!conn.isOpen()) {
Socket socket = new Socket(host.getHostName(), host.getPort());
conn.bind(socket, params);
}
BasicHttpRequest request = new BasicHttpRequest("GET", targets[i]);
System.out.println(">> Request URI: " + request.getRequestLine().getUri());
request.setParams(params);
httpexecutor.preProcess(request, httpproc, context);
HttpResponse response = httpexecutor.execute(request, conn, context);
response.setParams(params);
httpexecutor.postProcess(response, httpproc, context);
System.out.println("<< Response: " + response.getStatusLine());
System.out.println(EntityUtils.toString(response.getEntity()));
System.out.println("==============");
if (!connStrategy.keepAlive(response, context)) {
conn.close();
} else {
System.out.println("Connection kept alive...");
}
}
} finally {
conn.close();
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.examples;
import org.apache.ogt.http.util.VersionInfo;
/**
* Prints version information for debugging purposes.
* This can be used to verify that the correct versions of the
* HttpComponent JARs are picked up from the classpath.
*
*
*/
public class PrintVersionInfo {
/** A default list of module packages. */
private final static String[] MODULE_LIST = {
"org.apache.ogt.http", // HttpCore
"org.apache.ogt.http.nio", // HttpCore NIO
"org.apache.ogt.http.client", // HttpClient
};
/**
* Prints version information.
*
* @param args command line arguments. Leave empty to print version
* information for the default packages. Otherwise, pass
* a list of packages for which to get version info.
*/
public static void main(String args[]) {
String[] pckgs = (args.length > 0) ? args : MODULE_LIST;
VersionInfo[] via = VersionInfo.loadVersionInfo(pckgs, null);
System.out.println("version info for thread context classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
System.out.println();
// if the version information for the classloader of this class
// is different from that for the thread context classloader,
// there may be a problem with multiple versions in the classpath
via = VersionInfo.loadVersionInfo
(pckgs, PrintVersionInfo.class.getClassLoader());
System.out.println("version info for static classloader:");
for (int i=0; i<via.length; i++)
System.out.println(via[i]);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import org.apache.ogt.http.ProtocolVersion;
import org.apache.ogt.http.message.AbstractHttpMessage;
import org.apache.ogt.http.params.HttpProtocolParams;
/**
* {@link org.apache.ogt.http.HttpMessage} mockup implementation.
*
*/
public class HttpMessageMockup extends AbstractHttpMessage {
public HttpMessageMockup() {
super();
}
public ProtocolVersion getProtocolVersion() {
return HttpProtocolParams.getVersion(this.getParams());
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.ByteArrayOutputStream;
import java.io.OutputStream;
import org.apache.ogt.http.impl.io.AbstractSessionOutputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionOutputBuffer} mockup implementation.
*
*/
public class SessionOutputBufferMockup extends AbstractSessionOutputBuffer {
private ByteArrayOutputStream buffer = new ByteArrayOutputStream();
public static final int BUFFER_SIZE = 16;
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize,
final HttpParams params) {
super();
init(outstream, buffersize, params);
}
public SessionOutputBufferMockup(
final OutputStream outstream,
int buffersize) {
this(outstream, buffersize, new BasicHttpParams());
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer,
final HttpParams params) {
this(buffer, BUFFER_SIZE, params);
this.buffer = buffer;
}
public SessionOutputBufferMockup(
final ByteArrayOutputStream buffer) {
this(buffer, BUFFER_SIZE, new BasicHttpParams());
this.buffer = buffer;
}
public SessionOutputBufferMockup(final HttpParams params) {
this(new ByteArrayOutputStream(), params);
}
public SessionOutputBufferMockup() {
this(new ByteArrayOutputStream(), new BasicHttpParams());
}
public byte[] getData() {
if (this.buffer != null) {
return this.buffer.toByteArray();
} else {
return new byte[] {};
}
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import org.apache.ogt.http.impl.io.AbstractSessionInputBuffer;
import org.apache.ogt.http.params.BasicHttpParams;
import org.apache.ogt.http.params.HttpParams;
/**
* {@link org.apache.ogt.http.io.SessionInputBuffer} mockup implementation.
*/
public class SessionInputBufferMockup extends AbstractSessionInputBuffer {
public static final int BUFFER_SIZE = 16;
public SessionInputBufferMockup(
final InputStream instream,
int buffersize,
final HttpParams params) {
super();
init(instream, buffersize, params);
}
public SessionInputBufferMockup(
final InputStream instream,
int buffersize) {
this(instream, buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
final HttpParams params) {
this(bytes, BUFFER_SIZE, params);
}
public SessionInputBufferMockup(
final byte[] bytes) {
this(bytes, BUFFER_SIZE, new BasicHttpParams());
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize,
final HttpParams params) {
this(new ByteArrayInputStream(bytes), buffersize, params);
}
public SessionInputBufferMockup(
final byte[] bytes,
int buffersize) {
this(new ByteArrayInputStream(bytes), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, params);
}
public SessionInputBufferMockup(
final String s,
final String charset,
int buffersize)
throws UnsupportedEncodingException {
this(s.getBytes(charset), buffersize, new BasicHttpParams());
}
public SessionInputBufferMockup(
final String s,
final String charset,
final HttpParams params)
throws UnsupportedEncodingException {
this(s.getBytes(charset), params);
}
public SessionInputBufferMockup(
final String s,
final String charset)
throws UnsupportedEncodingException {
this(s.getBytes(charset), new BasicHttpParams());
}
public boolean isDataAvailable(int timeout) throws IOException {
return true;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
/**
* Test class similar to {@link java.io.ByteArrayInputStream} that throws if encounters
* value zero '\000' in the source byte array.
*/
public class TimeoutByteArrayInputStream extends InputStream {
private final byte[] buf;
private int pos;
protected int count;
public TimeoutByteArrayInputStream(byte[] buf, int off, int len) {
super();
this.buf = buf;
this.pos = off;
this.count = Math.min(off + len, buf.length);
}
public TimeoutByteArrayInputStream(byte[] buf) {
this(buf, 0, buf.length);
}
public int read() throws IOException {
if (this.pos < this.count) {
return -1;
}
int v = this.buf[this.pos++] & 0xff;
if (v != 0) {
return v;
} else {
throw new InterruptedIOException("Timeout");
}
}
public int read(byte b[], int off, int len) throws IOException {
if (b == null) {
throw new NullPointerException();
} else if ((off < 0) || (off > b.length) || (len < 0) ||
((off + len) > b.length) || ((off + len) < 0)) {
throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length);
}
if (this.pos >= this.count) {
return -1;
}
if (this.pos + len > this.count) {
len = this.count - this.pos;
}
if (len <= 0) {
return 0;
}
if ((this.buf[this.pos] & 0xff) == 0) {
this.pos++;
throw new InterruptedIOException("Timeout");
}
for (int i = 0; i < len; i++) {
int v = this.buf[this.pos] & 0xff;
if (v == 0) {
return i;
} else {
b[off + i] = (byte) v;
this.pos++;
}
}
return len;
}
public long skip(long n) {
if (this.pos + n > this.count) {
n = this.count - this.pos;
}
if (n < 0) {
return 0;
}
this.pos += n;
return n;
}
public int available() {
return this.count - this.pos;
}
public boolean markSupported() {
return false;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.HttpConnection;
import org.apache.ogt.http.HttpConnectionMetrics;
/**
* {@link HttpConnection} mockup implementation.
*
*/
public class HttpConnectionMockup implements HttpConnection {
private boolean open = true;
public HttpConnectionMockup() {
super();
}
public void close() throws IOException {
this.open = false;
}
public void shutdown() throws IOException {
this.open = false;
}
public void setSocketTimeout(int timeout) {
}
public int getSocketTimeout() {
return -1;
}
public boolean isOpen() {
return this.open;
}
public boolean isStale() {
return false;
}
public HttpConnectionMetrics getMetrics() {
return null;
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpClientConnection;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpHost;
import org.apache.ogt.http.HttpRequest;
import org.apache.ogt.http.HttpRequestInterceptor;
import org.apache.ogt.http.HttpResponse;
import org.apache.ogt.http.HttpVersion;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.DefaultedHttpParams;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.ExecutionContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestExecutor;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.RequestConnControl;
import org.apache.ogt.http.protocol.RequestContent;
import org.apache.ogt.http.protocol.RequestExpectContinue;
import org.apache.ogt.http.protocol.RequestTargetHost;
import org.apache.ogt.http.protocol.RequestUserAgent;
public class HttpClient {
private final HttpParams params;
private final HttpProcessor httpproc;
private final HttpRequestExecutor httpexecutor;
private final ConnectionReuseStrategy connStrategy;
private final HttpContext context;
public HttpClient() {
super();
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setParameter(CoreProtocolPNames.PROTOCOL_VERSION, HttpVersion.HTTP_1_1)
.setParameter(CoreProtocolPNames.USER_AGENT, "TEST-CLIENT/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpRequestInterceptor[] {
new RequestContent(),
new RequestTargetHost(),
new RequestConnControl(),
new RequestUserAgent(),
new RequestExpectContinue()
});
this.httpexecutor = new HttpRequestExecutor();
this.connStrategy = new DefaultConnectionReuseStrategy();
this.context = new BasicHttpContext();
}
public HttpParams getParams() {
return this.params;
}
public HttpResponse execute(
final HttpRequest request,
final HttpHost targetHost,
final HttpClientConnection conn) throws HttpException, IOException {
this.context.setAttribute(ExecutionContext.HTTP_REQUEST, request);
this.context.setAttribute(ExecutionContext.HTTP_TARGET_HOST, targetHost);
this.context.setAttribute(ExecutionContext.HTTP_CONNECTION, conn);
request.setParams(new DefaultedHttpParams(request.getParams(), this.params));
this.httpexecutor.preProcess(request, this.httpproc, this.context);
HttpResponse response = this.httpexecutor.execute(request, conn, this.context);
response.setParams(new DefaultedHttpParams(response.getParams(), this.params));
this.httpexecutor.postProcess(response, this.httpproc, this.context);
return response;
}
public boolean keepAlive(final HttpResponse response) {
return this.connStrategy.keepAlive(response, this.context);
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import org.apache.ogt.http.entity.AbstractHttpEntity;
/**
* {@link AbstractHttpEntity} mockup implementation.
*
*/
public class HttpEntityMockup extends AbstractHttpEntity {
private boolean stream;
public InputStream getContent() throws IOException, IllegalStateException {
return null;
}
public long getContentLength() {
return 0;
}
public boolean isRepeatable() {
return false;
}
public void setStreaming(final boolean b) {
this.stream = b;
}
public boolean isStreaming() {
return this.stream;
}
public void writeTo(OutputStream outstream) throws IOException {
}
}
| Java |
/*
* ====================================================================
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.ogt.http.mockup;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;
import org.apache.ogt.http.ConnectionClosedException;
import org.apache.ogt.http.ConnectionReuseStrategy;
import org.apache.ogt.http.HttpException;
import org.apache.ogt.http.HttpResponseFactory;
import org.apache.ogt.http.HttpResponseInterceptor;
import org.apache.ogt.http.HttpServerConnection;
import org.apache.ogt.http.impl.DefaultConnectionReuseStrategy;
import org.apache.ogt.http.impl.DefaultHttpResponseFactory;
import org.apache.ogt.http.impl.DefaultHttpServerConnection;
import org.apache.ogt.http.params.CoreConnectionPNames;
import org.apache.ogt.http.params.CoreProtocolPNames;
import org.apache.ogt.http.params.HttpParams;
import org.apache.ogt.http.params.SyncBasicHttpParams;
import org.apache.ogt.http.protocol.BasicHttpContext;
import org.apache.ogt.http.protocol.HttpContext;
import org.apache.ogt.http.protocol.HttpExpectationVerifier;
import org.apache.ogt.http.protocol.HttpProcessor;
import org.apache.ogt.http.protocol.HttpRequestHandler;
import org.apache.ogt.http.protocol.HttpRequestHandlerRegistry;
import org.apache.ogt.http.protocol.HttpService;
import org.apache.ogt.http.protocol.ImmutableHttpProcessor;
import org.apache.ogt.http.protocol.ResponseConnControl;
import org.apache.ogt.http.protocol.ResponseContent;
import org.apache.ogt.http.protocol.ResponseDate;
import org.apache.ogt.http.protocol.ResponseServer;
public class HttpServer {
private final HttpParams params;
private final HttpProcessor httpproc;
private final ConnectionReuseStrategy connStrategy;
private final HttpResponseFactory responseFactory;
private final HttpRequestHandlerRegistry reqistry;
private final ServerSocket serversocket;
private HttpExpectationVerifier expectationVerifier;
private Thread listener;
private volatile boolean shutdown;
public HttpServer() throws IOException {
super();
this.params = new SyncBasicHttpParams();
this.params
.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, 5000)
.setIntParameter(CoreConnectionPNames.SOCKET_BUFFER_SIZE, 8 * 1024)
.setBooleanParameter(CoreConnectionPNames.STALE_CONNECTION_CHECK, false)
.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true)
.setParameter(CoreProtocolPNames.ORIGIN_SERVER, "TEST-SERVER/1.1");
this.httpproc = new ImmutableHttpProcessor(
new HttpResponseInterceptor[] {
new ResponseDate(),
new ResponseServer(),
new ResponseContent(),
new ResponseConnControl()
});
this.connStrategy = new DefaultConnectionReuseStrategy();
this.responseFactory = new DefaultHttpResponseFactory();
this.reqistry = new HttpRequestHandlerRegistry();
this.serversocket = new ServerSocket(0);
}
public void registerHandler(
final String pattern,
final HttpRequestHandler handler) {
this.reqistry.register(pattern, handler);
}
public void setExpectationVerifier(final HttpExpectationVerifier expectationVerifier) {
this.expectationVerifier = expectationVerifier;
}
private HttpServerConnection acceptConnection() throws IOException {
Socket socket = this.serversocket.accept();
DefaultHttpServerConnection conn = new DefaultHttpServerConnection();
conn.bind(socket, this.params);
return conn;
}
public int getPort() {
return this.serversocket.getLocalPort();
}
public InetAddress getInetAddress() {
return this.serversocket.getInetAddress();
}
public void start() {
if (this.listener != null) {
throw new IllegalStateException("Listener already running");
}
this.listener = new Thread(new Runnable() {
public void run() {
while (!shutdown && !Thread.interrupted()) {
try {
// Set up HTTP connection
HttpServerConnection conn = acceptConnection();
// Set up the HTTP service
HttpService httpService = new HttpService(
httpproc,
connStrategy,
responseFactory,
reqistry,
expectationVerifier,
params);
// Start worker thread
Thread t = new WorkerThread(httpService, conn);
t.setDaemon(true);
t.start();
} catch (InterruptedIOException ex) {
break;
} catch (IOException e) {
break;
}
}
}
});
this.listener.start();
}
public void shutdown() {
if (this.shutdown) {
return;
}
this.shutdown = true;
try {
this.serversocket.close();
} catch (IOException ignore) {}
this.listener.interrupt();
try {
this.listener.join(1000);
} catch (InterruptedException ignore) {}
}
static class WorkerThread extends Thread {
private final HttpService httpservice;
private final HttpServerConnection conn;
public WorkerThread(
final HttpService httpservice,
final HttpServerConnection conn) {
super();
this.httpservice = httpservice;
this.conn = conn;
}
public void run() {
HttpContext context = new BasicHttpContext(null);
try {
while (!Thread.interrupted() && this.conn.isOpen()) {
this.httpservice.handleRequest(this.conn, context);
}
} catch (ConnectionClosedException ex) {
} catch (IOException ex) {
System.err.println("I/O error: " + ex.getMessage());
} catch (HttpException ex) {
System.err.println("Unrecoverable HTTP protocol violation: " + ex.getMessage());
} finally {
try {
this.conn.shutdown();
} catch (IOException ignore) {}
}
}
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import android.util.Log;
/**
* Translates SimplePosition objects to a telnet command and sends the commands to a telnet session with an android emulator.
*
* @version $Id$
* @author Bram Pouwelse (c) Jan 22, 2009, Sogeti B.V.
*
*/
public class TelnetPositionSender
{
private static final String TAG = "TelnetPositionSender";
private static final String TELNET_OK_FEEDBACK_MESSAGE = "OK\r\n";
private static String HOST = "10.0.2.2";
private static int PORT = 5554;
private Socket socket;
private OutputStream out;
private InputStream in;
/**
* Constructor
*/
public TelnetPositionSender()
{
}
/**
* Setup a telnet connection to the android emulator
*/
private void createTelnetConnection() {
try {
this.socket = new Socket(HOST, PORT);
this.in = this.socket.getInputStream();
this.out = this.socket.getOutputStream();
Thread.sleep(500); // give the telnet session half a second to
// respond
} catch (UnknownHostException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
readInput(); // read the input to throw it away the first time :)
}
private void closeConnection()
{
try
{
this.out.close();
this.in.close();
this.socket.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
/**
* read the input buffer
* @return
*/
private String readInput() {
StringBuffer sb = new StringBuffer();
try {
byte[] bytes = new byte[this.in.available()];
this.in.read(bytes);
for (byte b : bytes) {
sb.append((char) b);
}
} catch (Exception e) {
System.err.println("Warning: Could not read the input from the telnet session");
}
return sb.toString();
}
/**
* When a new position is received it is sent to the android emulator over the telnet connection.
*
* @param position the position to send
*/
public void sendCommand(String telnetString)
{
createTelnetConnection();
Log.v( TAG, "Sending command: "+telnetString);
byte[] sendArray = telnetString.getBytes();
for (byte b : sendArray)
{
try
{
this.out.write(b);
} catch (IOException e) {
System.out.println("IOException: " + e.getMessage());
}
}
String feedback = readInput();
if (!feedback.equals(TELNET_OK_FEEDBACK_MESSAGE))
{
System.err.println("Warning: no OK mesage message was(" + feedback + ")");
}
closeConnection();
}
} | Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.utils;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Calendar;
import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;
import android.content.Context;
import android.content.res.XmlResourceParser;
import android.util.Log;
/**
* Feeder of GPS-location information
*
* @version $Id$
* @author Maarten van Berkel (maarten.van.berkel@sogeti.nl / +0586)
*/
public class MockGPSLoggerDriver implements Runnable
{
private static final String TAG = "MockGPSLoggerDriver";
private boolean running = true;
private int mTimeout;
private Context mContext;
private TelnetPositionSender sender;
private ArrayList<SimplePosition> positions;
private int mRouteResource;
/**
* Constructor: create a new MockGPSLoggerDriver.
*
* @param context context of the test package
* @param route resource identifier for the xml route
* @param timeout time to idle between waypoints in miliseconds
*/
public MockGPSLoggerDriver(Context context, int route, int timeout)
{
this();
this.mTimeout = timeout;
this.mRouteResource = route;// R.xml.denhaagdenbosch;
this.mContext = context;
}
public MockGPSLoggerDriver()
{
this.sender = new TelnetPositionSender();
}
public int getPositions()
{
return this.positions.size();
}
private void prepareRun( int xmlResource )
{
this.positions = new ArrayList<SimplePosition>();
XmlResourceParser xmlParser = this.mContext.getResources().getXml( xmlResource );
doUglyXMLParsing( this.positions, xmlParser );
xmlParser.close();
}
public void run()
{
prepareRun( this.mRouteResource );
while( this.running && ( this.positions.size() > 0 ) )
{
SimplePosition position = this.positions.remove( 0 );
//String nmeaCommand = createGPGGALocationCommand(position.getLongitude(), position.getLatitude(), 0);
String nmeaCommand = createGPRMCLocationCommand( position.lng, position.lat, 0, 0 );
String checksum = calulateChecksum( nmeaCommand );
this.sender.sendCommand( "geo nmea $" + nmeaCommand + "*" + checksum + "\r\n" );
try
{
Thread.sleep( this.mTimeout );
}
catch( InterruptedException e )
{
Log.w( TAG, "Interrupted" );
}
}
}
public static String calulateChecksum( String nmeaCommand )
{
byte[] chars = null;
try
{
chars = nmeaCommand.getBytes( "ASCII" );
}
catch( UnsupportedEncodingException e )
{
e.printStackTrace();
}
byte xor = 0;
for( int i = 0; i < chars.length; i++ )
{
xor ^= chars[i];
}
return Integer.toHexString( (int) xor ).toUpperCase();
}
public void stop()
{
this.running = false;
}
private void doUglyXMLParsing( ArrayList<SimplePosition> positions, XmlResourceParser xmlParser )
{
int eventType;
try
{
eventType = xmlParser.getEventType();
SimplePosition lastPosition = null;
boolean speed = false;
while( eventType != XmlPullParser.END_DOCUMENT )
{
if( eventType == XmlPullParser.START_TAG )
{
if( xmlParser.getName().equals( "trkpt" ) || xmlParser.getName().equals( "rtept" ) || xmlParser.getName().equals( "wpt" ) )
{
lastPosition = new SimplePosition( xmlParser.getAttributeFloatValue( 0, 12.3456F ), xmlParser.getAttributeFloatValue( 1, 12.3456F ) );
positions.add( lastPosition );
}
if( xmlParser.getName().equals( "speed" ) )
{
speed = true;
}
}
else if( eventType == XmlPullParser.END_TAG )
{
if( xmlParser.getName().equals( "speed" ) )
{
speed = false;
}
}
else if( eventType == XmlPullParser.TEXT )
{
if( lastPosition != null && speed )
{
lastPosition.speed = Float.parseFloat( xmlParser.getText() );
}
}
eventType = xmlParser.next();
}
}
catch( XmlPullParserException e )
{ /* ignore */
}
catch( IOException e )
{/* ignore */
}
}
/**
* Create a NMEA GPRMC sentence
*
* @param longitude
* @param latitude
* @param elevation
* @param speed in mps
* @return
*/
public static String createGPRMCLocationCommand( double longitude, double latitude, double elevation, double speed )
{
speed *= 0.51; // from m/s to knots
final String COMMAND_GPS = "GPRMC," + "%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d,A," + // ss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection (N or S)
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection (E or W)
"%14$.2f," + // Speed over ground in knot
"0," + // Track made good in degrees True
"%11$02d" + // dd
"%12$02d" + // mm
"%13$02d," + // yy
"0," + // Magnetic variation degrees (Easterly var. subtracts from true course)
"E," + // East/West
"mode"; // Just as workaround....
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection, c.get( Calendar.DAY_OF_MONTH ), c.get( Calendar.MONTH ), c.get( Calendar.YEAR ) - 2000 , speed);
return command;
}
public static String createGPGGALocationCommand( double longitude, double latitude, double elevation )
{
final String COMMAND_GPS = "GPGGA," + // $--GGA,
"%1$02d" + // hh c.get(Calendar.HOUR_OF_DAY)
"%2$02d" + // mm c.get(Calendar.MINUTE)
"%3$02d." + // ss. c.get(Calendar.SECOND)
"%4$03d," + // sss, c.get(Calendar.MILLISECOND)
"%5$03d" + // llll latDegree
"%6$09.6f," + // latMinute
"%7$c," + // latDirection
"%8$03d" + // longDegree
"%9$09.6f," + // longMinutett
"%10$c," + // longDirection
"1,05,02.1,00545.5,M,-26.0,M,,";
Calendar c = Calendar.getInstance();
double absLong = Math.abs( longitude );
int longDegree = (int) Math.floor( absLong );
char longDirection = 'E';
if( longitude < 0 )
{
longDirection = 'W';
}
double longMinute = ( absLong - Math.floor( absLong ) ) * 60;
double absLat = Math.abs( latitude );
int latDegree = (int) Math.floor( absLat );
char latDirection = 'N';
if( latitude < 0 )
{
latDirection = 'S';
}
double latMinute = ( absLat - Math.floor( absLat ) ) * 60;
String command = String.format( COMMAND_GPS, c.get( Calendar.HOUR_OF_DAY ), c.get( Calendar.MINUTE ), c.get( Calendar.SECOND ), c.get( Calendar.MILLISECOND ), latDegree, latMinute,
latDirection, longDegree, longMinute, longDirection );
return command;
}
class SimplePosition
{
public float speed;
public double lat, lng;
public SimplePosition(float latitude, float longtitude)
{
this.lat = latitude;
this.lng = longtitude;
}
}
public void sendSMS( String string )
{
this.sender.sendCommand( "sms send 31886606607 " + string + "\r\n" );
}
} | Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests;
import junit.framework.TestSuite;
import nl.sogeti.android.gpstracker.tests.actions.ExportGPXTest;
import nl.sogeti.android.gpstracker.tests.db.GPStrackingProviderTest;
import nl.sogeti.android.gpstracker.tests.gpsmock.MockGPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.logger.GPSLoggerServiceTest;
import nl.sogeti.android.gpstracker.tests.userinterface.LoggerMapTest;
import android.test.InstrumentationTestRunner;
import android.test.InstrumentationTestSuite;
/**
* Perform unit tests Run on the adb shell:
*
* <pre>
* am instrument -w nl.sogeti.android.gpstracker.tests/.GPStrackingInstrumentation
* </pre>
*
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class GPStrackingInstrumentation extends InstrumentationTestRunner
{
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getAllTests()
*/
@Override
public TestSuite getAllTests()
{
TestSuite suite = new InstrumentationTestSuite( this );
suite.setName( "GPS Tracking Testsuite" );
suite.addTestSuite( GPStrackingProviderTest.class );
suite.addTestSuite( MockGPSLoggerServiceTest.class );
suite.addTestSuite( GPSLoggerServiceTest.class );
suite.addTestSuite( ExportGPXTest.class );
suite.addTestSuite( LoggerMapTest.class );
// suite.addTestSuite( OpenGPSTrackerDemo.class ); // The demo recorded for youtube
// suite.addTestSuite( MapStressTest.class ); // The stress test of the map viewer
return suite;
}
/**
* (non-Javadoc)
* @see android.test.InstrumentationTestRunner#getLoader()
*/
@Override
public ClassLoader getLoader()
{
return GPStrackingInstrumentation.class.getClassLoader();
}
}
| Java |
/*------------------------------------------------------------------------------
** Ident: Innovation en Inspiration > Google Android
** Author: rene
** Copyright: (c) Jan 22, 2009 Sogeti Nederland B.V. All Rights Reserved.
**------------------------------------------------------------------------------
** Sogeti Nederland B.V. | No part of this file may be reproduced
** Distributed Software Engineering | or transmitted in any form or by any
** Lange Dreef 17 | means, electronic or mechanical, for the
** 4131 NJ Vianen | purpose, without the express written
** The Netherlands | permission of the copyright holder.
*------------------------------------------------------------------------------
*
* This file is part of OpenGPSTracker.
*
* OpenGPSTracker is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* OpenGPSTracker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with OpenGPSTracker. If not, see <http://www.gnu.org/licenses/>.
*
*/
package nl.sogeti.android.gpstracker.tests.demo;
import nl.sogeti.android.gpstracker.logger.GPSLoggerServiceManager;
import nl.sogeti.android.gpstracker.tests.utils.MockGPSLoggerDriver;
import nl.sogeti.android.gpstracker.viewer.map.CommonLoggerMap;
import android.test.ActivityInstrumentationTestCase2;
import android.test.suitebuilder.annotation.LargeTest;
import android.test.suitebuilder.annotation.SmallTest;
import com.google.android.maps.GeoPoint;
import com.google.android.maps.MapView;
/**
* @version $Id$
* @author rene (c) Jan 22, 2009, Sogeti B.V.
*/
public class OpenGPSTrackerDemo extends ActivityInstrumentationTestCase2<CommonLoggerMap>
{
private static final int ZOOM_LEVEL = 16;
private static final Class<CommonLoggerMap> CLASS = CommonLoggerMap.class;
private static final String PACKAGE = "nl.sogeti.android.gpstracker";
private CommonLoggerMap mLoggermap;
private GPSLoggerServiceManager mLoggerServiceManager;
private MapView mMapView;
private MockGPSLoggerDriver mSender;
public OpenGPSTrackerDemo()
{
super( PACKAGE, CLASS );
}
@Override
protected void setUp() throws Exception
{
super.setUp();
this.mLoggermap = getActivity();
this.mMapView = (MapView) this.mLoggermap.findViewById( nl.sogeti.android.gpstracker.R.id.myMapView );
this.mSender = new MockGPSLoggerDriver();
}
protected void tearDown() throws Exception
{
this.mLoggerServiceManager.shutdown( getActivity() );
super.tearDown();
}
/**
* Start tracking and allow it to go on for 30 seconds
*
* @throws InterruptedException
*/
@LargeTest
public void testTracking() throws InterruptedException
{
a_introSingelUtrecht30Seconds();
c_startRoute10Seconds();
d_showDrawMethods30seconds();
e_statistics10Seconds();
f_showPrecision30seconds();
g_stopTracking10Seconds();
h_shareTrack30Seconds();
i_finish10Seconds();
}
@SmallTest
public void a_introSingelUtrecht30Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL);
Thread.sleep( 1 * 1000 );
// Browse the Utrecht map
sendMessage( "Selecting a previous recorded track" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
Thread.sleep( 2 * 1000 );
sendMessage( "The walk around the \"singel\" in Utrecht" );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
Thread.sleep( 2 * 1000 );
sendMessage( "Scrolling about" );
this.mMapView.getController().animateTo( new GeoPoint( 52095829, 5118599 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52096778, 5125090 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52085117, 5128255 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52081517, 5121646 ) );
Thread.sleep( 2 * 1000 );
this.mMapView.getController().animateTo( new GeoPoint( 52093535, 5116711 ) );
Thread.sleep( 2 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 5 * 1000 );
}
@SmallTest
public void c_startRoute10Seconds() throws InterruptedException
{
sendMessage( "Lets start a new route" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );//Toggle start/stop tracker
Thread.sleep( 1 * 1000 );
this.mMapView.getController().setZoom( ZOOM_LEVEL);
this.sendKeys( "D E M O SPACE R O U T E ENTER" );
Thread.sleep( 5 * 1000 );
sendMessage( "The GPS logger is already running as a background service" );
Thread.sleep( 5 * 1000 );
this.sendKeys( "ENTER" );
this.sendKeys( "T T T T" );
Thread.sleep( 30 * 1000 );
this.sendKeys( "G G" );
}
@SmallTest
public void d_showDrawMethods30seconds() throws InterruptedException
{
sendMessage( "Track drawing color has different options" );
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Plain green" );
Thread.sleep( 15 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "MENU" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP");
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Average speeds drawn" );
Thread.sleep( 15 * 1000 );
}
@SmallTest
public void e_statistics10Seconds() throws InterruptedException
{
// Show of the statistics screen
sendMessage( "Lets look at some statistics" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "E" );
Thread.sleep( 2 * 1000 );
sendMessage( "Shows the basics on time, speed and distance" );
Thread.sleep( 10 * 1000 );
this.sendKeys( "BACK" );
}
@SmallTest
public void f_showPrecision30seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
sendMessage( "There are options on the precision of tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_RIGHT DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "S" );
Thread.sleep( 3 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_UP DPAD_UP" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_UP" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "BACK" );
sendMessage( "Course will drain the battery the least" );
Thread.sleep( 5 * 1000 );
sendMessage( "Fine will store the best track" );
Thread.sleep( 10 * 1000 );
}
@SmallTest
public void g_stopTracking10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
Thread.sleep( 5 * 1000 );
// Stop tracking
sendMessage( "Stopping tracking" );
this.sendKeys( "MENU DPAD_RIGHT DPAD_LEFT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "T" );
Thread.sleep( 2 * 1000 );
sendMessage( "Is the track stored?" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "MENU DPAD_RIGHT" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "L" );
this.sendKeys( "DPAD_DOWN DPAD_DOWN" );
Thread.sleep( 2 * 1000 );
this.sendKeys( "DPAD_CENTER" );
Thread.sleep( 2 * 1000 );
}
private void h_shareTrack30Seconds()
{
// TODO Auto-generated method stub
}
@SmallTest
public void i_finish10Seconds() throws InterruptedException
{
this.mMapView.getController().setZoom( ZOOM_LEVEL );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
Thread.sleep( 1 * 1000 );
this.sendKeys( "G G" );
sendMessage( "Thank you for watching this demo." );
Thread.sleep( 10 * 1000 );
Thread.sleep( 5 * 1000 );
}
private void sendMessage( String string )
{
this.mSender.sendSMS( string );
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
/**
* Utility methods for working with a DOM tree.
* $Id: DOMUtil.java,v 1.18 2004/09/10 14:20:50 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class DOMUtil
{
/**
* Clears all childnodes in document
*/
public static void clearDocument(Document document)
{
NodeList nodeList = document.getChildNodes();
if (nodeList == null)
{
return;
}
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
document.removeChild(nodeList.item(i));
}
}
/**
* Create empty document TO BE DEBUGGED!.
*/
public static Document createDocument()
{
DocumentBuilder documentBuilder = null;
// System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl");
try
{
documentBuilder = DocumentBuilderFactory.newInstance().newDocumentBuilder();
} catch (ParserConfigurationException pce)
{
warn("ParserConfigurationException: " + pce);
return null;
}
return documentBuilder.newDocument();
}
/**
* Copies all attributes from one element to another in the official way.
*/
public static void copyAttributes(Element elementFrom, Element elementTo)
{
NamedNodeMap nodeList = elementFrom.getAttributes();
if (nodeList == null)
{
// No attributes to copy: just return
return;
}
Attr attrFrom = null;
Attr attrTo = null;
// Needed as factory to create attrs
Document documentTo = elementTo.getOwnerDocument();
int len = nodeList.getLength();
// Copy each attr by making/setting a new one and
// adding to the target element.
for (int i = 0; i < len; i++)
{
attrFrom = (Attr) nodeList.item(i);
// Create an set value
attrTo = documentTo.createAttribute(attrFrom.getName());
attrTo.setValue(attrFrom.getValue());
// Set in target element
elementTo.setAttributeNode(attrTo);
}
}
public static Element getFirstElementByTagName(Document document, String tag)
{
// Get all elements matching the tagname
NodeList nodeList = document.getElementsByTagName(tag);
if (nodeList == null)
{
p("no list of elements with tag=" + tag);
return null;
}
// Get the first if any.
Element element = (Element) nodeList.item(0);
if (element == null)
{
p("no element for tag=" + tag);
return null;
}
return element;
}
public static Element getElementById(Document document, String id)
{
return getElementById(document.getDocumentElement(), id);
}
public static Element getElementById(Element element, String id)
{
return getElementById(element.getChildNodes(), id);
}
/**
* Get Element that has attribute id="xyz".
*/
public static Element getElementById(NodeList nodeList, String id)
{
// Note we should really use the Query here !!
Element element = null;
int len = nodeList.getLength();
for (int i = 0; i < len; i++)
{
Node node = (Node) nodeList.item(i);
if (node.getNodeType() == Node.ELEMENT_NODE)
{
element = (Element) node;
if (((Element) node).getAttribute("id").equals(id))
{
// found it !
break;
}
}
}
// returns found element or null
return element;
}
public static Document parse(InputStream anInputStream)
{
Document document;
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
try
{
DocumentBuilder builder = factory.newDocumentBuilder();
document = builder.parse(anInputStream);
} catch (Exception e)
{
throw new RuntimeException(e);
}
return document;
}
/**
* Prints an XML DOM.
*/
public static void printAsXML(Document document, PrintWriter printWriter)
{
new TreeWalker(new XMLPrintVisitor(printWriter)).traverse(document);
}
/**
* Prints an XML DOM.
*/
public static String dom2String(Document document)
{
StringWriter sw = new StringWriter();
DOMUtil.printAsXML(document, new PrintWriter(sw));
return sw.toString();
}
/**
* Replaces an element in document.
*/
public static void replaceElement(Element newElement, Element oldElement)
{
// Must be 1
Node parent = oldElement.getParentNode();
if (parent == null)
{
warn("replaceElement: no parent of oldElement found");
return;
}
// Create a copy owned by the document
ElementCopyVisitor ecv = new ElementCopyVisitor(oldElement.getOwnerDocument(), newElement);
Element newElementCopy = ecv.getCopy();
// Replace the old element with the new copy
parent.replaceChild(newElementCopy, oldElement);
}
/**
* Write Document structure to XML file.
*/
static public void document2File(Document document, String fileName)
{
new TreeWalker(new XMLPrintVisitor(fileName)).traverse(document);
}
public static void warn(String s)
{
p("DOMUtil: WARNING " + s);
}
public static void p(String s)
{
// System.out.println("DOMUtil: "+s);
}
}
/*
* $Log: DOMUtil.java,v $
* Revision 1.18 2004/09/10 14:20:50 just
* expandIncludes() tab to 2 spaces
*
* Revision 1.17 2004/09/10 12:48:11 just
* ok
*
* Revision 1.16 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.15 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.14 2002/06/18 10:30:02 just
* no rel change
*
* Revision 1.13 2001/08/01 15:20:23 kstroke
* fix for expand includes (added rootDir)
*
* Revision 1.12 2001/02/17 14:28:16 just
* added comments and changed interface for expandIds()
*
* Revision 1.11 2000/12/09 14:35:35 just
* added parse() method with optional DTD validation
*
* Revision 1.10 2000/09/21 22:37:20 just
* removed print statements
*
* Revision 1.9 2000/08/28 00:07:46 just
* changes for introduction of EntityResolverImpl
*
* Revision 1.8 2000/08/24 10:11:12 just
* added XML file verfication
*
* Revision 1.7 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Makes deep copy of an Element for another Document.
* $Id: ElementCopyVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
public class ElementCopyVisitor extends DefaultVisitor
{
Document ownerDocument;
Element elementOrig;
Element elementCopy;
Element elementPointer;
int level = 0;
public ElementCopyVisitor(Document theOwnerDocument, Element theElement)
{
ownerDocument = theOwnerDocument;
elementOrig = theElement;
}
public Element getCopy()
{
new TreeWalker(this).traverse(elementOrig);
return elementCopy;
}
public void visitDocumentPre(Document document)
{
p("visitDocumentPre: level=" + level);
}
public void visitDocumentPost(Document document)
{
p("visitDocumentPost: level=" + level);
}
public void visitElementPre(Element element)
{
p("visitElementPre: " + element.getTagName() + " level=" + level);
// Create the copy; must use target document as factory
Element newElement = ownerDocument.createElement(element.getTagName());
// If first time we need to create the copy
if (elementCopy == null)
{
elementCopy = newElement;
} else
{
elementPointer.appendChild(newElement);
}
// Always point to the last created and appended element
elementPointer = newElement;
level++;
}
public void visitElementPost(Element element)
{
p("visitElementPost: " + element.getTagName() + " level=" + level);
DOMUtil.copyAttributes(element, elementPointer);
level--;
if (level == 0) return;
// Always transfer attributes if any
if (level > 0)
{
elementPointer = (Element) elementPointer.getParentNode();
}
}
public void visitText(Text element)
{
// Create the copy; must use target document as factory
Text newText = ownerDocument.createTextNode(element.getData());
// If first time we need to create the copy
if (elementPointer == null)
{
p("ERROR no element copy");
return;
} else
{
elementPointer.appendChild(newText);
}
}
private void p(String s)
{
//System.out.println("ElementCopyVisitor: "+s);
}
}
/*
* $Log: ElementCopyVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
import org.w3c.dom.*;
import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
/**
* XMLPrintVisitor implements the Visitor interface in the visitor design pattern for the
* purpose of printing in HTML-like format the various DOM-Nodes.
* <p>In HTML-like printing, only the following Nodes are printed:
* <DL>
* <DT>Document</DT>
* <DD>Only the doctype provided on this constructor is written (i.e. no XML declaration, <!DOCTYPE>, or internal DTD).</DD>
* <DT>Element</DT>
* <DD>All element names are uppercased.</DD>
* <DD>Empty elements are written as <code><BR></code> instead of <code><BR/></code>.</DD>
* <DT>Attr</DT>
* <DD>All attribute names are lowercased.</DD>
* <DT>Text</DT>
* </DL>
* <p/>
* <p>The following sample code uses the XMLPrintVisitor on a hierarchy of nodes:
* <pre>
* <p/>
* PrintWriter printWriter = new PrintWriter();
* Visitor htmlPrintVisitor = new XMLPrintVisitor(printWriter);
* TreeWalker treeWalker = new TreeWalker(htmlPrintVisitor);
* treeWalker.traverse(document);
* printWriter.close();
* <p/>
* </pre>
* <p/>
* <P>By default, this doesn't print non-specified attributes.</P>
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
* @version $Id: XMLPrintVisitor.java,v 1.8 2003/01/06 00:23:49 just Exp $
* @see Visitor
* @see TreeWalker
*/
public class XMLPrintVisitor implements Visitor
{
protected Writer writer = null;
protected int level = 0;
protected String doctype = null;
/**
* Constructor for customized encoding and doctype.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
* @param doctype String to be printed at the top of the document.
*/
public XMLPrintVisitor(Writer writer, String encoding, String doctype)
{
this.writer = writer;
this.doctype = doctype;
// this.isPrintNonSpecifiedAttributes = false;
}
/**
* Constructor for customized encoding.
*
* @param writer The character output stream to use.
* @param encoding Java character encoding in use by <VAR>writer</VAR>.
*/
public XMLPrintVisitor(Writer writer, String encoding)
{
this(writer, encoding, null);
}
/**
* Constructor for default encoding.
*
* @param writer The character output stream to use.
*/
public XMLPrintVisitor(Writer writer)
{
this(writer, null, null);
}
/**
* Constructor for default encoding.
*
* @param fileName the filepath to write to
*/
public XMLPrintVisitor(String fileName)
{
try
{
writer = new FileWriter(fileName);
} catch (IOException ioe)
{
}
}
/**
* Writes the <var>doctype</var> from the constructor (if any).
*
* @param document Node print as HTML.
*/
public void visitDocumentPre(Document document)
{
}
/**
* Flush the writer.
*
* @param document Node to print as HTML.
*/
public void visitDocumentPost(Document document)
{
write("\n");
flush();
}
/**
* Creates a formatted string representation of the start of the specified <var>element</var> Node
* and its associated attributes, and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPre(Element element)
{
this.level++;
write("<" + element.getTagName());
NamedNodeMap attributes = element.getAttributes();
for (int i = 0; i < attributes.getLength(); i++)
{
Attr attr = (Attr) attributes.item(i);
visitAttributePre(attr);
}
write(">\n");
}
/**
* Creates a formatted string representation of the end of the specified <var>element</var> Node,
* and directs it to the print writer.
*
* @param element Node to print as XML.
*/
public void visitElementPost(Element element)
{
String tagName = element.getTagName();
// if (element.hasChildNodes()) {
write("</" + tagName + ">\n");
// }
level--;
}
/**
* Creates a formatted string representation of the specified <var>attribute</var> Node
* and its associated attributes, and directs it to the print writer.
* <p>Note that TXAttribute Nodes are not parsed into the document object hierarchy by the
* XML4J parser; attributes exist as part of a Element Node.
*
* @param attr attr to print.
*/
public void visitAttributePre(Attr attr)
{
write(" " + attr.getName() + "=\"" + attr.getValue() + "\"");
}
/**
* Creates a formatted string representation of the specified <var>text</var> Node,
* and directs it to the print writer. CDATASections are respected.
*
* @param text Node to print with format.
*/
public void visitText(Text text)
{
if (this.level > 0)
{
write(text.getData());
}
}
private void write(String s)
{
try
{
writer.write(s);
} catch (IOException e)
{
}
}
private void flush()
{
try
{
writer.flush();
} catch (IOException e)
{
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This class does a pre-order walk of a DOM tree or Node, calling an ElementVisitor
* interface as it goes.
* <p>The numbered nodes in the trees below indicate the order of traversal given
* the specified <code>startNode</code> of "1".
* <pre>
*
* 1 x x
* / \ / \ / \
* 2 6 1 x x x
* /|\ \ /|\ \ /|\ \
* 3 4 5 7 2 3 4 x x 1 x x
*
* </pre>
* $Id: TreeWalker.java,v 1.5 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.Text;
public class TreeWalker
{
private Visitor visitor;
private Node topNode;
/**
* Constructor.
*
* @param
*/
public TreeWalker(Visitor theVisitor)
{
visitor = theVisitor;
}
/**
* Disabled default constructor.
*/
private TreeWalker()
{
}
/**
* Perform a pre-order traversal non-recursive style.
*/
public void traverse(Node node)
{
// Remember the top node
if (topNode == null)
{
topNode = node;
}
while (node != null)
{
visitPre(node);
Node nextNode = node.getFirstChild();
while (nextNode == null)
{
visitPost(node);
// We are ready after post-visiting the topnode
if (node == topNode)
{
return;
}
try
{
nextNode = node.getNextSibling();
}
catch (IndexOutOfBoundsException e)
{
nextNode = null;
}
if (nextNode == null)
{
node = node.getParentNode();
if (node == null)
{
nextNode = node;
break;
}
}
}
node = nextNode;
}
}
protected void visitPre(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPre((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPre((Element) node);
break;
case Node.TEXT_NODE:
visitor.visitText((Text) node);
break;
// Not yet
case Node.ENTITY_REFERENCE_NODE:
System.out.println("ENTITY_REFERENCE_NODE");
default:
break;
}
}
protected void visitPost(Node node)
{
switch (node.getNodeType())
{
case Node.DOCUMENT_NODE:
visitor.visitDocumentPost((Document) node);
break;
case Node.ELEMENT_NODE:
visitor.visitElementPost((Element) node);
break;
case Node.TEXT_NODE:
break;
default:
break;
}
}
}
/*
* $Log: TreeWalker.java,v $
* Revision 1.5 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.4 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.3 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* This interface specifies the callbacks from the TreeWalker.
* $Id: Visitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
/**
* Callback methods from the TreeWalker.
*/
public interface Visitor
{
public void visitDocumentPre(Document document);
public void visitDocumentPost(Document document);
public void visitElementPre(Element element);
public void visitElementPost(Element element);
public void visitText(Text element);
}
/*
* $Log: Visitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.xml;
/**
* Implements a Visitor that does nothin'
* $Id: DefaultVisitor.java,v 1.4 2003/01/06 00:23:49 just Exp $
*
* @author $Author: just $ - Just van den Broecke - Just Objects B.V. ©
*/
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Text;
public class DefaultVisitor implements Visitor
{
public void visitDocumentPre(Document document)
{
}
public void visitDocumentPost(Document document)
{
}
public void visitElementPre(Element element)
{
}
public void visitElementPost(Element element)
{
}
public void visitText(Text element)
{
}
}
/*
* $Log: DefaultVisitor.java,v $
* Revision 1.4 2003/01/06 00:23:49 just
* moved devenv to linux
*
* Revision 1.3 2002/11/14 20:25:20 just
* reformat of code only
*
* Revision 1.2 2000/08/10 19:26:58 just
* changes for comments only
*
*
*/
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.logger;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.net.Uri;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;
import nl.sogeti.android.gpstracker.logger.IGPSLoggerServiceRemote;
import org.opentraces.metatracker.Constants;
/**
* Class to interact with the service that tracks and logs the locations
*
* @author rene (c) Jan 18, 2009, Sogeti B.V. adapted by Just van den Broecke
* @version $Id: GPSLoggerServiceManager.java 455 2010-03-14 08:16:44Z rcgroot $
*/
public class GPSLoggerServiceManager
{
private static final String TAG = "MT.GPSLoggerServiceManager";
private static final String REMOTE_EXCEPTION = "REMOTE_EXCEPTION";
private Context mCtx;
private IGPSLoggerServiceRemote mGPSLoggerRemote;
private final Object mStartLock = new Object();
private boolean mStarted = false;
/**
* Class for interacting with the main interface of the service.
*/
private ServiceConnection mServiceConnection = null;
public GPSLoggerServiceManager(Context ctx)
{
this.mCtx = ctx;
}
public boolean isStarted()
{
synchronized (mStartLock)
{
return mStarted;
}
}
public int getLoggingState()
{
synchronized (mStartLock)
{
int logging = Constants.UNKNOWN;
try
{
if (this.mGPSLoggerRemote != null)
{
logging = this.mGPSLoggerRemote.loggingState();
Log.d(TAG, "mGPSLoggerRemote tells state to be " + logging);
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return logging;
}
}
public boolean isMediaPrepared()
{
synchronized (mStartLock)
{
boolean prepared = false;
try
{
if (this.mGPSLoggerRemote != null)
{
prepared = this.mGPSLoggerRemote.isMediaPrepared();
} else
{
Log.w(TAG, "Remote interface to logging service not found. Started: " + mStarted);
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could stat GPSLoggerService.", e);
}
return prepared;
}
}
public long startGPSLogging(String name)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.startLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void pauseGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.pauseLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
}
}
public long resumeGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
return this.mGPSLoggerRemote.resumeLogging();
}
}
catch (RemoteException e)
{
Log.e(TAG, "Could not start GPSLoggerService.", e);
}
}
return -1;
}
}
public void stopGPSLogging()
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.stopLogging();
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not stop GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
public void storeMediaUri(Uri mediaUri)
{
synchronized (mStartLock)
{
if (mStarted)
{
try
{
if (this.mGPSLoggerRemote != null)
{
this.mGPSLoggerRemote.storeMediaUri(mediaUri);
}
}
catch (RemoteException e)
{
Log.e(GPSLoggerServiceManager.REMOTE_EXCEPTION, "Could not send media to GPSLoggerService.", e);
}
} else
{
Log.e(TAG, "No GPSLoggerRemote service connected to this manager");
}
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void startup(final ServiceConnection observer)
{
Log.d(TAG, "connectToGPSLoggerService()");
if (!mStarted)
{
this.mServiceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
synchronized (mStartLock)
{
Log.d(TAG, "onServiceConnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = IGPSLoggerServiceRemote.Stub.asInterface(service);
mStarted = true;
if (observer != null)
{
observer.onServiceConnected(className, service);
}
}
}
public void onServiceDisconnected(ComponentName className)
{
synchronized (mStartLock)
{
Log.e(TAG, "onServiceDisconnected()");
GPSLoggerServiceManager.this.mGPSLoggerRemote = null;
mStarted = false;
if (observer != null)
{
observer.onServiceDisconnected(className);
}
}
}
};
this.mCtx.bindService(new Intent(Constants.SERVICE_GPS_LOGGING), this.mServiceConnection, Context.BIND_AUTO_CREATE);
} else
{
Log.w(TAG, "Attempting to connect whilst connected");
}
}
/**
* Means by which an Activity lifecycle aware object hints about binding and unbinding
*/
public void shutdown()
{
Log.d(TAG, "disconnectFromGPSLoggerService()");
try
{
this.mCtx.unbindService(this.mServiceConnection);
}
catch (IllegalArgumentException e)
{
Log.e(TAG, "Failed to unbind a service, prehaps the service disapeared?", e);
}
}
} | Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
/**
* Constants and utilities for the KW protocol.
*
* @author $Author: $
* @version $Id: Protocol.java,v 1.2 2005/07/22 22:25:20 just Exp $
*/
public class Protocol
{
/**
* AMUSE Protocol version.
*/
public static final String PROTOCOL_VERSION = "4.0";
/**
* Postfixes
*/
public static final String POSTFIX_REQ = "-req";
public static final String POSTFIX_RSP = "-rsp";
public static final String POSTFIX_NRSP = "-nrsp";
public static final String POSTFIX_IND = "-ind";
/**
* Service id's
*/
public static final String SERVICE_SESSION_CREATE = "ses-create";
public static final String SERVICE_LOGIN = "ses-login";
public static final String SERVICE_LOGOUT = "ses-logout";
public static final String SERVICE_SESSION_PING = "ses-ping";
public static final String SERVICE_QUERY_STORE = "query-store";
public static final String SERVICE_MAP_AVAIL = "map-avail";
public static final String SERVICE_MULTI_REQ = "multi-req";
/**
* Common Attributes *
*/
public static final String ATTR_DEVID = "devid";
public static final String ATTR_USER = "user";
public static final String ATTR_AGENT = "agent";
public static final String ATTR_AGENTKEY = "agentkey";
public static final String ATTR_SECTIONS = "sections";
public static final String ATTR_ID = "id";
public static final String ATTR_CMD = "cmd";
public static final String ATTR_ERROR = "error";
public static final String ATTR_ERRORID = "errorId"; // yes id must be Id !!
public static final String ATTR_PASSWORD = "password";
public static final String ATTR_PROTOCOLVERSION = "protocolversion";
public static final String ATTR_STOPONERROR = "stoponerror";
public static final String ATTR_T = "t";
public static final String ATTR_TIME = "time";
public static final String ATTR_DETAILS = "details";
public static final String ATTR_NAME = "name";
/**
* Error ids returned in -nrsp as attribute ATTR_ERRORID
*/
public final static int
// 4000-4999 are "user-correctable" errors (user sends wrong input)
// 5000-5999 are server failures
ERR4004_ILLEGAL_COMMAND_FOR_STATE = 4003,
ERR4004_INVALID_ATTR_VALUE = 4004,
ERR4007_AGENT_LEASE_EXPIRED = 4007,
//_Portal/Application_error_codes_(4100-4199)
ERR4100_INVALID_USERNAME = 4100,
ERR4101_INVALID_PASSWORD = 4101,
ERR4102_MAX_LOGIN_ATTEMPTS_EXCEEDED = 4102,
//_General_Server_Error_Codes
ERR5000_INTERNAL_SERVER_ERROR = 5000;
/**
* Create login protocol request.
*/
public static Element createLoginRequest(String aName, String aPassword)
{
Element request = createRequest(SERVICE_LOGIN);
request.setAttribute(ATTR_NAME, aName);
request.setAttribute(ATTR_PASSWORD, aPassword);
request.setAttribute(ATTR_PROTOCOLVERSION, PROTOCOL_VERSION);
return request;
}
/**
* Create create-session protocol request.
*/
public static Element createSessionCreateRequest()
{
return createRequest(SERVICE_SESSION_CREATE);
}
/**
* Create a positive response element.
*/
public static Element createRequest(String aService)
{
Element element = null;
try
{
DocumentBuilderFactory dFact = DocumentBuilderFactory.newInstance();
DocumentBuilder build = dFact.newDocumentBuilder();
Document doc = build.newDocument();
element = doc.createElement(aService + POSTFIX_REQ);
doc.appendChild(element);
} catch (Throwable t)
{
}
return element;
}
/**
* Return service name for a message tag.
*
* @param aMessageTag
* @return
*/
public static String getServiceName(String aMessageTag)
{
try
{
return aMessageTag.substring(0, aMessageTag.lastIndexOf('-'));
}
catch (Throwable t)
{
throw new IllegalArgumentException("getServiceName: invalid tag: " + aMessageTag);
}
}
/**
* Is message a (negative) response..
*
* @param message
* @return
*/
public static boolean isResponse(Element message)
{
String tag = message.getTagName();
return tag.endsWith(POSTFIX_RSP) || tag.endsWith(POSTFIX_NRSP);
}
/**
* Is message a positive response..
*
* @param message
* @return
*/
public static boolean isPositiveResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_RSP);
}
/**
* Is message a negative response..
*
* @param message
* @return
*/
public static boolean isNegativeResponse(Element message)
{
return message.getTagName().endsWith(POSTFIX_NRSP);
}
public static boolean isPositiveServiceResponse(Element message, String service)
{
return isPositiveResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isNegativeServiceResponse(Element message, String service)
{
return isNegativeResponse(message) && service.equals(getServiceName(message.getTagName()));
}
public static boolean isService(Element message, String service)
{
return service.equals(getServiceName(message.getTagName()));
}
protected Protocol()
{
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
import android.util.Log;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.DefaultHttpClient;
import org.opentraces.metatracker.xml.DOMUtil;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Basic OpenTraces client using XML over HTTP.
* <p/>
* Use this class within Android HTTP clients.
*
* @author $Author: Just van den Broecke$
* @version $Revision: 3043 $ $Id: HTTPClient.java 3043 2009-01-17 16:25:21Z just $
* @see
*/
public class OpenTracesClient extends Protocol
{
private static final String LOG_TAG = "MT.OpenTracesClient";
/**
* Default KW session timeout (minutes).
*/
public static final int DEFAULT_TIMEOUT_MINS = 5;
/**
* Full KW protocol URL.
*/
private String protocolURL;
/**
* Debug flag for verbose output.
*/
private boolean debug;
/**
* Key gotten on login ack
*/
private String agentKey;
/**
* Keyworx session timeout (minutes).
*/
private int timeout;
/**
* Saved login request for session restore on timeout.
*/
private Element loginRequest;
/**
* Constructor with full protocol URL e.g. http://www.bla.com/proto.srv.
*/
public OpenTracesClient(String aProtocolURL)
{
this(aProtocolURL, DEFAULT_TIMEOUT_MINS);
}
/**
* Constructor with protocol URL and timeout.
*/
public OpenTracesClient(String aProtocolURL, int aTimeout)
{
protocolURL = aProtocolURL;
if (!protocolURL.endsWith("/proto.srv")) {
protocolURL += "/proto.srv";
}
timeout = aTimeout;
}
/**
* Create session.
*/
synchronized public Element createSession() throws ClientException
{
agentKey = null;
// Create XML request
Element request = createRequest(SERVICE_SESSION_CREATE);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
public String getAgentKey()
{
return agentKey;
}
public boolean hasSession()
{
return agentKey != null;
}
public boolean isLoggedIn()
{
return hasSession() && loginRequest != null;
}
/**
* Login on portal.
*/
synchronized public Element login(String aName, String aPassword) throws ClientException
{
// Create XML request
Element request = createLoginRequest(aName, aPassword);
// Execute request
Element response = doRequest(request);
// Filter session-related attrs
handleResponse(request, response);
throwOnNrsp(response);
// Returns positive response
return response;
}
/**
* Keep alive service.
*/
synchronized public Element ping() throws ClientException
{
return service(createRequest(SERVICE_SESSION_PING));
}
/**
* perform TWorx service request.
*/
synchronized public Element service(Element request) throws ClientException
{
throwOnInvalidSession();
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Positive response: return wrapped handler response
return response;
}
/**
* perform TWorx multi-service request.
*/
synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException
{
// We don't need a valid session as one of the requests
// may be a login or create-session request.
// Create multi-req request with individual requests as children
Element request = createRequest(SERVICE_MULTI_REQ);
request.setAttribute(ATTR_STOPONERROR, stopOnError + "");
for (Element req : requests)
{
request.appendChild(req);
}
// Execute request
Element response = doRequest(request);
// Check for session timeout
response = redoRequestOnSessionTimeout(request, response);
// Throw exception on negative response
throwOnNrsp(response);
// Filter child responses for session-based responses
NodeList responseList = response.getChildNodes();
List<Element> responses = new ArrayList(responseList.getLength());
for (int i = 0; i < responseList.getLength(); i++)
{
handleResponse(requests.get(i), (Element) responseList.item(i));
responses.add((Element) responseList.item(i));
}
// Positive multi-req response: return child responses
return responses;
}
/**
* Logout from portal.
*/
synchronized public Element logout() throws ClientException
{
throwOnInvalidSession();
// Create XML request
Element request = createRequest(SERVICE_LOGOUT);
// Execute request
Element response = doRequest(request);
handleResponse(request, response);
// Throw exception or return positive response
// throwOnNrsp(response);
return response;
}
/*
http://brainflush.wordpress.com/2008/10/17/talking-to-web-servers-via-http-in-android-10/
*/
public void uploadFile(String fileName)
{
try
{
DefaultHttpClient httpclient = new DefaultHttpClient();
File f = new File(fileName);
HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv");
MultipartEntity entity = new MultipartEntity();
entity.addPart("myIdentifier", new StringBody("somevalue"));
entity.addPart("myFile", new FileBody(f));
httpost.setEntity(entity);
HttpResponse response;
response = httpclient.execute(httpost);
Log.d(LOG_TAG, "Upload result: " + response.getStatusLine());
if (entity != null)
{
entity.consumeContent();
}
httpclient.getConnectionManager().shutdown();
} catch (Throwable ex)
{
Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace());
}
}
public void setDebug(boolean b)
{
debug = b;
}
/**
* Filter responses for session-related requests.
*/
private void handleResponse(Element request, Element response) throws ClientException
{
if (isNegativeResponse(response))
{
return;
}
String service = Protocol.getServiceName(request.getTagName());
if (service.equals(SERVICE_LOGIN))
{
// Save for later session restore
loginRequest = request;
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// if (response.hasAttribute(ATTR_TIME)) {
// DateTimeUtils.setTime(response.getLongAttr(ATTR_TIME));
// }
} else if (service.equals(SERVICE_SESSION_CREATE))
{
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
} else if (service.equals(SERVICE_LOGOUT))
{
loginRequest = null;
agentKey = null;
}
}
/**
* Throw exception on negative protocol response.
*/
private void throwOnNrsp(Element anElement) throws ClientException
{
if (isNegativeResponse(anElement))
{
String details = "no details";
if (anElement.hasAttribute(ATTR_DETAILS))
{
details = anElement.getAttribute(ATTR_DETAILS);
}
throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)),
anElement.getAttribute(ATTR_ERROR), details);
}
}
/**
* Throw exception when not logged in.
*/
private void throwOnInvalidSession() throws ClientException
{
if (agentKey == null)
{
throw new ClientException("Invalid tworx session");
}
}
/**
* .
*/
private Element redoRequestOnSessionTimeout(Element request, Element response) throws ClientException
{
// Check for session timeout
if (isNegativeResponse(response) && Integer.parseInt(response.getAttribute(ATTR_ERRORID)) == Protocol.ERR4007_AGENT_LEASE_EXPIRED)
{
p("Reestablishing session...");
// Reset session
agentKey = null;
// Do login if already logged in
if (loginRequest != null)
{
response = doRequest(loginRequest);
throwOnNrsp(response);
} else
{
response = createSession();
throwOnNrsp(response);
}
// Save session key
agentKey = response.getAttribute(ATTR_AGENTKEY);
// Re-issue service request and return new response
return doRequest(request);
}
// No session timeout so same response
return response;
}
/**
* Do XML over HTTP request and retun response.
*/
private Element doRequest(Element anElement) throws ClientException
{
// Create URL to use
String url = protocolURL;
if (agentKey != null)
{
url = url + "?agentkey=" + agentKey;
} else
{
// Must be login
url = url + "?timeout=" + timeout;
}
p("doRequest: " + url + " req=" + anElement.getTagName());
// Perform request/response
HttpClient httpclient = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(url);
Element replyElement = null;
try
{
// Make sure the server knows what kind of a response we will accept
httpPost.addHeader("Accept", "text/xml");
// Also be sure to tell the server what kind of content we are sending
httpPost.addHeader("Content-Type", "application/xml");
String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument());
StringEntity entity = new StringEntity(xmlString, "UTF-8");
entity.setContentType("application/xml");
httpPost.setEntity(entity);
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httpPost);
// Parse response
Document replyDoc = DOMUtil.parse(response.getEntity().getContent());
replyElement = replyDoc.getDocumentElement();
p("doRequest: rsp=" + replyElement.getTagName());
}
catch (Throwable t)
{
throw new ClientException("Error in doRequest: " + t);
}
finally
{
}
return replyElement;
}
/**
* Util: print.
*/
private void p(String s)
{
if (debug)
{
Log.d(LOG_TAG, s);
}
}
/**
* Util: warn.
*/
private void warn(String s)
{
warn(s, null);
}
/**
* Util: warn with exception.
*/
private void warn(String s, Throwable t)
{
Log.e(LOG_TAG, s + " ex=" + t, t);
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.net;
/**
* Generic exception wrapper. $Id: ClientException.java,v 1.2 2005/07/22 22:25:20 just Exp $
*
* @author $Author: Just van den Broecke$
* @version $Revision: $
*/
public class ClientException extends Exception
{
private int errorId;
String error;
protected ClientException()
{
}
public ClientException(String aMessage, Throwable t)
{
super(aMessage + "\n embedded exception=" + t.toString());
}
public ClientException(String aMessage)
{
super(aMessage);
}
public ClientException(int anErrorId, String anError, String someDetails)
{
super(someDetails);
errorId = anErrorId;
error = anError;
}
public ClientException(Throwable t)
{
this("ClientException: ", t);
}
public String toString()
{
return "ClientException: " + getMessage();
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker;
import android.net.Uri;
/**
* Various application wide constants
*
* @author Just van den Broecke
* @version $Id:$
*/
public class Constants
{
/**
* The authority of the track data provider
*/
public static final String AUTHORITY = "nl.sogeti.android.gpstracker";
/**
* The content:// style URL for the track data provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY);
/**
* Logging states, slightly adapted from GPSService states
*/
public static final int DOWN = 0;
public static final int LOGGING = 1;
public static final int PAUSED = 2;
public static final int STOPPED = 3;
public static final int UNKNOWN = 4;
public static String[] LOGGING_STATES = {"down", "logging", "paused", "stopped", "unknown"};
public static final String DISABLEBLANKING = "disableblanking";
public static final String PREF_ENABLE_SOUND = "pref_enablesound";
public static final String PREF_SERVER_URL = "pref_server_url";
public static final String PREF_SERVER_USER = "pref_server_user";
public static final String PREF_SERVER_PASSWORD = "pref_server_password";
public static final String SERVICE_GPS_LOGGING = "nl.sogeti.android.gpstracker.intent.action.GPSLoggerService";
public static final String EXTERNAL_DIR = "/OpenGPSTracker/";
public static final Uri NAME_URI = Uri.parse("content://" + AUTHORITY + ".string");
/**
* Activity Action: Pick a file through the file manager, or let user
* specify a custom file name.
* Data is the current file name or file name suggestion.
* Returns a new file name as file URI in data.
* <p/>
* <p>Constant Value: "org.openintents.action.PICK_FILE"</p>
*/
public static final String ACTION_PICK_FILE = "org.openintents.action.PICK_FILE";
public static final int REQUEST_CODE_PICK_FILE_OR_DIRECTORY = 1;
/**
* Activity Action: Show an about dialog to display
* information about the application.
* <p/>
* The application information is retrieved from the
* application's manifest. In order to send the package
* you have to launch this activity through
* startActivityForResult().
* <p/>
* Alternatively, you can specify the package name
* manually through the extra EXTRA_PACKAGE.
* <p/>
* All data can be replaced using optional intent extras.
* <p/>
* <p>
* Constant Value: "org.openintents.action.SHOW_ABOUT_DIALOG"
* </p>
*/
public static final String OI_ACTION_SHOW_ABOUT_DIALOG =
"org.openintents.action.SHOW_ABOUT_DIALOG";
/**
* Definitions for tracks.
*
*/
public static final class Tracks implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "tracks";
/**
* The end time
*/
public static final String NAME = "name";
public static final String CREATION_TIME = "creationtime";
/**
* The MIME type of a CONTENT_URI subdirectory of a single track.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.track";
/**
* The content:// style URL for this provider
*/
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for segments.
*/
public static final class Segments implements android.provider.BaseColumns
{
/**
* The name of this table
*/
static final String TABLE = "segments";
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
static final String TRACK_TYPE = "INTEGER NOT NULL";
static final String _ID_TYPE = "INTEGER PRIMARY KEY AUTOINCREMENT";
/**
* The MIME type of a CONTENT_URI subdirectory of a single segment.
*/
public static final String CONTENT_ITEM_TYPE = "vnd.android.cursor.item/vnd.nl.sogeti.android.segment";
/**
* The MIME type of CONTENT_URI providing a directory of segments.
*/
public static final String CONTENT_TYPE = "vnd.android.cursor.dir/vnd.nl.sogeti.android.segment";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for media URI's.
*
*/
public static final class Media implements android.provider.BaseColumns
{
/**
* The track _id to which this segment belongs
*/
public static final String TRACK = "track";
public static final String SEGMENT = "segment";
public static final String WAYPOINT = "waypoint";
public static final String URI = "uri";
/**
* The name of this table
*/
public static final String TABLE = "media";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
/**
* Definitions for waypoints.
*
*/
public static final class Waypoints implements android.provider.BaseColumns
{
/**
* The name of this table
*/
public static final String TABLE = "waypoints";
/**
* The latitude
*/
public static final String LATITUDE = "latitude";
/**
* The longitude
*/
public static final String LONGITUDE = "longitude";
/**
* The recorded time
*/
public static final String TIME = "time";
/**
* The speed in meters per second
*/
public static final String SPEED = "speed";
/**
* The segment _id to which this segment belongs
*/
public static final String SEGMENT = "tracksegment";
/**
* The accuracy of the fix
*/
public static final String ACCURACY = "accuracy";
/**
* The altitude
*/
public static final String ALTITUDE = "altitude";
/**
* the bearing of the fix
*/
public static final String BEARING = "bearing";
public static final Uri CONTENT_URI = Uri.parse("content://" + AUTHORITY + "/" + TABLE);
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.content.SharedPreferences;
import android.location.Location;
import org.opentraces.metatracker.Constants;
public class TrackingState
{
public int loggingState;
public boolean newRoadRating;
public int roadRating;
public float distance;
public Track track = new Track();
public Segment segment = new Segment();
public Waypoint waypoint = new Waypoint();
private SharedPreferences sharedPreferences;
public TrackingState(SharedPreferences sharedPreferences) {
this.sharedPreferences = sharedPreferences;
reset();
}
public void load()
{
distance = sharedPreferences.getFloat("distance", 0.0f);
track.load();
waypoint.load();
}
public void save()
{
sharedPreferences.edit().putFloat("distance", distance).commit();
track.save();
waypoint.save();
}
public void reset()
{
loggingState = Constants.DOWN;
distance = 0.0f;
waypoint.reset();
track.reset();
}
public class Track
{
public int id = -1;
public String name = "NO TRACK";
public long creationTime;
public void load()
{
id = sharedPreferences.getInt("track.id", -1);
name = sharedPreferences.getString("track.name", "NO TRACK");
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("track.id", id);
editor.putString("track.name", name);
editor.commit();
}
public void reset()
{
name = "NO TRACK";
id = -1;
}
}
public static class Segment
{
public int id = -1;
}
public class Waypoint
{
public int id = -1;
public Location location;
public float speed;
public float accuracy;
public int count;
public void load()
{
id = sharedPreferences.getInt("waypoint.id", -1);
count = sharedPreferences.getInt("waypoint.count", 0);
}
public void save()
{
SharedPreferences.Editor editor = sharedPreferences.edit();
editor.putInt("waypoint.id", id);
editor.putInt("waypoint.count", count);
editor.commit();
}
public void reset()
{
count = 0;
id = -1;
location = null;
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import org.opentraces.metatracker.R;
import android.os.Bundle;
import android.preference.PreferenceActivity;
/**
* Dialog for setting preferences.
*
* @author Just van den Broecke
*/
public class SettingsActivity extends PreferenceActivity
{
@Override
protected void onCreate( Bundle savedInstanceState )
{
super.onCreate( savedInstanceState );
addPreferencesFromResource( R.layout.settings );
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.ActivityNotFoundException;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.Constants;
import org.opentraces.metatracker.R;
import org.opentraces.metatracker.net.OpenTracesClient;
public class UploadTrackActivity extends Activity
{
protected static final int DIALOG_FILENAME = 11;
protected static final int PROGRESS_STEPS = 10;
private static final int DIALOG_INSTALL_FILEMANAGER = 34;
private static final String TAG = "MT.UploadTrack";
private String filePath;
private TextView fileNameView;
private SharedPreferences sharedPreferences;
private final DialogInterface.OnClickListener mFileManagerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.filemanager");
Intent oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiFileManagerDownloadIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/FileManager-1.1.3.apk");
oiFileManagerDownloadIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiFileManagerDownloadIntent);
}
}
};
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
setContentView(R.layout.uploaddialog);
fileNameView = (TextView) findViewById(R.id.filename);
filePath = null;
pickFile();
Button okay = (Button) findViewById(R.id.okayupload_button);
okay.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
if (filePath == null) {
return;
}
uploadFile(filePath);
}
});
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_FILEMANAGER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nofilemanager)
.setMessage(R.string.dialog_nofilemanager_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mFileManagerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent intent)
{
super.onActivityResult(requestCode, resultCode, intent);
// Bundle extras = intent.getExtras();
switch (requestCode)
{
case Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY:
if (resultCode == RESULT_OK && intent != null)
{
// obtain the filename
filePath = intent.getDataString();
if (filePath != null)
{
// Get rid of URI prefix:
if (filePath.startsWith("file://"))
{
filePath = filePath.substring(7);
}
fileNameView.setText(filePath);
}
}
break;
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void pickFile()
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
startActivityForResult(intent, Constants.REQUEST_CODE_PICK_FILE_OR_DIRECTORY);
} catch (ActivityNotFoundException e)
{
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_FILEMANAGER);
}
}
/*
http://edwards.sdsu.edu/labsite/index.php/josh/179-android-nuts-and-bolts-vii
http://code.google.com/p/openintents/source/browse/trunk/samples/TestFileManager/src/org/openintents/samples/TestFileManager/TestFileManager.java
*/
private void uploadFile(String aFilePath)
{
Intent intent = new Intent(Constants.ACTION_PICK_FILE);
intent.setData(Uri.parse("file://" + Environment.getExternalStorageDirectory() + Constants.EXTERNAL_DIR));
try
{
;
OpenTracesClient openTracesClient = new OpenTracesClient(sharedPreferences.getString(Constants.PREF_SERVER_URL, "http://geotracing.com/tland"));
openTracesClient.createSession();
openTracesClient.login(sharedPreferences.getString(Constants.PREF_SERVER_USER, "no_user"), sharedPreferences.getString(Constants.PREF_SERVER_PASSWORD, "no_passwd"));
openTracesClient.uploadFile(aFilePath);
openTracesClient.logout();
} catch (Throwable e)
{
Log.e(TAG, "Error uploading file : ", e);
}
}
}
| Java |
/*
* Copyright (C) 2010 Just Objects B.V.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.opentraces.metatracker.activity;
import android.app.*;
import android.content.*;
import android.database.ContentObserver;
import android.database.Cursor;
import android.location.Location;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.ContextMenu;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import org.opentraces.metatracker.*;
import org.opentraces.metatracker.logger.GPSLoggerServiceManager;
import java.text.DecimalFormat;
public class MainActivity extends Activity
{
// MENU'S
private static final int MENU_SETTINGS = 1;
private static final int MENU_TRACKING = 2;
private static final int MENU_UPLOAD = 3;
private static final int MENU_HELP = 4;
private static final int MENU_ABOUT = 5;
private static final int DIALOG_INSTALL_OPENGPSTRACKER = 1;
private static final int DIALOG_INSTALL_ABOUT = 2;
private static DecimalFormat REAL_FORMATTER1 = new DecimalFormat("0.#");
private static DecimalFormat REAL_FORMATTER2 = new DecimalFormat("0.##");
private static final String TAG = "MetaTracker.Main";
private TextView waypointCountView, timeView, distanceView, speedView, roadRatingView, accuracyView;
private GPSLoggerServiceManager loggerServiceManager;
private TrackingState trackingState;
private MediaPlayer mediaPlayer;
// private PowerManager.WakeLock wakeLock = null;
private static final int COLOR_WHITE = 0xFFFFFFFF;
private static final int[] ROAD_RATING_COLORS = {0xFF808080, 0xFFCC0099, 0xFFEE0000, 0xFFFF6600, 0xFFFFCC00, 0xFF33CC33};
private SharedPreferences sharedPreferences;
private Button[] roadRatingButtons = new Button[6];
/**
* Called when the activity is first created.
*/
@Override
public void onCreate(Bundle savedInstanceState)
{
Log.d(TAG, "onCreate()");
super.onCreate(savedInstanceState);
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
sharedPreferences.registerOnSharedPreferenceChangeListener(sharedPreferenceChangeListener);
trackingState = new TrackingState(sharedPreferences);
trackingState.load();
setContentView(R.layout.main);
getLastTrackingState();
getApplicationContext().getContentResolver().registerContentObserver(Constants.Tracks.CONTENT_URI, true, trackingObserver);
// mUnits = new UnitsI18n(this, mUnitsChangeListener);
speedView = (TextView) findViewById(R.id.currentSpeed);
timeView = (TextView) findViewById(R.id.currentTime);
distanceView = (TextView) findViewById(R.id.totalDist);
waypointCountView = (TextView) findViewById(R.id.waypointCount);
accuracyView = (TextView) findViewById(R.id.currentAccuracy);
roadRatingView = (TextView) findViewById(R.id.currentRoadRating);
// Capture our button from layout
roadRatingButtons[0] = (Button) findViewById(R.id.road_qual_none);
roadRatingButtons[1] = (Button) findViewById(R.id.road_qual_nogo);
roadRatingButtons[2] = (Button) findViewById(R.id.road_qual_bad);
roadRatingButtons[3] = (Button) findViewById(R.id.road_qual_poor);
roadRatingButtons[4] = (Button) findViewById(R.id.road_qual_good);
roadRatingButtons[5] = (Button) findViewById(R.id.road_qual_best);
for (Button button : roadRatingButtons)
{
button.setOnClickListener(roadRatingButtonListener);
}
bindGPSLoggingService();
}
/**
* Called when the activity is started.
*/
@Override
public void onStart()
{
Log.d(TAG, "onStart()");
super.onStart();
}
/**
* Called when the activity is started.
*/
@Override
public void onRestart()
{
Log.d(TAG, "onRestart()");
super.onRestart();
}
/**
* Called when the activity is resumed.
*/
@Override
public void onResume()
{
Log.d(TAG, "onResume()");
getLastTrackingState();
// updateBlankingBehavior();
drawScreen();
super.onResume();
}
/**
* Called when the activity is paused.
*/
@Override
public void onPause()
{
trackingState.save();
/* if (this.wakeLock != null && this.wakeLock.isHeld())
{
this.wakeLock.release();
Log.w(TAG, "onPause(): Released lock to keep screen on!");
} */
Log.d(TAG, "onPause()");
super.onPause();
}
@Override
protected void onDestroy()
{
Log.d(TAG, "onDestroy()");
trackingState.save();
/* if (wakeLock != null && wakeLock.isHeld())
{
wakeLock.release();
Log.w(TAG, "onDestroy(): Released lock to keep screen on!");
} */
getApplicationContext().getContentResolver().unregisterContentObserver(trackingObserver);
sharedPreferences.unregisterOnSharedPreferenceChangeListener(this.sharedPreferenceChangeListener);
unbindGPSLoggingService();
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu)
{
boolean result = super.onCreateOptionsMenu(menu);
menu.add(ContextMenu.NONE, MENU_TRACKING, ContextMenu.NONE, R.string.menu_tracking).setIcon(R.drawable.ic_menu_movie).setAlphabeticShortcut('T');
menu.add(ContextMenu.NONE, MENU_UPLOAD, ContextMenu.NONE, R.string.menu_upload).setIcon(R.drawable.ic_menu_upload).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_SETTINGS, ContextMenu.NONE, R.string.menu_settings).setIcon(R.drawable.ic_menu_preferences).setAlphabeticShortcut('C');
menu.add(ContextMenu.NONE, MENU_HELP, ContextMenu.NONE, R.string.menu_help).setIcon(R.drawable.ic_menu_help).setAlphabeticShortcut('I');
menu.add(ContextMenu.NONE, MENU_ABOUT, ContextMenu.NONE, R.string.menu_about).setIcon(R.drawable.ic_menu_info_details).setAlphabeticShortcut('A');
return result;
}
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
switch (item.getItemId())
{
case MENU_TRACKING:
startOpenGPSTrackerActivity();
break;
case MENU_UPLOAD:
startActivityForClass("org.opentraces.metatracker", "org.opentraces.metatracker.activity.UploadTrackActivity");
break;
case MENU_SETTINGS:
startActivity(new Intent(this, SettingsActivity.class));
break;
case MENU_ABOUT:
try
{
startActivityForResult(new Intent(Constants.OI_ACTION_SHOW_ABOUT_DIALOG), MENU_ABOUT);
}
catch (ActivityNotFoundException e)
{
showDialog(DIALOG_INSTALL_ABOUT);
}
break;
default:
showAlert(R.string.menu_message_unsupported);
break;
}
return true;
}
/*
* (non-Javadoc)
* @see android.app.Activity#onCreateDialog(int)
*/
@Override
protected Dialog onCreateDialog(int id)
{
Dialog dialog = null;
AlertDialog.Builder builder = null;
switch (id)
{
case DIALOG_INSTALL_OPENGPSTRACKER:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_noopengpstracker)
.setMessage(R.string.dialog_noopengpstracker_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOpenGPSTrackerDownloadDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
break;
case DIALOG_INSTALL_ABOUT:
builder = new AlertDialog.Builder(this);
builder
.setTitle(R.string.dialog_nooiabout)
.setMessage(R.string.dialog_nooiabout_message)
.setIcon(android.R.drawable.ic_dialog_alert)
.setPositiveButton(R.string.btn_install, mOiAboutDialogListener)
.setNegativeButton(R.string.btn_cancel, null);
dialog = builder.create();
return dialog;
default:
dialog = super.onCreateDialog(id);
break;
}
return dialog;
}
private void drawTitleBar(String s)
{
this.setTitle(s);
}
/**
* Called on any update to Tracks table.
*/
private void onTrackingUpdate()
{
getLastTrackingState();
if (trackingState.waypoint.count == 1)
{
sendRoadRating();
}
drawScreen();
}
/**
* Called on any update to Tracks table.
*/
private synchronized void playPingSound()
{
if (!sharedPreferences.getBoolean(Constants.PREF_ENABLE_SOUND, false)) {
return;
}
try
{
if (mediaPlayer == null)
{
mediaPlayer = MediaPlayer.create(this, R.raw.ping_short);
} else
{
mediaPlayer.stop();
mediaPlayer.prepare();
}
mediaPlayer.start();
} catch (Throwable t)
{
Log.e(TAG, "Error playing sound", t);
}
}
/**
* Retrieve the last point of the current track
*/
private void getLastWaypoint()
{
Cursor waypoint = null;
try
{
ContentResolver resolver = this.getContentResolver();
waypoint = resolver.query(Uri.withAppendedPath(Constants.Tracks.CONTENT_URI, trackingState.track.id + "/" + Constants.Waypoints.TABLE),
new String[]{"max(" + Constants.Waypoints.TABLE + "." + Constants.Waypoints._ID + ")", Constants.Waypoints.LONGITUDE, Constants.Waypoints.LATITUDE, Constants.Waypoints.SPEED, Constants.Waypoints.ACCURACY, Constants.Waypoints.SEGMENT
}, null, null, null);
if (waypoint != null && waypoint.moveToLast())
{
// New point: increase pointcount
int waypointId = waypoint.getInt(0);
if (waypointId > 0 && trackingState.waypoint.id != waypointId)
{
trackingState.waypoint.count++;
trackingState.waypoint.id = waypoint.getInt(0);
// Increase total distance
Location newLocation = new Location(this.getClass().getName());
newLocation.setLongitude(waypoint.getDouble(1));
newLocation.setLatitude(waypoint.getDouble(2));
if (trackingState.waypoint.location != null)
{
float delta = trackingState.waypoint.location.distanceTo(newLocation);
// Log.d(TAG, "trackingState.distance=" + trackingState.distance + " delta=" + delta + " ll=" + waypoint.getDouble(1) + ", " +waypoint.getDouble(2));
trackingState.distance += delta;
}
trackingState.waypoint.location = newLocation;
trackingState.waypoint.speed = waypoint.getFloat(3);
trackingState.waypoint.accuracy = waypoint.getFloat(4);
trackingState.segment.id = waypoint.getInt(5);
playPingSound();
}
}
}
finally
{
if (waypoint != null)
{
waypoint.close();
}
}
}
private void getLastTrack()
{
Cursor cursor = null;
try
{
ContentResolver resolver = this.getApplicationContext().getContentResolver();
cursor = resolver.query(Constants.Tracks.CONTENT_URI, new String[]{"max(" + Constants.Tracks._ID + ")", Constants.Tracks.NAME, Constants.Tracks.CREATION_TIME}, null, null, null);
if (cursor != null && cursor.moveToLast())
{
int trackId = cursor.getInt(0);
// Check if new track created
if (trackId != trackingState.track.id)
{
trackingState.reset();
trackingState.save();
}
trackingState.track.id = trackId;
trackingState.track.name = cursor.getString(1);
trackingState.track.creationTime = cursor.getLong(2);
}
}
finally
{
if (cursor != null)
{
cursor.close();
}
}
}
private void getLastTrackingState()
{
getLastTrack();
getLoggingState();
getLastWaypoint();
}
private void sendRoadRating()
{
if (trackingState.roadRating > 0 && trackingState.newRoadRating && loggerServiceManager != null)
{
Uri media = Uri.withAppendedPath(Constants.NAME_URI, Uri.encode(trackingState.roadRating + ""));
loggerServiceManager.storeMediaUri(media);
trackingState.newRoadRating = false;
}
}
private void startOpenGPSTrackerActivity()
{
try
{
startActivityForClass("nl.sogeti.android.gpstracker", "nl.sogeti.android.gpstracker.viewer.LoggerMap");
}
catch (ActivityNotFoundException e)
{
Log.i(TAG, "Cannot find activity for open-gpstracker");
// No compatible file manager was found: install openintents filemanager.
showDialog(DIALOG_INSTALL_OPENGPSTRACKER);
}
sendRoadRating();
}
private void startActivityForClass(String aPackageName, String aClassName) throws ActivityNotFoundException
{
Intent intent = new Intent();
intent.setClassName(aPackageName, aClassName);
startActivity(intent);
}
private void bindGPSLoggingService()
{
unbindGPSLoggingService();
ServiceConnection serviceConnection = new ServiceConnection()
{
public void onServiceConnected(ComponentName className, IBinder service)
{
getLoggingState();
drawTitleBar();
}
public void onServiceDisconnected(ComponentName className)
{
trackingState.loggingState = Constants.DOWN;
}
};
loggerServiceManager = new GPSLoggerServiceManager(this);
loggerServiceManager.startup(serviceConnection);
}
private void unbindGPSLoggingService()
{
if (loggerServiceManager == null)
{
return;
}
try
{
loggerServiceManager.shutdown();
} finally
{
loggerServiceManager = null;
trackingState.loggingState = Constants.DOWN;
}
}
private void getLoggingState()
{
// Get state from logger if bound
trackingState.loggingState = loggerServiceManager == null ? Constants.DOWN : loggerServiceManager.getLoggingState();
// protect for values outside array bounds (set to unknown)
if (trackingState.loggingState < 0 || trackingState.loggingState > Constants.LOGGING_STATES.length - 1)
{
trackingState.loggingState = Constants.UNKNOWN;
}
}
private String getLoggingStateStr()
{
return Constants.LOGGING_STATES[trackingState.loggingState];
}
private void drawTitleBar()
{
drawTitleBar("MT : " + trackingState.track.name + " : " + getLoggingStateStr());
}
private void drawScreen()
{
drawTitleBar();
drawTripStats();
drawRoadRating();
}
/**
* Retrieves the numbers of the measured speed and altitude
* from the most recent waypoint and
* updates UI components with this latest bit of information.
*/
private void drawTripStats()
{
try
{
waypointCountView.setText(trackingState.waypoint.count + "");
long secsDelta = 0L;
long hours = 0L;
long mins = 0L;
long secs = 0L;
if (trackingState.track.creationTime != 0)
{
secsDelta = (System.currentTimeMillis() - trackingState.track.creationTime) / 1000;
hours = secsDelta / 3600L;
mins = (secsDelta % 3600L) / 60L;
secs = ((secsDelta % 3600L) % 60);
}
timeView.setText(formatTimeNum(hours) + ":" + formatTimeNum(mins) + ":" + formatTimeNum(secs));
speedView.setText(REAL_FORMATTER1.format(3.6f * trackingState.waypoint.speed));
accuracyView.setText(REAL_FORMATTER1.format(trackingState.waypoint.accuracy));
distanceView.setText(REAL_FORMATTER2.format(trackingState.distance / 1000f));
}
finally
{
}
}
private String formatTimeNum(long n)
{
return n < 10 ? ("0" + n) : (n + "");
}
private void drawRoadRating()
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
roadRatingButtons[i].setBackgroundColor(COLOR_WHITE);
}
if (trackingState.roadRating >= 0)
{
roadRatingButtons[trackingState.roadRating].setBackgroundColor(ROAD_RATING_COLORS[trackingState.roadRating]);
}
String roadRatingStr = trackingState.roadRating + "";
roadRatingView.setText(roadRatingStr);
}
private void showAlert(int aMessage)
{
new AlertDialog.Builder(this)
.setMessage(aMessage)
.setPositiveButton("Ok", null)
.show();
}
private void updateBlankingBehavior()
{
boolean disableblanking = sharedPreferences.getBoolean(Constants.DISABLEBLANKING, false);
if (disableblanking)
{
/* if (wakeLock == null)
{
PowerManager pm = (PowerManager) this.getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, TAG);
}
wakeLock.acquire();
Log.w(TAG, "Acquired lock to keep screen on!"); */
}
}
private final DialogInterface.OnClickListener mOiAboutDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri oiDownload = Uri.parse("market://details?id=org.openintents.about");
Intent oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
try
{
startActivity(oiAboutIntent);
}
catch (ActivityNotFoundException e)
{
oiDownload = Uri.parse("http://openintents.googlecode.com/files/AboutApp-1.0.0.apk");
oiAboutIntent = new Intent(Intent.ACTION_VIEW, oiDownload);
startActivity(oiAboutIntent);
}
}
};
private final DialogInterface.OnClickListener mOpenGPSTrackerDownloadDialogListener = new DialogInterface.OnClickListener()
{
public void onClick(DialogInterface dialog, int which)
{
Uri marketUri = Uri.parse("market://details?id=nl.sogeti.android.gpstracker");
Intent downloadIntent = new Intent(Intent.ACTION_VIEW, marketUri);
try
{
startActivity(downloadIntent);
}
catch (ActivityNotFoundException e)
{
showAlert(R.string.dialog_failinstallopengpstracker_message);
}
}
};
// Create an anonymous implementation of OnClickListener
private View.OnClickListener roadRatingButtonListener = new View.OnClickListener()
{
public void onClick(View v)
{
for (int i = 0; i < roadRatingButtons.length; i++)
{
if (v.getId() == roadRatingButtons[i].getId())
{
trackingState.roadRating = i;
}
}
trackingState.newRoadRating = true;
drawRoadRating();
sendRoadRating();
}
};
private final ContentObserver trackingObserver = new ContentObserver(new Handler())
{
@Override
public void onChange(boolean selfUpdate)
{
if (!selfUpdate)
{
onTrackingUpdate();
Log.d(TAG, "trackingObserver onTrackingUpdate lastWaypointId=" + trackingState.waypoint.id);
} else
{
Log.w(TAG, "trackingObserver skipping change");
}
}
};
private final SharedPreferences.OnSharedPreferenceChangeListener sharedPreferenceChangeListener = new SharedPreferences.OnSharedPreferenceChangeListener()
{
public void onSharedPreferenceChanged(SharedPreferences sharedPreferences, String key)
{
if (key.equals(Constants.DISABLEBLANKING))
{
updateBlankingBehavior();
}
}
};
}
| Java |
package SerovaGS;
import robocode.*;
import java.awt.Color;
import java.util.Random;
/**
* Anku - a robot by (your name here)
*/
public class Anku extends AdvancedRobot
{
private Random rnd = new Random();
private double moveDist = 100000;
/**
* run: Anku's default behavior
*/
public void run() {
setColors(Color.red,Color.blue,Color.green);
while(true) {
setTurnRadarRight(360000);
setAhead(moveDist);
setTurnRight(getRandomAngle());
waitFor(new TurnCompleteCondition(this));
setAhead(getRandomDist());
waitFor(new MoveCompleteCondition(this));
}
}
/**
* onScannedRobot: What to do when you see another robot
*/
public void onScannedRobot(ScannedRobotEvent e) {
double angleToTarget = getHeading() + e.getBearing();
turnGunRight(angleToTarget-getGunHeading());
fire(3);
turnRadarRight(angleToTarget-getRadarHeading());
scan();
}
public void onHitWall(HitWallEvent e) {
reverse();
turnLeft(getHeading()%90);
}
/**
* onHitByBullet: What to do when you're hit by a bullet
*/
public void onHitByBullet(HitByBulletEvent e) {
turnLeft(90 - e.getBearing());
}
public int getRandomAngle() {
return rnd.nextInt()%200;
}
public int getRandomDist() {
return rnd.nextInt()%300;
}
public void reverse() {
moveDist *= -1;
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author XuanHung
*/
public class CipherInputStream
{
BlockCipher currentCipher;
InputStream bi;
byte[] buffer;
byte[] enc;
int blockSize;
int pos;
/*
* We cannot use java.io.BufferedInputStream, since that is not available in
* J2ME. Everything could be improved alot here.
*/
final int BUFF_SIZE = 2048;
byte[] input_buffer = new byte[BUFF_SIZE];
int input_buffer_pos = 0;
int input_buffer_size = 0;
public CipherInputStream(BlockCipher tc, InputStream bi)
{
this.bi = bi;
changeCipher(tc);
}
private int fill_buffer() throws IOException
{
input_buffer_pos = 0;
input_buffer_size = bi.read(input_buffer, 0, BUFF_SIZE);
return input_buffer_size;
}
private int internal_read(byte[] b, int off, int len) throws IOException
{
if (input_buffer_size < 0)
return -1;
if (input_buffer_pos >= input_buffer_size)
{
if (fill_buffer() <= 0)
return -1;
}
int avail = input_buffer_size - input_buffer_pos;
int thiscopy = (len > avail) ? avail : len;
System.arraycopy(input_buffer, input_buffer_pos, b, off, thiscopy);
input_buffer_pos += thiscopy;
return thiscopy;
}
public void changeCipher(BlockCipher bc)
{
this.currentCipher = bc;
blockSize = bc.getBlockSize();
buffer = new byte[blockSize];
enc = new byte[blockSize];
pos = blockSize;
}
private void getBlock() throws IOException
{
int n = 0;
while (n < blockSize)
{
int len = internal_read(enc, n, blockSize - n);
if (len < 0)
throw new IOException("Cannot read full block, EOF reached.");
n += len;
}
try
{
currentCipher.transformBlock(enc, 0, buffer, 0);
}
catch (Exception e)
{
throw new IOException("Error while decrypting block.");
}
pos = 0;
}
public int read(byte[] dst) throws IOException
{
return read(dst, 0, dst.length);
}
public int read(byte[] dst, int off, int len) throws IOException
{
int count = 0;
while (len > 0)
{
if (pos >= blockSize)
getBlock();
int avail = blockSize - pos;
int copy = Math.min(avail, len);
System.arraycopy(buffer, pos, dst, off, copy);
pos += copy;
off += copy;
len -= copy;
count += copy;
}
return count;
}
public int read() throws IOException
{
if (pos >= blockSize)
{
getBlock();
}
return buffer[pos++] & 0xff;
}
public int readPlain(byte[] b, int off, int len) throws IOException
{
if (pos != blockSize)
throw new IOException("Cannot read plain since crypto buffer is not aligned.");
int n = 0;
while (n < len)
{
int cnt = internal_read(b, off + n, len - n);
if (cnt < 0)
throw new IOException("Cannot fill buffer, EOF reached.");
n += cnt;
}
return n;
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class CBCMode implements BlockCipher
{
BlockCipher tc;
int blockSize;
boolean doEncrypt;
byte[] cbc_vector;
byte[] tmp_vector;
@Override
public void init(boolean forEncryption, byte[] key)
{
}
public CBCMode(BlockCipher tc, byte[] iv, boolean doEncrypt)
throws IllegalArgumentException
{
this.tc = tc;
this.blockSize = tc.getBlockSize();
this.doEncrypt = doEncrypt;
if (this.blockSize != iv.length)
throw new IllegalArgumentException("IV must be " + blockSize
+ " bytes long! (currently " + iv.length + ")");
this.cbc_vector = new byte[blockSize];
this.tmp_vector = new byte[blockSize];
System.arraycopy(iv, 0, cbc_vector, 0, blockSize);
}
@Override
public int getBlockSize()
{
return blockSize;
}
private void encryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
for (int i = 0; i < blockSize; i++)
cbc_vector[i] ^= src[srcoff + i];
tc.transformBlock(cbc_vector, 0, dst, dstoff);
System.arraycopy(dst, dstoff, cbc_vector, 0, blockSize);
}
private void decryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
/* Assume the worst, src and dst are overlapping... */
System.arraycopy(src, srcoff, tmp_vector, 0, blockSize);
tc.transformBlock(src, srcoff, dst, dstoff);
for (int i = 0; i < blockSize; i++)
dst[dstoff + i] ^= cbc_vector[i];
/* ...that is why we need a tmp buffer. */
byte[] swap = cbc_vector;
cbc_vector = tmp_vector;
tmp_vector = swap;
}
/**
*
* @param src
* @param srcoff
* @param dst
* @param dstoff
*/
@Override
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
if (doEncrypt)
encryptBlock(src, srcoff, dst, dstoff);
else
decryptBlock(src, srcoff, dst, dstoff);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class DES implements BlockCipher
{
private int[] workingKey = null;
/**
* standard constructor.
*/
public DES()
{
}
/**
* initialise a DES cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the parameters required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
@Override
public void init(boolean encrypting, byte[] key)
{
this.workingKey = generateWorkingKey(encrypting, key, 0);
}
public String getAlgorithmName()
{
return "DES";
}
@Override
public int getBlockSize()
{
return 8;
}
@Override
public void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (workingKey == null)
{
throw new IllegalStateException("DES engine not initialised!");
}
desFunc(workingKey, in, inOff, out, outOff);
}
public void reset()
{
}
/**
* what follows is mainly taken from "Applied Cryptography", by Bruce
* Schneier, however it also bears great resemblance to Richard
* Outerbridge's D3DES...
*/
static short[] Df_Key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32,
0x10, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67 };
static short[] bytebit = { 0200, 0100, 040, 020, 010, 04, 02, 01 };
static int[] bigbyte = { 0x800000, 0x400000, 0x200000, 0x100000, 0x80000, 0x40000, 0x20000, 0x10000, 0x8000,
0x4000, 0x2000, 0x1000, 0x800, 0x400, 0x200, 0x100, 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 };
/*
* Use the key schedule specified in the Standard (ANSI X3.92-1981).
*/
static byte[] pc1 = { 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12,
4, 27, 19, 11, 3 };
static byte[] totrot = { 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28 };
static byte[] pc2 = { 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40,
51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 };
static int[] SP1 = { 0x01010400, 0x00000000, 0x00010000, 0x01010404, 0x01010004, 0x00010404, 0x00000004,
0x00010000, 0x00000400, 0x01010400, 0x01010404, 0x00000400, 0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400, 0x00010400, 0x01010000, 0x01010000, 0x01000404, 0x00010004,
0x01000004, 0x01000004, 0x00010004, 0x00000000, 0x00000404, 0x00010404, 0x01000000, 0x00010000, 0x01010404,
0x00000004, 0x01010000, 0x01010400, 0x01000000, 0x01000000, 0x00000400, 0x01010004, 0x00010000, 0x00010400,
0x01000004, 0x00000400, 0x00000004, 0x01000404, 0x00010404, 0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400, 0x00000404, 0x01000400, 0x01000400, 0x00000000, 0x00010004,
0x00010400, 0x00000000, 0x01010004 };
static int[] SP2 = { 0x80108020, 0x80008000, 0x00008000, 0x00108020, 0x00100000, 0x00000020, 0x80100020,
0x80008020, 0x80000020, 0x80108020, 0x80108000, 0x80000000, 0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000, 0x80000000, 0x00008000, 0x00108020, 0x80100000, 0x00100020,
0x80000020, 0x00000000, 0x00108000, 0x00008020, 0x80108000, 0x80100000, 0x00008020, 0x00000000, 0x00108020,
0x80100020, 0x00100000, 0x80008020, 0x80100000, 0x80108000, 0x00008000, 0x80100000, 0x80008000, 0x00000020,
0x80108020, 0x00108020, 0x00000020, 0x00008000, 0x80000000, 0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020, 0x00108000, 0x00000000, 0x80008000, 0x00008020, 0x80000000,
0x80100020, 0x80108020, 0x00108000 };
static int[] SP3 = { 0x00000208, 0x08020200, 0x00000000, 0x08020008, 0x08000200, 0x00000000, 0x00020208,
0x08000200, 0x00020008, 0x08000008, 0x08000008, 0x00020000, 0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200, 0x00020200, 0x08020000, 0x08020008, 0x00020208, 0x08000208,
0x00020200, 0x00020000, 0x08000208, 0x00000008, 0x08020208, 0x00000200, 0x08000000, 0x08020200, 0x08000000,
0x00020008, 0x00000208, 0x00020000, 0x08020200, 0x08000200, 0x00000000, 0x00000200, 0x00020008, 0x08020208,
0x08000200, 0x08000008, 0x00000200, 0x00000000, 0x08020008, 0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008, 0x08020000, 0x08000208, 0x00000208, 0x08020000, 0x00020208,
0x00000008, 0x08020008, 0x00020200 };
static int[] SP4 = { 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802080, 0x00800081, 0x00800001,
0x00002001, 0x00000000, 0x00802000, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002001, 0x00002080, 0x00800081,
0x00000001, 0x00002080, 0x00800080, 0x00002000, 0x00802080, 0x00802081, 0x00000081, 0x00800080, 0x00800001,
0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00000000, 0x00802000, 0x00002080, 0x00800080, 0x00800081,
0x00000001, 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081, 0x00002001, 0x00002080, 0x00800000, 0x00802001, 0x00000080,
0x00800000, 0x00002000, 0x00802080 };
static int[] SP5 = { 0x00000100, 0x02080100, 0x02080000, 0x42000100, 0x00080000, 0x00000100, 0x40000000,
0x02080000, 0x40080100, 0x00080000, 0x02000100, 0x40080100, 0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000, 0x40000100, 0x42080100, 0x42080100, 0x02000100, 0x42080000,
0x40000100, 0x00000000, 0x42000000, 0x02080100, 0x02000000, 0x42000000, 0x00080100, 0x00080000, 0x42000100,
0x00000100, 0x02000000, 0x40000000, 0x02080000, 0x42000100, 0x40080100, 0x02000100, 0x40000000, 0x42080000,
0x02080100, 0x40080100, 0x00000100, 0x02000000, 0x42080000, 0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000, 0x00080100, 0x02000100, 0x40000100, 0x00080000, 0x00000000,
0x40080000, 0x02080100, 0x40000100 };
static int[] SP6 = { 0x20000010, 0x20400000, 0x00004000, 0x20404010, 0x20400000, 0x00000010, 0x20404010,
0x00400000, 0x20004000, 0x00404010, 0x00400000, 0x20000010, 0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000, 0x00404000, 0x20004010, 0x00000010, 0x20400010, 0x20400010,
0x00000000, 0x00404010, 0x20404000, 0x00004010, 0x00404000, 0x20404000, 0x20000000, 0x20004000, 0x00000010,
0x20400010, 0x00404000, 0x20404010, 0x00400000, 0x00004010, 0x20000010, 0x00400000, 0x20004000, 0x20000000,
0x00004010, 0x20000010, 0x20404010, 0x00404000, 0x20400000, 0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010, 0x00004000, 0x00400010, 0x20004010, 0x00000000, 0x20404000,
0x20000000, 0x00400010, 0x20004010 };
static int[] SP7 = { 0x00200000, 0x04200002, 0x04000802, 0x00000000, 0x00000800, 0x04000802, 0x00200802,
0x04200800, 0x04200802, 0x00200000, 0x00000000, 0x04000002, 0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800, 0x04000002, 0x04200000, 0x04200800, 0x00200002, 0x04200000,
0x00000800, 0x00000802, 0x04200802, 0x00200800, 0x00000002, 0x04000000, 0x00200800, 0x04000000, 0x00200800,
0x00200000, 0x04000802, 0x04000802, 0x04200002, 0x04200002, 0x00000002, 0x00200002, 0x04000000, 0x04000800,
0x00200000, 0x04200800, 0x00000802, 0x00200802, 0x04200800, 0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802, 0x00000000, 0x00200802, 0x04200000, 0x00000800, 0x04000002,
0x04000800, 0x00000800, 0x00200002 };
static int[] SP8 = { 0x10001040, 0x00001000, 0x00040000, 0x10041040, 0x10000000, 0x10001040, 0x00000040,
0x10000000, 0x00040040, 0x10040000, 0x10041040, 0x00041000, 0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040, 0x00041000, 0x00040040, 0x10040040, 0x10041000, 0x00001040,
0x00000000, 0x00000000, 0x10040040, 0x10000040, 0x10001000, 0x00041040, 0x00040000, 0x00041040, 0x00040000,
0x10041000, 0x00001000, 0x00000040, 0x10040040, 0x00001000, 0x00041040, 0x10001000, 0x00000040, 0x10000040,
0x10040000, 0x10040040, 0x10000000, 0x00040000, 0x10001040, 0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000, 0x10041040, 0x00041000, 0x00041000, 0x00001040, 0x00001040,
0x00040040, 0x10000000, 0x10041000 };
/**
* generate an integer based working key based on our secret key and what we
* processing we are planning to do.
*
* Acknowledgements for this routine go to James Gillogly & Phil Karn.
* (whoever, and wherever they are!).
*/
protected int[] generateWorkingKey(boolean encrypting, byte[] key, int off)
{
int[] newKey = new int[32];
boolean[] pc1m = new boolean[56], pcr = new boolean[56];
for (int j = 0; j < 56; j++)
{
int l = pc1[j];
pc1m[j] = ((key[off + (l >>> 3)] & bytebit[l & 07]) != 0);
}
for (int i = 0; i < 16; i++)
{
int l, m, n;
if (encrypting)
{
m = i << 1;
}
else
{
m = (15 - i) << 1;
}
n = m + 1;
newKey[m] = newKey[n] = 0;
for (int j = 0; j < 28; j++)
{
l = j + totrot[i];
if (l < 28)
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 28; j < 56; j++)
{
l = j + totrot[i];
if (l < 56)
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 0; j < 24; j++)
{
if (pcr[pc2[j]])
{
newKey[m] |= bigbyte[j];
}
if (pcr[pc2[j + 24]])
{
newKey[n] |= bigbyte[j];
}
}
}
//
// store the processed key
//
for (int i = 0; i != 32; i += 2)
{
int i1, i2;
i1 = newKey[i];
i2 = newKey[i + 1];
newKey[i] = ((i1 & 0x00fc0000) << 6) | ((i1 & 0x00000fc0) << 10) | ((i2 & 0x00fc0000) >>> 10)
| ((i2 & 0x00000fc0) >>> 6);
newKey[i + 1] = ((i1 & 0x0003f000) << 12) | ((i1 & 0x0000003f) << 16) | ((i2 & 0x0003f000) >>> 4)
| (i2 & 0x0000003f);
}
return newKey;
}
/**
* the DES engine.
*/
protected void desFunc(int[] wKey, byte[] in, int inOff, byte[] out, int outOff)
{
int work, right, left;
left = (in[inOff + 0] & 0xff) << 24;
left |= (in[inOff + 1] & 0xff) << 16;
left |= (in[inOff + 2] & 0xff) << 8;
left |= (in[inOff + 3] & 0xff);
right = (in[inOff + 4] & 0xff) << 24;
right |= (in[inOff + 5] & 0xff) << 16;
right |= (in[inOff + 6] & 0xff) << 8;
right |= (in[inOff + 7] & 0xff);
work = ((left >>> 4) ^ right) & 0x0f0f0f0f;
right ^= work;
left ^= (work << 4);
work = ((left >>> 16) ^ right) & 0x0000ffff;
right ^= work;
left ^= (work << 16);
work = ((right >>> 2) ^ left) & 0x33333333;
left ^= work;
right ^= (work << 2);
work = ((right >>> 8) ^ left) & 0x00ff00ff;
left ^= work;
right ^= (work << 8);
right = ((right << 1) | ((right >>> 31) & 1)) & 0xffffffff;
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = ((left << 1) | ((left >>> 31) & 1)) & 0xffffffff;
for (int round = 0; round < 8; round++)
{
int fval;
work = (right << 28) | (right >>> 4);
work ^= wKey[round * 4 + 0];
fval = SP7[work & 0x3f];
fval |= SP5[(work >>> 8) & 0x3f];
fval |= SP3[(work >>> 16) & 0x3f];
fval |= SP1[(work >>> 24) & 0x3f];
work = right ^ wKey[round * 4 + 1];
fval |= SP8[work & 0x3f];
fval |= SP6[(work >>> 8) & 0x3f];
fval |= SP4[(work >>> 16) & 0x3f];
fval |= SP2[(work >>> 24) & 0x3f];
left ^= fval;
work = (left << 28) | (left >>> 4);
work ^= wKey[round * 4 + 2];
fval = SP7[work & 0x3f];
fval |= SP5[(work >>> 8) & 0x3f];
fval |= SP3[(work >>> 16) & 0x3f];
fval |= SP1[(work >>> 24) & 0x3f];
work = left ^ wKey[round * 4 + 3];
fval |= SP8[work & 0x3f];
fval |= SP6[(work >>> 8) & 0x3f];
fval |= SP4[(work >>> 16) & 0x3f];
fval |= SP2[(work >>> 24) & 0x3f];
right ^= fval;
}
right = (right << 31) | (right >>> 1);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = (left << 31) | (left >>> 1);
work = ((left >>> 8) ^ right) & 0x00ff00ff;
right ^= work;
left ^= (work << 8);
work = ((left >>> 2) ^ right) & 0x33333333;
right ^= work;
left ^= (work << 2);
work = ((right >>> 16) ^ left) & 0x0000ffff;
left ^= work;
right ^= (work << 16);
work = ((right >>> 4) ^ left) & 0x0f0f0f0f;
left ^= work;
right ^= (work << 4);
out[outOff + 0] = (byte) ((right >>> 24) & 0xff);
out[outOff + 1] = (byte) ((right >>> 16) & 0xff);
out[outOff + 2] = (byte) ((right >>> 8) & 0xff);
out[outOff + 3] = (byte) (right & 0xff);
out[outOff + 4] = (byte) ((left >>> 24) & 0xff);
out[outOff + 5] = (byte) ((left >>> 16) & 0xff);
out[outOff + 6] = (byte) ((left >>> 8) & 0xff);
out[outOff + 7] = (byte) (left & 0xff);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class CTRMode implements BlockCipher
{
byte[] X;
byte[] Xenc;
BlockCipher bc;
int blockSize;
boolean doEncrypt;
int count = 0;
@Override
public void init(boolean forEncryption, byte[] key)
{
}
public CTRMode(BlockCipher tc, byte[] iv, boolean doEnc) throws IllegalArgumentException
{
bc = tc;
blockSize = bc.getBlockSize();
doEncrypt = doEnc;
if (blockSize != iv.length)
throw new IllegalArgumentException("IV must be " + blockSize + " bytes long! (currently " + iv.length + ")");
X = new byte[blockSize];
Xenc = new byte[blockSize];
System.arraycopy(iv, 0, X, 0, blockSize);
}
@Override
public final int getBlockSize()
{
return blockSize;
}
@Override
public final void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
bc.transformBlock(X, 0, Xenc, 0);
for (int i = 0; i < blockSize; i++)
{
dst[dstoff + i] = (byte) (src[srcoff + i] ^ Xenc[i]);
}
for (int i = (blockSize - 1); i >= 0; i--)
{
X[i]++;
if (X[i] != 0)
break;
}
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.io.*;
/**
*
* @author XuanHung
*/
public class CipherOutputStream
{
BlockCipher currentCipher;
OutputStream bo;
byte[] buffer;
byte[] enc;
int blockSize;
int pos;
/*
* We cannot use java.io.BufferedOutputStream, since that is not available
* in J2ME. Everything could be improved here alot.
*/
final int BUFF_SIZE = 2048;
byte[] out_buffer = new byte[BUFF_SIZE];
int out_buffer_pos = 0;
public CipherOutputStream(BlockCipher tc, OutputStream bo)
{
this.bo = bo;
changeCipher(tc);
}
private void internal_write(byte[] src, int off, int len) throws IOException
{
while (len > 0)
{
int space = BUFF_SIZE - out_buffer_pos;
int copy = (len > space) ? space : len;
System.arraycopy(src, off, out_buffer, out_buffer_pos, copy);
off += copy;
out_buffer_pos += copy;
len -= copy;
if (out_buffer_pos >= BUFF_SIZE)
{
bo.write(out_buffer, 0, BUFF_SIZE);
out_buffer_pos = 0;
}
}
}
private void internal_write(int b) throws IOException
{
out_buffer[out_buffer_pos++] = (byte) b;
if (out_buffer_pos >= BUFF_SIZE)
{
bo.write(out_buffer, 0, BUFF_SIZE);
out_buffer_pos = 0;
}
}
public void flush() throws IOException
{
if (pos != 0)
throw new IOException("FATAL: cannot flush since crypto buffer is not aligned.");
if (out_buffer_pos > 0)
{
bo.write(out_buffer, 0, out_buffer_pos);
out_buffer_pos = 0;
}
bo.flush();
}
public void changeCipher(BlockCipher bc)
{
this.currentCipher = bc;
blockSize = bc.getBlockSize();
buffer = new byte[blockSize];
enc = new byte[blockSize];
pos = 0;
}
private void writeBlock() throws IOException
{
try
{
currentCipher.transformBlock(buffer, 0, enc, 0);
}
catch (Exception e)
{
throw (IOException) new IOException("Error while decrypting block.").initCause(e);
}
internal_write(enc, 0, blockSize);
pos = 0;
}
public void write(byte[] src, int off, int len) throws IOException
{
while (len > 0)
{
int avail = blockSize - pos;
int copy = Math.min(avail, len);
System.arraycopy(src, off, buffer, pos, copy);
pos += copy;
off += copy;
len -= copy;
if (pos >= blockSize)
writeBlock();
}
}
public void write(int b) throws IOException
{
buffer[pos++] = (byte) b;
if (pos >= blockSize)
writeBlock();
}
public void writePlain(int b) throws IOException
{
if (pos != 0)
throw new IOException("Cannot write plain since crypto buffer is not aligned.");
internal_write(b);
}
public void writePlain(byte[] b, int off, int len) throws IOException
{
if (pos != 0)
throw new IOException("Cannot write plain since crypto buffer is not aligned.");
internal_write(b, off, len);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.util.Vector;
/**
*
* @author XuanHung
*/
public class BlockCipherFactory
{
static class CipherEntry
{
String type;
int blocksize;
int keysize;
String cipherClass;
public CipherEntry(String type, int blockSize, int keySize, String cipherClass)
{
this.type = type;
this.blocksize = blockSize;
this.keysize = keySize;
this.cipherClass = cipherClass;
}
}
static Vector<CipherEntry> ciphers = new Vector<>();
static
{
/* Higher Priority First */
ciphers.addElement(new CipherEntry("aes256-ctr", 16, 32, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes192-ctr", 16, 24, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes128-ctr", 16, 16, "encrypt.AES"));
ciphers.addElement(new CipherEntry("blowfish-ctr", 8, 16, "encrypt.BlowFish"));
ciphers.addElement(new CipherEntry("aes256-cbc", 16, 32, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes192-cbc", 16, 24, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes128-cbc", 16, 16, "encrypt.AES"));
ciphers.addElement(new CipherEntry("blowfish-cbc", 8, 16, "encrypt.BlowFish"));
ciphers.addElement(new CipherEntry("3des-ctr", 8, 24, "encrypt.DESede"));
ciphers.addElement(new CipherEntry("3des-cbc", 8, 24, "encrypt.DESede"));
}
public static String[] getDefaultCipherList()
{
String list[] = new String[ciphers.size()];
for (int i = 0; i < ciphers.size(); i++)
{
CipherEntry ce = ciphers.elementAt(i);
list[i] = ce.type;
}
return list;
}
public static void checkCipherList(String[] cipherCandidates)
{
for (String cipherCandidate : cipherCandidates) {
getEntry(cipherCandidate);
}
}
public static BlockCipher createCipher(String type, boolean encrypt, byte[] key, byte[] iv)
{
try
{
CipherEntry ce = getEntry(type);
Class cc = Class.forName(ce.cipherClass);
BlockCipher bc = (BlockCipher) cc.newInstance();
if (type.endsWith("-cbc"))
{
bc.init(encrypt, key);
return new CBCMode(bc, iv, encrypt);
}
else if (type.endsWith("-ctr"))
{
bc.init(true, key);
return new CTRMode(bc, iv, encrypt);
}
throw new IllegalArgumentException("Cannot instantiate " + type);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e)
{
throw new IllegalArgumentException("Cannot instantiate " + type);
}
}
private static CipherEntry getEntry(String type)
{
for (int i = 0; i < ciphers.size(); i++)
{
CipherEntry ce = ciphers.elementAt(i);
if (ce.type.equals(type))
return ce;
}
throw new IllegalArgumentException("Unkown algorithm " + type);
}
public static int getBlockSize(String type)
{
CipherEntry ce = getEntry(type);
return ce.blocksize;
}
public static int getKeySize(String type)
{
CipherEntry ce = getEntry(type);
return ce.keysize;
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public interface BlockCipher
{
public void init(boolean forEncryption, byte[] key);
public int getBlockSize();
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff);
} | Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.security.PublicKey;
/**
*
* @author XuanHung
*/
class pkCipher {
static void init(int ENCRYPT_MODE, PublicKey pk) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class DESede extends DES
{
private int[] key1 = null;
private int[] key2 = null;
private int[] key3 = null;
private boolean encrypt;
/**
* standard constructor.
*/
public DESede()
{
}
/**
* initialise a DES cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the parameters required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
public void init(boolean encrypting, byte[] key)
{
key1 = generateWorkingKey(encrypting, key, 0);
key2 = generateWorkingKey(!encrypting, key, 8);
key3 = generateWorkingKey(encrypting, key, 16);
encrypt = encrypting;
}
public String getAlgorithmName()
{
return "DESede";
}
public int getBlockSize()
{
return 8;
}
public void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (key1 == null)
{
throw new IllegalStateException("DESede engine not initialised!");
}
if (encrypt)
{
desFunc(key1, in, inOff, out, outOff);
desFunc(key2, out, outOff, out, outOff);
desFunc(key3, out, outOff, out, outOff);
}
else
{
desFunc(key3, in, inOff, out, outOff);
desFunc(key2, out, outOff, out, outOff);
desFunc(key1, out, outOff, out, outOff);
}
}
public void reset()
{
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class BlowFish implements BlockCipher
{
private final static int[] KP = { 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0,
0x082EFA98, 0xEC4E6C89, 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5,
0xB5470917, 0x9216D5D9, 0x8979FB1B },
KS0 = { 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, 0x24A19947,
0xB3916CF7, 0x0801F2E2, 0x858EFC16, 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, 0x0D95748F, 0x728EB658,
0x718BCD58, 0x82154AEE, 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, 0xC5D1B023, 0x286085F0, 0xCA417918,
0xB8DB38EF, 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60,
0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, 0xA15486AF,
0x7C72E993, 0xB3EE1411, 0x636FBC2A, 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, 0xAFD6BA33, 0x6C24CF5C,
0x7A325381, 0x28958677, 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, 0x61D809CC, 0xFB21A991, 0x487CAC60,
0x5DEC8032, 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239,
0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, 0x6A51A0D2,
0xD8542F68, 0x960FA728, 0xAB5133A3, 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, 0xA1F1651D, 0x39AF0176,
0x66CA593E, 0x82430E88, 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, 0xE06F75D8, 0x85C12073, 0x401A449F,
0x56C16AA6, 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B,
0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, 0xC1A94FB6,
0x409F60C4, 0x5E5C9EC2, 0x196A2463, 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, 0x6DFC511F, 0x9B30952C,
0xCC814544, 0xAF5EBD09, 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, 0xC0CBA857, 0x45C8740F, 0xD20B5F39,
0xB9D3FBDB, 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8,
0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, 0x9E5C57BB,
0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, 0x695B27B0, 0xBBCA58C8,
0xE1FFA35D, 0xB8F011A0, 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, 0x9A53E479, 0xB6F84565, 0xD28E49BC,
0x4BFB9790, 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4,
0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, 0x8FF6E2FB,
0xF2122B64, 0x8888B812, 0x900DF01C, 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, 0x2F2F2218, 0xBE0E1777,
0xEA752DFE, 0x8B021FA1, 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81,
0xD2ADA8D9, 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF,
0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, 0x2464369B,
0xF009B91E, 0x5563911D, 0x59DFA6AA, 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, 0x83260376, 0x6295CFA9,
0x11C81968, 0x4E734A41, 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, 0xD60F573F, 0xBC9BC6E4, 0x2B60A476,
0x81E67400, 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664,
0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A },
KS1 = { 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, 0xECAA8C71,
0x699A17FF, 0x5664526C, 0xC2B19EE1, 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, 0x3F54989A, 0x5B429D65,
0x6B8FE4D6, 0x99F73FD6, 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, 0x4CDD2086, 0x8470EB26, 0x6382E9C6,
0x021ECC5E, 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737,
0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, 0xAE0CF51A,
0x3CB574B2, 0x25837A58, 0xDC0921BD, 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, 0x3AE5E581, 0x37C2DADC,
0xC8B57634, 0x9AF3DDA7, 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1,
0x183EB331, 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF,
0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, 0x7A584718,
0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, 0xEF1C1847, 0x3215D908,
0xDD433B37, 0x24C2BA16, 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, 0x71DFF89E, 0x10314E55, 0x81AC77D6,
0x5F11199B, 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E,
0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, 0x803E89D6,
0x5266C825, 0x2E4CC978, 0x9C10B36A, 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, 0xF2F74EA7, 0x361D2B3D,
0x1939260F, 0x19C27960, 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, 0xE3BC4595, 0xA67BC883, 0xB17F37D1,
0x018CFF28, 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84,
0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, 0xB5735C90,
0x4C70A239, 0xD59E9E0B, 0xCBAADE14, 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, 0x648B1EAF, 0x19BDF0CA,
0xA02369B9, 0x655ABB50, 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, 0x9B540B19, 0x875FA099, 0x95F7997E,
0x623D7DA8, 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99,
0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, 0x58EBF2EF,
0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, 0x45EEE2B6, 0xA3AAABEA,
0xDB6C4F15, 0xFACB4FD0, 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, 0xD81E799E, 0x86854DC7, 0xE44B476A,
0x3D816250, 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285,
0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, 0x3372F092,
0x8D937E41, 0xD65FECF1, 0x6C223BDB, 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, 0xA6078084, 0x19F8509E,
0xE8EFD855, 0x61D99735, 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, 0x9E447A2E, 0xC3453484, 0xFDD56705,
0x0E1E9EC9, 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20,
0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 },
KS2 = { 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, 0xD4082471,
0x3320F46A, 0x43B7D4B7, 0x500061AF, 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, 0x4D95FC1D, 0x96B591AF,
0x70F4DDD3, 0x66A02F45, 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, 0x96EB27B3, 0x55FD3941, 0xDA2547E6,
0xABCA0A9A, 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE,
0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, 0x20FE9E35,
0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, 0x3A6EFA74, 0xDD5B4332,
0x6841E7F7, 0xCA7820FB, 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, 0x55533A3A, 0x20838D87, 0xFE6BA9B7,
0xD096954B, 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C,
0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, 0x07F9C9EE,
0x41041F0F, 0x404779A4, 0x5D886E17, 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, 0x257B7834, 0x602A9C60,
0xDFF8E8A3, 0x1F636C1B, 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, 0x6B2395E0, 0x333E92E1, 0x3B240B62,
0xEEBEB922, 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0,
0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, 0xA812DC60,
0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, 0xF1290DC7, 0xCC00FFA3,
0xB5390F92, 0x690FED0B, 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, 0xBB132F88, 0x515BAD24, 0x7B9479BF,
0x763BD6EB, 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C,
0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, 0x44421659,
0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, 0x9DBC8057, 0xF0F7C086,
0x60787BF8, 0x6003604D, 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, 0x83426B33, 0xF01EAB71, 0xB0804187,
0x3C005E5F, 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2,
0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, 0x466E598E,
0x20B45770, 0x8CD55591, 0xC902DE4C, 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, 0xB77F19B6, 0xE0A9DC09,
0x662D09A1, 0xC4324633, 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F,
0x2868F169, 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027,
0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, 0x11E69ED7,
0x2338EA63, 0x53C2DD94, 0xC2C21634, 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, 0x6F05E409, 0x4B7C0188,
0x39720A3D, 0x7C927C24, 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, 0xED545578, 0x08FCA5B5, 0xD83D7CD3,
0x4DAD0FC4, 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837,
0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 },
KS3 = { 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, 0xD5118E9D,
0xBF0F7315, 0xD62D1C7E, 0xC700C47B, 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, 0x5748AB2F, 0xBC946E79,
0xC6A376D2, 0x6549C2C8, 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, 0x2939BBDB, 0xA9BA4650, 0xAC9526E8,
0xBE5EE304, 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4,
0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, 0xC72FEFD3,
0xF752F7DA, 0x3F046F69, 0x77FA0A59, 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, 0xE990FD5A, 0x9E34D797,
0x2CF0B7D9, 0x022B8B51, 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472,
0x5A88F54C, 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28,
0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, 0xC3EB9E15,
0x3C9057A2, 0x97271AEC, 0xA93A072A, 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, 0x7533D928, 0xB155FDF5,
0x03563482, 0x8ABA3CBB, 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, 0x4DE81751, 0x3830DC8E, 0x379D5862,
0x9320F991, 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680,
0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, 0x5BBEF7DD,
0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, 0x72EACEA8, 0xFA6484BB,
0x8D6612AE, 0xBF3C6F47, 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, 0x740E0D8D, 0xE75B1357, 0xF8721671,
0xAF537D5D, 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048,
0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, 0xA08839E1,
0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, 0x1A908749, 0xD44FBD9A,
0xD0DADECB, 0xD50ADA38, 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF,
0x27D9459C, 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1,
0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, 0x9F1F9532,
0xE0D392DF, 0xD3A0342B, 0x8971F21E, 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, 0xDF359F8D, 0x9B992F2E,
0xE60B6F47, 0x0FE3F11D, 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, 0x1618B166, 0xFD2C1D05, 0x848FD2C5,
0xF6FB2299, 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC,
0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, 0xC9AA53FD,
0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, 0x53113EC0, 0x1640E3D3,
0x38ABBD60, 0x2547ADF0, 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0,
0x4CF9AA7E, 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F,
0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 };
// ====================================
// Useful constants
// ====================================
private static final int ROUNDS = 16;
private static final int BLOCK_SIZE = 8; // bytes = 64 bits
private static final int SBOX_SK = 256;
private static final int P_SZ = ROUNDS + 2;
private final int[] S0, S1, S2, S3; // the s-boxes
private final int[] P; // the p-array
private boolean doEncrypt = false;
private byte[] workingKey = null;
public BlowFish()
{
S0 = new int[SBOX_SK];
S1 = new int[SBOX_SK];
S2 = new int[SBOX_SK];
S3 = new int[SBOX_SK];
P = new int[P_SZ];
}
/**
* initialise a Blowfish cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the key required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
public void init(boolean encrypting, byte[] key)
{
this.doEncrypt = encrypting;
this.workingKey = key;
setKey(this.workingKey);
}
public String getAlgorithmName()
{
return "Blowfish";
}
public final void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (workingKey == null)
{
throw new IllegalStateException("Blowfish not initialised");
}
if (doEncrypt)
{
encryptBlock(in, inOff, out, outOff);
}
else
{
decryptBlock(in, inOff, out, outOff);
}
}
public void reset()
{
}
public int getBlockSize()
{
return BLOCK_SIZE;
}
// ==================================
// Private Implementation
// ==================================
private int F(int x)
{
return (((S0[(x >>> 24)] + S1[(x >>> 16) & 0xff]) ^ S2[(x >>> 8) & 0xff]) + S3[x & 0xff]);
}
/**
* apply the encryption cycle to each value pair in the table.
*/
private void processTable(int xl, int xr, int[] table)
{
int size = table.length;
for (int s = 0; s < size; s += 2)
{
xl ^= P[0];
for (int i = 1; i < ROUNDS; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[ROUNDS + 1];
table[s] = xr;
table[s + 1] = xl;
xr = xl; // end of cycle swap
xl = table[s];
}
}
private void setKey(byte[] key)
{
/*
* - comments are from _Applied Crypto_, Schneier, p338 please be
* careful comparing the two, AC numbers the arrays from 1, the enclosed
* code from 0.
*
* (1) Initialise the S-boxes and the P-array, with a fixed string This
* string contains the hexadecimal digits of pi (3.141...)
*/
System.arraycopy(KS0, 0, S0, 0, SBOX_SK);
System.arraycopy(KS1, 0, S1, 0, SBOX_SK);
System.arraycopy(KS2, 0, S2, 0, SBOX_SK);
System.arraycopy(KS3, 0, S3, 0, SBOX_SK);
System.arraycopy(KP, 0, P, 0, P_SZ);
/*
* (2) Now, XOR P[0] with the first 32 bits of the key, XOR P[1] with
* the second 32-bits of the key, and so on for all bits of the key (up
* to P[17]). Repeatedly cycle through the key bits until the entire
* P-array has been XOR-ed with the key bits
*/
int keyLength = key.length;
int keyIndex = 0;
for (int i = 0; i < P_SZ; i++)
{
// get the 32 bits of the key, in 4 * 8 bit chunks
int data = 0x0000000;
for (int j = 0; j < 4; j++)
{
// create a 32 bit block
data = (data << 8) | (key[keyIndex++] & 0xff);
// wrap when we get to the end of the key
if (keyIndex >= keyLength)
{
keyIndex = 0;
}
}
// XOR the newly created 32 bit chunk onto the P-array
P[i] ^= data;
}
/*
* (3) Encrypt the all-zero string with the Blowfish algorithm, using
* the subkeys described in (1) and (2)
*
* (4) Replace P1 and P2 with the output of step (3)
*
* (5) Encrypt the output of step(3) using the Blowfish algorithm, with
* the modified subkeys.
*
* (6) Replace P3 and P4 with the output of step (5)
*
* (7) Continue the process, replacing all elements of the P-array and
* then all four S-boxes in order, with the output of the continuously
* changing Blowfish algorithm
*/
processTable(0, 0, P);
processTable(P[P_SZ - 2], P[P_SZ - 1], S0);
processTable(S0[SBOX_SK - 2], S0[SBOX_SK - 1], S1);
processTable(S1[SBOX_SK - 2], S1[SBOX_SK - 1], S2);
processTable(S2[SBOX_SK - 2], S2[SBOX_SK - 1], S3);
}
/**
* Encrypt the given input starting at the given offset and place the result
* in the provided buffer starting at the given offset. The input will be an
* exact multiple of our blocksize.
*/
private void encryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[0];
for (int i = 1; i < ROUNDS; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[ROUNDS + 1];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
/**
* Decrypt the given input starting at the given offset and place the result
* in the provided buffer starting at the given offset. The input will be an
* exact multiple of our blocksize.
*/
private void decryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[ROUNDS + 1];
for (int i = ROUNDS; i > 0; i -= 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i - 1];
}
xr ^= P[0];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
private int BytesTo32bits(byte[] b, int i)
{
return ((b[i] & 0xff) << 24) | ((b[i + 1] & 0xff) << 16) | ((b[i + 2] & 0xff) << 8) | ((b[i + 3] & 0xff));
}
private void Bits32ToBytes(int in, byte[] b, int offset)
{
b[offset + 3] = (byte) in;
b[offset + 2] = (byte) (in >> 8);
b[offset + 1] = (byte) (in >> 16);
b[offset] = (byte) (in >> 24);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class NullCipher implements BlockCipher
{
private int blockSize = 8;
public NullCipher()
{
}
public NullCipher(int blockSize)
{
this.blockSize = blockSize;
}
@Override
public void init(boolean forEncryption, byte[] key)
{
}
@Override
public int getBlockSize()
{
return blockSize;
}
@Override
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
System.arraycopy(src, srcoff, dst, dstoff, blockSize);
}
}
| Java |
package banvetauclient;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Serializer {
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
} | Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package banvetauclient;
import java.awt.EventQueue;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import clientGUI.BookTicket;
import clientGUI.Login;
/**
*
* @author XuanHung
*/
public class BanVeTauClient {
public static Socket clientSk = null;
public static ObjectInputStream cis = null;
public static ObjectOutputStream cos = null;
public static void main(String args[]) {
/* Set the Nimbus look and feel */
// <editor-fold defaultstate="collapsed"
// desc=" Look and feel setting code (optional) ">
/*
* If Nimbus (introduced in Java SE 6) is not available, stay with the
* default look and feel. For details see
* http://download.oracle.com/javase
* /tutorial/uiswing/lookandfeel/plaf.html
*/
try {
for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager
.getInstalledLookAndFeels()) {
if ("Nimbus".equals(info.getName())) {
javax.swing.UIManager.setLookAndFeel(info.getClassName());
break;
}
}
} catch (ClassNotFoundException ex) {
java.util.logging.Logger.getLogger(BookTicket.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (InstantiationException ex) {
java.util.logging.Logger.getLogger(BookTicket.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (IllegalAccessException ex) {
java.util.logging.Logger.getLogger(BookTicket.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
} catch (javax.swing.UnsupportedLookAndFeelException ex) {
java.util.logging.Logger.getLogger(BookTicket.class.getName()).log(
java.util.logging.Level.SEVERE, null, ex);
}
// </editor-fold>
/* Create and display the form */
EventQueue.invokeLater(new Runnable() {
public void run() {
try {
clientSk = new Socket("127.0.0.1", 10000);
cos = new ObjectOutputStream(clientSk.getOutputStream());
cis = new ObjectInputStream(clientSk.getInputStream());
Login frame = new Login();
frame.setVisible(true);
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
}
| Java |
package clientGUI;
import banvetauclient.BanVeTauClient;
import banvetauclient.Serializer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
@SuppressWarnings("serial")
public class Login extends JFrame {
private final JPanel contentPane;
private final JTextField txtUser;
private final JPasswordField txtPass;
/**
* Create the frame.
*/
public Login() {
setTitle("Đăng nhập tài khoản");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 346, 300);
final JFrame parentForm = this;
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("Tên tài khoản:");
lblNewLabel.setBounds(26, 61, 79, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("Mật khẩu:");
lblNewLabel_1.setBounds(26, 105, 62, 14);
contentPane.add(lblNewLabel_1);
txtUser = new JTextField();
txtUser.setBounds(115, 50, 203, 36);
contentPane.add(txtUser);
txtUser.setColumns(10);
JButton btnLogin = new JButton("\u0110\u0103ng nh\u1EADp");
btnLogin.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
if(AccountIsExist(txtUser.getText(), new String(txtPass.getPassword()))){
JOptionPane.showMessageDialog(null, "Login Successfull", "Notice", JOptionPane.INFORMATION_MESSAGE);
parentForm.setVisible(false);
BookTicket fr = new BookTicket();
//BookTicket.user = user;
fr.setVisible(true);
parentForm.dispose();
} else {
JOptionPane.showMessageDialog(null, "Login Failure", "Notice", JOptionPane.INFORMATION_MESSAGE);
}
}
});
btnLogin.setBounds(29, 150, 91, 23);
contentPane.add(btnLogin);
JButton btnSignUp = new JButton("\u0110\u0103ng k\u00FD");
btnSignUp.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
SignUp frame = new SignUp();
frame.setVisible(true);
}
});
btnSignUp.setBounds(127, 150, 91, 23);
contentPane.add(btnSignUp);
JButton btnExit = new JButton("Tho\u00E1t");
btnExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
CloseFrame();
}
});
btnExit.setBounds(227, 150, 91, 23);
contentPane.add(btnExit);
txtPass = new JPasswordField();
txtPass.setBounds(115, 94, 203, 36);
contentPane.add(txtPass);
}
private void CloseFrame() {
super.dispose();
}
public static boolean AccountIsExist(String acc, String pass) {
/*Session session = TicketUtil.getSessionFactory().openSession();
List<Users> lst = null;
try {
String queryCommand = "FROM Users where username = :acc and is_active = 1";
if (pass != null && !pass.isEmpty()) {
queryCommand += " and password = :pass";
}
Query query = session.createQuery(queryCommand);
query.setParameter("acc", acc.toLowerCase());
if (pass != null && !pass.isEmpty()) {
query.setParameter("pass", pass);
}
lst = query.list();
} catch (HibernateException e) {
e.printStackTrace();
} finally {
session.close();
}
if (lst != null) {
if (lst.size() > 0) {
user = lst.get(0);
return true;
}
}*/
try {
String[] InfoAccount = new String[2];
InfoAccount[0] = acc;
InfoAccount[1] = pass;
byte[] serialObject = Serializer.serialize(InfoAccount);
BanVeTauClient.cos.write(1);
BanVeTauClient.cos.write(serialObject.length);
BanVeTauClient.cos.write(serialObject);
BanVeTauClient.cos.flush();
boolean result = BanVeTauClient.cis.readBoolean();
System.out.println(result);
return result;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return false;
}
}
| Java |
package clientGUI;
import CommonObject.InfoChuyenTau;
import CommonObject.InfoDangKyVe;
import banvetauclient.BanVeTauClient;
import banvetauclient.Serializer;
import java.awt.Color;
import java.awt.Font;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.List;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.JTextField;
import javax.swing.ListSelectionModel;
import javax.swing.SwingConstants;
import javax.swing.border.EmptyBorder;
import javax.swing.border.LineBorder;
import javax.swing.table.DefaultTableModel;
@SuppressWarnings("serial")
public class BookTicket extends JFrame {
//public static Users user = null;
private final JPanel contentPane;
private final JTextField txtNumTicket;
private final JTable tblRoute;
private final JTextField txtCodeConfirm;
private final JTextField txtReInputCodeConfirm;
private JComboBox<InfoChuyenTau> combRoute;
private final JLabel lblTuyenDuong;
private final JLabel lblLoaiGhe;
private InfoChuyenTau selectedTrain = null;
private List<InfoDangKyVe> orderList = null;
/**
* Create the frame.
*/
@SuppressWarnings("rawtypes")
public BookTicket() {
addWindowListener(new WindowAdapter() {
@Override
public void windowOpened(WindowEvent arg0) {
fillDataIntoCombobox();
}
});
setTitle("Đặt vé");
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 806, 572);
//orderList = new ArrayList<Orders>();
final JFrame parentForm = this;
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(54, 15, 15, 15));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblChuyn = new JLabel("Chuy\u1EBFn: ");
lblChuyn.setBounds(277, 14, 79, 14);
contentPane.add(lblChuyn);
JLabel lblSLngV = new JLabel("S\u1ED1 l\u01B0\u1EE3ng v\u00E9 :");
lblSLngV.setBounds(277, 132, 91, 14);
contentPane.add(lblSLngV);
txtNumTicket = new JTextField();
txtNumTicket.setColumns(10);
txtNumTicket.setBounds(378, 123, 150, 32);
contentPane.add(txtNumTicket);
JButton btnXoaVeDat = new JButton("Xóa vé đặt");
btnXoaVeDat.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
RemoveBookTicket();
}
});
btnXoaVeDat.setBounds(277, 164, 91, 23);
contentPane.add(btnXoaVeDat);
JButton btnBookTicket = new JButton("Đặt vé");
btnBookTicket.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
InsertBookTicket();
}
});
btnBookTicket.setBounds(437, 164, 91, 23);
contentPane.add(btnBookTicket);
combRoute = new JComboBox<InfoChuyenTau>();
combRoute.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent arg0) {
/*try
{
if(arg0.getStateChange() == ItemEvent.SELECTED)
{
selectedTrain = ((Trains)combRoute.getSelectedItem());
if(selectedTrain!= null)
{
Stations startStation = selectedTrain.getStationsByStartStation();
Stations toStation = selectedTrain.getStationsByToStation();
if(startStation != null && toStation != null)
{
lblTuyenDuong.setText(startStation.getName() + " - " + toStation.getName());
}
Seats seat = selectedTrain.getSeats();
if(seat != null)
{
lblLoaiGhe.setText(seat.getName());
}
}
}
}
catch(Exception e)
{
selectedTrain = null;
lblTuyenDuong.setText("Chưa có");
lblLoaiGhe.setText("Chưa có");
e.printStackTrace();
}*/
}
});
combRoute.setModel(new DefaultComboBoxModel(new String[]{"Chọn Tuyến..."}));
combRoute.setBounds(378, 11, 150, 22);
contentPane.add(combRoute);
JLabel lblNewLabel = new JLabel("Danh sách đặt vé");
lblNewLabel.setFont(new Font("Tahoma", Font.PLAIN, 15));
lblNewLabel.setHorizontalAlignment(SwingConstants.CENTER);
lblNewLabel.setBounds(331, 198, 159, 34);
contentPane.add(lblNewLabel);
txtCodeConfirm = new JTextField();
txtCodeConfirm.setColumns(10);
txtCodeConfirm.setBounds(305, 395, 150, 20);
contentPane.add(txtCodeConfirm);
txtReInputCodeConfirm = new JTextField();
txtReInputCodeConfirm.setColumns(10);
txtReInputCodeConfirm.setBounds(378, 437, 150, 20);
contentPane.add(txtReInputCodeConfirm);
JLabel lblNhpLi = new JLabel("Nhập lại ô chữ trên:");
lblNhpLi.setBounds(260, 440, 108, 14);
contentPane.add(lblNhpLi);
JButton btnConfirm = new JButton("Xác nhận vé đặt");
btnConfirm.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
SaveOrderList();
}
});
btnConfirm.setBounds(260, 486, 129, 23);
contentPane.add(btnConfirm);
JButton btnExit = new JButton("Hủy bỏ");
btnExit.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent arg0) {
parentForm.dispose();
}
});
btnExit.setBounds(437, 486, 91, 23);
contentPane.add(btnExit);
JScrollPane scrollPane = new JScrollPane();
scrollPane.setBounds(0, 235, 790, 127);
tblRoute = new JTable();
tblRoute.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
tblRoute.setCellSelectionEnabled(true);
tblRoute.setColumnSelectionAllowed(true);
tblRoute.setBorder(new LineBorder(new Color(0, 0, 0)));
tblRoute.setModel(new DefaultTableModel(
new Object[][]{},
new String[]{
"STT", "Chuy\u1EBFn", "Ga \u0111\u1EBFn", "Ga \u0111i", "Th\u1EDDi gian", "S\u1ED1 l\u01B0\u1EE3ng", "\u0110\u01A1n gi\u00E1", "Th\u00E0nh ti\u1EC1n"
}
));
scrollPane.setViewportView(tblRoute);
contentPane.add(scrollPane);
JLabel lblTuynng = new JLabel("Tuyến đường:");
lblTuynng.setBounds(277, 55, 79, 23);
contentPane.add(lblTuynng);
JLabel lblLoiGh = new JLabel("Loại ghế: ");
lblLoiGh.setBounds(277, 89, 79, 23);
contentPane.add(lblLoiGh);
lblTuyenDuong = new JLabel("Chưa có");
lblTuyenDuong.setBounds(378, 52, 150, 29);
contentPane.add(lblTuyenDuong);
lblLoaiGhe = new JLabel("Chưa có");
lblLoaiGhe.setBounds(378, 89, 150, 29);
contentPane.add(lblLoaiGhe);
}
//Fill data into the route combobox
private void fillDataIntoCombobox() {
/*//Open connection
Session session = TicketUtil.getSessionFactory().openSession();
List<Trains> lst = null;
try
{
//Get Trains Data
String queryCommand = "SELECT tr " +
"FROM Trains tr " +
"join fetch tr.stationsByStartStation ss "+
"join fetch tr.stationsByToStation ts "+
"join fetch tr.seats ss ";
Query query = session.createQuery(queryCommand);
lst = query.list();
//fill data into combobox
for(int i = 0; i < lst.size(); i++)
{
combRoute.addItem(lst.get(i));
}
}
catch (HibernateException e) {
e.printStackTrace();
}
finally {
//Close connection
session.close();
}*/
try {
byte[] infoBytes = new byte[BanVeTauClient.cis.read()];
BanVeTauClient.cis.read(infoBytes);
InfoChuyenTau[] s = (InfoChuyenTau[]) Serializer.deserialize(infoBytes);
//fill data into combobox
for (int i = 0; i < s.length; i++) {
combRoute.addItem(s[i]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
//Insert the current book
private void InsertBookTicket() {
try {
//Check if user input the number of ticket
if (txtNumTicket.getText() != null && !txtNumTicket.getText().isEmpty()) {
int numTicket = Integer.parseInt(txtNumTicket.getText());
//Create new order
InfoDangKyVe newOrder = new InfoDangKyVe();
//Set information for the order
/*newOrder.setCode(new Date().toString() + user.getUsername());
newOrder.setStatus("PENDING");
newOrder.setPaid(0);
newOrder.setUsers(user);
newOrder.setAmount(numTicket);
newOrder.setTotal((double)(numTicket * selectedTrain.getPrice()));
newOrder.setTrains(selectedTrain);*/
newOrder.TrainId = selectedTrain.IdChuyenDi;
newOrder.Ammount = numTicket;
newOrder.Total = (double) (numTicket * selectedTrain.Price);
//add the new order to list
orderList.add(newOrder);
//add the information of new order to table
int numRow = tblRoute.getRowCount() + 1;
DefaultTableModel model = (DefaultTableModel) tblRoute.getModel();
model.addRow(new Object[]{
numRow,
selectedTrain.TenChuyen,
selectedTrain.TenGaDen,
selectedTrain.TenGaDi,
null,
newOrder.Ammount,
selectedTrain.Price,
newOrder.Total
});
} else {
JOptionPane.showMessageDialog(null, "You have not inputed the number of ticket yet", "Error", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
JOptionPane.showMessageDialog(null, "Error : " + e.getMessage(), "Error", JOptionPane.ERROR_MESSAGE);
}
}
//Remove the selected book
private void RemoveBookTicket() {
int index = tblRoute.getSelectedRow();
if (index >= 0) {
DefaultTableModel model = (DefaultTableModel) tblRoute.getModel();
model.removeRow(index);
orderList.remove(index);
JOptionPane.showMessageDialog(null, orderList.size(), "Error", JOptionPane.INFORMATION_MESSAGE);
} else {
JOptionPane.showMessageDialog(null, "You have not selected the order yet", "Error", JOptionPane.WARNING_MESSAGE);
}
}
//Save the order list
private void SaveOrderList() {
/*Session session = TicketUtil.getSessionFactory().openSession();
try
{
//Start the transaction
session.beginTransaction();
for(int i=0; i < orderList.size();i++)
{
session.save(orderList.get(i));
}
//Commit the transaction
session.getTransaction().commit();
JOptionPane.showMessageDialog (null, "The ticket book is accepted successfull", "Notice", JOptionPane.INFORMATION_MESSAGE);
}
catch (HibernateException e) {
session.getTransaction().rollback();
e.printStackTrace();
}
finally {
session.close();
}*/
try {
InfoDangKyVe[] dk = (InfoDangKyVe[])orderList.toArray();
byte[] serialObject = Serializer.serialize(dk);
BanVeTauClient.cos.write(1);
BanVeTauClient.cos.write(serialObject.length);
BanVeTauClient.cos.write(serialObject);
BanVeTauClient.cos.flush();
boolean result = BanVeTauClient.cis.readBoolean();
if(result)
{
JOptionPane.showMessageDialog(null, "The ticket book is accepted successfull", "Notice", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog(null, "The ticket book is accepted fail", "Notice", JOptionPane.ERROR_MESSAGE);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
| Java |
package clientGUI;
import banvetauclient.BanVeTauClient;
import banvetauclient.Serializer;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.IOException;
import java.util.Date;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.border.EmptyBorder;
import javax.swing.JPasswordField;
@SuppressWarnings("serial")
public class SignUp extends JFrame {
private JPanel contentPane;
private JTextField txtUser;
private JTextField txtEmail;
private JPasswordField txtPass;
/**
* Create the frame.
*/
public SignUp() {
setTitle("\u0110\u0103ng k\u00FD t\u00E0i kho\u1EA3n");
setDefaultCloseOperation(JFrame.DISPOSE_ON_CLOSE);
setBounds(100, 100, 364, 382);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
setContentPane(contentPane);
contentPane.setLayout(null);
JLabel lblNewLabel = new JLabel("T\u00EAn t\u00E0i kho\u1EA3n:");
lblNewLabel.setBounds(38, 54, 79, 14);
contentPane.add(lblNewLabel);
JLabel lblNewLabel_1 = new JLabel("M\u1EADt kh\u1EA9u:");
lblNewLabel_1.setBounds(38, 126, 62, 14);
contentPane.add(lblNewLabel_1);
txtUser = new JTextField();
txtUser.setBounds(127, 41, 197, 40);
contentPane.add(txtUser);
txtUser.setColumns(10);
JButton btnSignUp = new JButton("\u0110\u0103ng k\u00FD");
btnSignUp.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
RegAccount();
}
});
btnSignUp.setBounds(127, 258, 91, 23);
contentPane.add(btnSignUp);
JButton btnExit = new JButton("Tho\u00E1t");
btnExit.setBounds(233, 258, 91, 23);
contentPane.add(btnExit);
btnExit.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent arg0) {
CloseFrame();
}
});
JLabel Email = new JLabel("Email:");
Email.setBounds(38, 206, 62, 14);
contentPane.add(Email);
txtEmail = new JTextField();
txtEmail.setColumns(10);
txtEmail.setBounds(127, 193, 197, 40);
contentPane.add(txtEmail);
txtPass = new JPasswordField();
txtPass.setBounds(127, 113, 197, 40);
contentPane.add(txtPass);
}
private void RegAccount() {
/*String username = txtUser.getText();
//Check if user is exist
if(Login.AccountIsExist(username, null) == false)
{
Session session = TicketUtil.getSessionFactory().openSession();
try
{
//Start the transaction
session.beginTransaction();
String pass = new String(txtPass.getPassword());
String email = txtEmail.getText();
//Check if email is exist
Query queryCheckEmail = session.createQuery("FROM Users where email = :email and is_active = 1");
queryCheckEmail.setParameter("email", email);
if(queryCheckEmail.list().size() > 0)//Email is exist
{
JOptionPane.showMessageDialog (null, "Email is exits. Please type the other email", "Notice", JOptionPane.ERROR_MESSAGE);
}
else
{
//Set information for new user
Users newUser = new Users();
newUser.setUsername(username);
newUser.setPassword(pass);
newUser.setEmail(email);
newUser.setIsActive(1);
newUser.setCreated(new Date());
newUser.setActiveCode("ASXTNG");
session.save(newUser);
//Commit the transaction
session.getTransaction().commit();
}
JOptionPane.showMessageDialog (null, "Register user successfull", "Notice", JOptionPane.INFORMATION_MESSAGE);
this.dispose();
}
catch (HibernateException e) {
e.printStackTrace();
}
finally {
session.close();
}
}
else
{
JOptionPane.showMessageDialog (null, "Account is exits. Please type the other name", "Notice", JOptionPane.ERROR_MESSAGE);
}*/
try {
if(Login.AccountIsExist(txtUser.getText(), null) == false)
{
//Send account's info to register to server
String[] InfoAccount = new String[2];
InfoAccount[0] = txtUser.getText();
InfoAccount[1] = new String(txtPass.getPassword());
InfoAccount[2] = txtEmail.getText();
byte[] serialObject = Serializer.serialize(InfoAccount);
BanVeTauClient.cos.write(1);
BanVeTauClient.cos.write(serialObject.length);
BanVeTauClient.cos.write(serialObject);
BanVeTauClient.cos.flush();
System.out.println("Sent info to server");
//Confirm from server about register user
boolean result = BanVeTauClient.cis.readBoolean();
System.out.println(result);
if(result)
{
JOptionPane.showMessageDialog (null, "Register user successfull", "Notice", JOptionPane.INFORMATION_MESSAGE);
}
else
{
JOptionPane.showMessageDialog (null, "Account is exits. Please type the other name", "Notice", JOptionPane.ERROR_MESSAGE);
}
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void CloseFrame() {
this.dispose();
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dal;
import Util.HibernateUtil2;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Orders;
/**
*
* @author Sy Dai
*/
public class order {
public order() {
}
public static boolean add_order(Orders order) {
Session session = HibernateUtil2.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
session.save(order);
transaction.commit();
} catch (HibernateException ex) {
//Ghi loi vao file Log su dung Log4J
transaction.rollback();
throw new HibernateException(ex.toString());
} finally {
session.close();
}
return true;
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dal;
import Util.HibernateUtil2;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import pojo.Users;
/**
*
* @author Sy Dai
*/
public class user {
public user() {
}
public static boolean login(Users us) {
Session session = (Session) HibernateUtil2.getSessionFactory();
try {
String str_login_query = "select id from users where email='" + us.getEmail().trim() + "' and password='" + MD5(us.getPassword());
Query query = session.createQuery(str_login_query);
List lst_login = query.list();
if (!lst_login.isEmpty()) {
return true;
}
} catch (Exception ex) {
throw ex;
} finally {
session.close();
}
return false;
}
public static boolean register(Users us) {
Session session = HibernateUtil2.getSessionFactory().openSession();
Transaction transaction = null;
List lst_user = null;
try {
transaction = session.beginTransaction();
session.save(lst_user);
transaction.commit();
} catch (HibernateException ex) {
//Ghi loi vao file Log su dung Log4J
transaction.rollback();
throw new HibernateException(ex.toString());
} finally {
session.close();
}
return true;
}
public static boolean update_profile(Users us) {
Session session = HibernateUtil2.getSessionFactory().openSession();
Transaction transaction = null;
List lst_user = null;
try {
transaction = session.beginTransaction();
session.update(lst_user);
transaction.commit();
} catch (HibernateException ex) {
transaction.rollback();
throw new HibernateException(ex.toString());
} finally {
session.close();
}
return true;
}
public static String MD5(String str_input) {
try {
java.security.MessageDigest md = java.security.MessageDigest.getInstance("MD5");
byte[] array = md.digest(str_input.getBytes());
StringBuilder sb = new StringBuilder();
for (int i = 0; i < array.length; ++i) {
sb.append(Integer.toHexString((array[i] & 0xFF) | 0x100).substring(1, 3));
}
return sb.toString();
} catch (java.security.NoSuchAlgorithmException e) {
}
return null;
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package dal;
import static banvetauserver.BanVeTauServer.cis;
import static banvetauserver.BanVeTauServer.cos;
import banvetauserver.Serializer;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
/**
*
* @author Sy Dai
*/
public class connection {
public connection() {
this.connect();
}
public String connect() {
try {
ServerSocket srvSocket = new ServerSocket(10000);
System.out.println("Waiting...");
Socket client = srvSocket.accept();
System.out.println("Have client...");
cos = new ObjectOutputStream(client.getOutputStream());
cis = new ObjectInputStream(client.getInputStream());
System.out.println("Connected to stream...");
int funcNunber = cis.read();
if (funcNunber == 1) {
System.out.println("Function Login");
byte[] infoBytes = new byte[cis.read()];
cis.read(infoBytes);
String[] s = (String[]) Serializer.deserialize(infoBytes);
System.out.println(s[0] + "," + s[1]);
}
} catch (Exception e) {
e.printStackTrace();
}
return "";
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.io.IOException;
import java.io.InputStream;
/**
*
* @author XuanHung
*/
public class CipherInputStream
{
BlockCipher currentCipher;
InputStream bi;
byte[] buffer;
byte[] enc;
int blockSize;
int pos;
/*
* We cannot use java.io.BufferedInputStream, since that is not available in
* J2ME. Everything could be improved alot here.
*/
final int BUFF_SIZE = 2048;
byte[] input_buffer = new byte[BUFF_SIZE];
int input_buffer_pos = 0;
int input_buffer_size = 0;
public CipherInputStream(BlockCipher tc, InputStream bi)
{
this.bi = bi;
changeCipher(tc);
}
private int fill_buffer() throws IOException
{
input_buffer_pos = 0;
input_buffer_size = bi.read(input_buffer, 0, BUFF_SIZE);
return input_buffer_size;
}
private int internal_read(byte[] b, int off, int len) throws IOException
{
if (input_buffer_size < 0)
return -1;
if (input_buffer_pos >= input_buffer_size)
{
if (fill_buffer() <= 0)
return -1;
}
int avail = input_buffer_size - input_buffer_pos;
int thiscopy = (len > avail) ? avail : len;
System.arraycopy(input_buffer, input_buffer_pos, b, off, thiscopy);
input_buffer_pos += thiscopy;
return thiscopy;
}
public void changeCipher(BlockCipher bc)
{
this.currentCipher = bc;
blockSize = bc.getBlockSize();
buffer = new byte[blockSize];
enc = new byte[blockSize];
pos = blockSize;
}
private void getBlock() throws IOException
{
int n = 0;
while (n < blockSize)
{
int len = internal_read(enc, n, blockSize - n);
if (len < 0)
throw new IOException("Cannot read full block, EOF reached.");
n += len;
}
try
{
currentCipher.transformBlock(enc, 0, buffer, 0);
}
catch (Exception e)
{
throw new IOException("Error while decrypting block.");
}
pos = 0;
}
public int read(byte[] dst) throws IOException
{
return read(dst, 0, dst.length);
}
public int read(byte[] dst, int off, int len) throws IOException
{
int count = 0;
while (len > 0)
{
if (pos >= blockSize)
getBlock();
int avail = blockSize - pos;
int copy = Math.min(avail, len);
System.arraycopy(buffer, pos, dst, off, copy);
pos += copy;
off += copy;
len -= copy;
count += copy;
}
return count;
}
public int read() throws IOException
{
if (pos >= blockSize)
{
getBlock();
}
return buffer[pos++] & 0xff;
}
public int readPlain(byte[] b, int off, int len) throws IOException
{
if (pos != blockSize)
throw new IOException("Cannot read plain since crypto buffer is not aligned.");
int n = 0;
while (n < len)
{
int cnt = internal_read(b, off + n, len - n);
if (cnt < 0)
throw new IOException("Cannot fill buffer, EOF reached.");
n += cnt;
}
return n;
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class CBCMode implements BlockCipher
{
BlockCipher tc;
int blockSize;
boolean doEncrypt;
byte[] cbc_vector;
byte[] tmp_vector;
@Override
public void init(boolean forEncryption, byte[] key)
{
}
public CBCMode(BlockCipher tc, byte[] iv, boolean doEncrypt)
throws IllegalArgumentException
{
this.tc = tc;
this.blockSize = tc.getBlockSize();
this.doEncrypt = doEncrypt;
if (this.blockSize != iv.length)
throw new IllegalArgumentException("IV must be " + blockSize
+ " bytes long! (currently " + iv.length + ")");
this.cbc_vector = new byte[blockSize];
this.tmp_vector = new byte[blockSize];
System.arraycopy(iv, 0, cbc_vector, 0, blockSize);
}
@Override
public int getBlockSize()
{
return blockSize;
}
private void encryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
for (int i = 0; i < blockSize; i++)
cbc_vector[i] ^= src[srcoff + i];
tc.transformBlock(cbc_vector, 0, dst, dstoff);
System.arraycopy(dst, dstoff, cbc_vector, 0, blockSize);
}
private void decryptBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
/* Assume the worst, src and dst are overlapping... */
System.arraycopy(src, srcoff, tmp_vector, 0, blockSize);
tc.transformBlock(src, srcoff, dst, dstoff);
for (int i = 0; i < blockSize; i++)
dst[dstoff + i] ^= cbc_vector[i];
/* ...that is why we need a tmp buffer. */
byte[] swap = cbc_vector;
cbc_vector = tmp_vector;
tmp_vector = swap;
}
/**
*
* @param src
* @param srcoff
* @param dst
* @param dstoff
*/
@Override
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
if (doEncrypt)
encryptBlock(src, srcoff, dst, dstoff);
else
decryptBlock(src, srcoff, dst, dstoff);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class DES implements BlockCipher
{
private int[] workingKey = null;
/**
* standard constructor.
*/
public DES()
{
}
/**
* initialise a DES cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the parameters required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
@Override
public void init(boolean encrypting, byte[] key)
{
this.workingKey = generateWorkingKey(encrypting, key, 0);
}
public String getAlgorithmName()
{
return "DES";
}
@Override
public int getBlockSize()
{
return 8;
}
@Override
public void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (workingKey == null)
{
throw new IllegalStateException("DES engine not initialised!");
}
desFunc(workingKey, in, inOff, out, outOff);
}
public void reset()
{
}
/**
* what follows is mainly taken from "Applied Cryptography", by Bruce
* Schneier, however it also bears great resemblance to Richard
* Outerbridge's D3DES...
*/
static short[] Df_Key = { 0x01, 0x23, 0x45, 0x67, 0x89, 0xab, 0xcd, 0xef, 0xfe, 0xdc, 0xba, 0x98, 0x76, 0x54, 0x32,
0x10, 0x89, 0xab, 0xcd, 0xef, 0x01, 0x23, 0x45, 0x67 };
static short[] bytebit = { 0200, 0100, 040, 020, 010, 04, 02, 01 };
static int[] bigbyte = { 0x800000, 0x400000, 0x200000, 0x100000, 0x80000, 0x40000, 0x20000, 0x10000, 0x8000,
0x4000, 0x2000, 0x1000, 0x800, 0x400, 0x200, 0x100, 0x80, 0x40, 0x20, 0x10, 0x8, 0x4, 0x2, 0x1 };
/*
* Use the key schedule specified in the Standard (ANSI X3.92-1981).
*/
static byte[] pc1 = { 56, 48, 40, 32, 24, 16, 8, 0, 57, 49, 41, 33, 25, 17, 9, 1, 58, 50, 42, 34, 26, 18, 10, 2,
59, 51, 43, 35, 62, 54, 46, 38, 30, 22, 14, 6, 61, 53, 45, 37, 29, 21, 13, 5, 60, 52, 44, 36, 28, 20, 12,
4, 27, 19, 11, 3 };
static byte[] totrot = { 1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28 };
static byte[] pc2 = { 13, 16, 10, 23, 0, 4, 2, 27, 14, 5, 20, 9, 22, 18, 11, 3, 25, 7, 15, 6, 26, 19, 12, 1, 40,
51, 30, 36, 46, 54, 29, 39, 50, 44, 32, 47, 43, 48, 38, 55, 33, 52, 45, 41, 49, 35, 28, 31 };
static int[] SP1 = { 0x01010400, 0x00000000, 0x00010000, 0x01010404, 0x01010004, 0x00010404, 0x00000004,
0x00010000, 0x00000400, 0x01010400, 0x01010404, 0x00000400, 0x01000404, 0x01010004, 0x01000000, 0x00000004,
0x00000404, 0x01000400, 0x01000400, 0x00010400, 0x00010400, 0x01010000, 0x01010000, 0x01000404, 0x00010004,
0x01000004, 0x01000004, 0x00010004, 0x00000000, 0x00000404, 0x00010404, 0x01000000, 0x00010000, 0x01010404,
0x00000004, 0x01010000, 0x01010400, 0x01000000, 0x01000000, 0x00000400, 0x01010004, 0x00010000, 0x00010400,
0x01000004, 0x00000400, 0x00000004, 0x01000404, 0x00010404, 0x01010404, 0x00010004, 0x01010000, 0x01000404,
0x01000004, 0x00000404, 0x00010404, 0x01010400, 0x00000404, 0x01000400, 0x01000400, 0x00000000, 0x00010004,
0x00010400, 0x00000000, 0x01010004 };
static int[] SP2 = { 0x80108020, 0x80008000, 0x00008000, 0x00108020, 0x00100000, 0x00000020, 0x80100020,
0x80008020, 0x80000020, 0x80108020, 0x80108000, 0x80000000, 0x80008000, 0x00100000, 0x00000020, 0x80100020,
0x00108000, 0x00100020, 0x80008020, 0x00000000, 0x80000000, 0x00008000, 0x00108020, 0x80100000, 0x00100020,
0x80000020, 0x00000000, 0x00108000, 0x00008020, 0x80108000, 0x80100000, 0x00008020, 0x00000000, 0x00108020,
0x80100020, 0x00100000, 0x80008020, 0x80100000, 0x80108000, 0x00008000, 0x80100000, 0x80008000, 0x00000020,
0x80108020, 0x00108020, 0x00000020, 0x00008000, 0x80000000, 0x00008020, 0x80108000, 0x00100000, 0x80000020,
0x00100020, 0x80008020, 0x80000020, 0x00100020, 0x00108000, 0x00000000, 0x80008000, 0x00008020, 0x80000000,
0x80100020, 0x80108020, 0x00108000 };
static int[] SP3 = { 0x00000208, 0x08020200, 0x00000000, 0x08020008, 0x08000200, 0x00000000, 0x00020208,
0x08000200, 0x00020008, 0x08000008, 0x08000008, 0x00020000, 0x08020208, 0x00020008, 0x08020000, 0x00000208,
0x08000000, 0x00000008, 0x08020200, 0x00000200, 0x00020200, 0x08020000, 0x08020008, 0x00020208, 0x08000208,
0x00020200, 0x00020000, 0x08000208, 0x00000008, 0x08020208, 0x00000200, 0x08000000, 0x08020200, 0x08000000,
0x00020008, 0x00000208, 0x00020000, 0x08020200, 0x08000200, 0x00000000, 0x00000200, 0x00020008, 0x08020208,
0x08000200, 0x08000008, 0x00000200, 0x00000000, 0x08020008, 0x08000208, 0x00020000, 0x08000000, 0x08020208,
0x00000008, 0x00020208, 0x00020200, 0x08000008, 0x08020000, 0x08000208, 0x00000208, 0x08020000, 0x00020208,
0x00000008, 0x08020008, 0x00020200 };
static int[] SP4 = { 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802080, 0x00800081, 0x00800001,
0x00002001, 0x00000000, 0x00802000, 0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00800080, 0x00800001,
0x00000001, 0x00002000, 0x00800000, 0x00802001, 0x00000080, 0x00800000, 0x00002001, 0x00002080, 0x00800081,
0x00000001, 0x00002080, 0x00800080, 0x00002000, 0x00802080, 0x00802081, 0x00000081, 0x00800080, 0x00800001,
0x00802000, 0x00802081, 0x00000081, 0x00000000, 0x00000000, 0x00802000, 0x00002080, 0x00800080, 0x00800081,
0x00000001, 0x00802001, 0x00002081, 0x00002081, 0x00000080, 0x00802081, 0x00000081, 0x00000001, 0x00002000,
0x00800001, 0x00002001, 0x00802080, 0x00800081, 0x00002001, 0x00002080, 0x00800000, 0x00802001, 0x00000080,
0x00800000, 0x00002000, 0x00802080 };
static int[] SP5 = { 0x00000100, 0x02080100, 0x02080000, 0x42000100, 0x00080000, 0x00000100, 0x40000000,
0x02080000, 0x40080100, 0x00080000, 0x02000100, 0x40080100, 0x42000100, 0x42080000, 0x00080100, 0x40000000,
0x02000000, 0x40080000, 0x40080000, 0x00000000, 0x40000100, 0x42080100, 0x42080100, 0x02000100, 0x42080000,
0x40000100, 0x00000000, 0x42000000, 0x02080100, 0x02000000, 0x42000000, 0x00080100, 0x00080000, 0x42000100,
0x00000100, 0x02000000, 0x40000000, 0x02080000, 0x42000100, 0x40080100, 0x02000100, 0x40000000, 0x42080000,
0x02080100, 0x40080100, 0x00000100, 0x02000000, 0x42080000, 0x42080100, 0x00080100, 0x42000000, 0x42080100,
0x02080000, 0x00000000, 0x40080000, 0x42000000, 0x00080100, 0x02000100, 0x40000100, 0x00080000, 0x00000000,
0x40080000, 0x02080100, 0x40000100 };
static int[] SP6 = { 0x20000010, 0x20400000, 0x00004000, 0x20404010, 0x20400000, 0x00000010, 0x20404010,
0x00400000, 0x20004000, 0x00404010, 0x00400000, 0x20000010, 0x00400010, 0x20004000, 0x20000000, 0x00004010,
0x00000000, 0x00400010, 0x20004010, 0x00004000, 0x00404000, 0x20004010, 0x00000010, 0x20400010, 0x20400010,
0x00000000, 0x00404010, 0x20404000, 0x00004010, 0x00404000, 0x20404000, 0x20000000, 0x20004000, 0x00000010,
0x20400010, 0x00404000, 0x20404010, 0x00400000, 0x00004010, 0x20000010, 0x00400000, 0x20004000, 0x20000000,
0x00004010, 0x20000010, 0x20404010, 0x00404000, 0x20400000, 0x00404010, 0x20404000, 0x00000000, 0x20400010,
0x00000010, 0x00004000, 0x20400000, 0x00404010, 0x00004000, 0x00400010, 0x20004010, 0x00000000, 0x20404000,
0x20000000, 0x00400010, 0x20004010 };
static int[] SP7 = { 0x00200000, 0x04200002, 0x04000802, 0x00000000, 0x00000800, 0x04000802, 0x00200802,
0x04200800, 0x04200802, 0x00200000, 0x00000000, 0x04000002, 0x00000002, 0x04000000, 0x04200002, 0x00000802,
0x04000800, 0x00200802, 0x00200002, 0x04000800, 0x04000002, 0x04200000, 0x04200800, 0x00200002, 0x04200000,
0x00000800, 0x00000802, 0x04200802, 0x00200800, 0x00000002, 0x04000000, 0x00200800, 0x04000000, 0x00200800,
0x00200000, 0x04000802, 0x04000802, 0x04200002, 0x04200002, 0x00000002, 0x00200002, 0x04000000, 0x04000800,
0x00200000, 0x04200800, 0x00000802, 0x00200802, 0x04200800, 0x00000802, 0x04000002, 0x04200802, 0x04200000,
0x00200800, 0x00000000, 0x00000002, 0x04200802, 0x00000000, 0x00200802, 0x04200000, 0x00000800, 0x04000002,
0x04000800, 0x00000800, 0x00200002 };
static int[] SP8 = { 0x10001040, 0x00001000, 0x00040000, 0x10041040, 0x10000000, 0x10001040, 0x00000040,
0x10000000, 0x00040040, 0x10040000, 0x10041040, 0x00041000, 0x10041000, 0x00041040, 0x00001000, 0x00000040,
0x10040000, 0x10000040, 0x10001000, 0x00001040, 0x00041000, 0x00040040, 0x10040040, 0x10041000, 0x00001040,
0x00000000, 0x00000000, 0x10040040, 0x10000040, 0x10001000, 0x00041040, 0x00040000, 0x00041040, 0x00040000,
0x10041000, 0x00001000, 0x00000040, 0x10040040, 0x00001000, 0x00041040, 0x10001000, 0x00000040, 0x10000040,
0x10040000, 0x10040040, 0x10000000, 0x00040000, 0x10001040, 0x00000000, 0x10041040, 0x00040040, 0x10000040,
0x10040000, 0x10001000, 0x10001040, 0x00000000, 0x10041040, 0x00041000, 0x00041000, 0x00001040, 0x00001040,
0x00040040, 0x10000000, 0x10041000 };
/**
* generate an integer based working key based on our secret key and what we
* processing we are planning to do.
*
* Acknowledgements for this routine go to James Gillogly & Phil Karn.
* (whoever, and wherever they are!).
*/
protected int[] generateWorkingKey(boolean encrypting, byte[] key, int off)
{
int[] newKey = new int[32];
boolean[] pc1m = new boolean[56], pcr = new boolean[56];
for (int j = 0; j < 56; j++)
{
int l = pc1[j];
pc1m[j] = ((key[off + (l >>> 3)] & bytebit[l & 07]) != 0);
}
for (int i = 0; i < 16; i++)
{
int l, m, n;
if (encrypting)
{
m = i << 1;
}
else
{
m = (15 - i) << 1;
}
n = m + 1;
newKey[m] = newKey[n] = 0;
for (int j = 0; j < 28; j++)
{
l = j + totrot[i];
if (l < 28)
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 28; j < 56; j++)
{
l = j + totrot[i];
if (l < 56)
{
pcr[j] = pc1m[l];
}
else
{
pcr[j] = pc1m[l - 28];
}
}
for (int j = 0; j < 24; j++)
{
if (pcr[pc2[j]])
{
newKey[m] |= bigbyte[j];
}
if (pcr[pc2[j + 24]])
{
newKey[n] |= bigbyte[j];
}
}
}
//
// store the processed key
//
for (int i = 0; i != 32; i += 2)
{
int i1, i2;
i1 = newKey[i];
i2 = newKey[i + 1];
newKey[i] = ((i1 & 0x00fc0000) << 6) | ((i1 & 0x00000fc0) << 10) | ((i2 & 0x00fc0000) >>> 10)
| ((i2 & 0x00000fc0) >>> 6);
newKey[i + 1] = ((i1 & 0x0003f000) << 12) | ((i1 & 0x0000003f) << 16) | ((i2 & 0x0003f000) >>> 4)
| (i2 & 0x0000003f);
}
return newKey;
}
/**
* the DES engine.
*/
protected void desFunc(int[] wKey, byte[] in, int inOff, byte[] out, int outOff)
{
int work, right, left;
left = (in[inOff + 0] & 0xff) << 24;
left |= (in[inOff + 1] & 0xff) << 16;
left |= (in[inOff + 2] & 0xff) << 8;
left |= (in[inOff + 3] & 0xff);
right = (in[inOff + 4] & 0xff) << 24;
right |= (in[inOff + 5] & 0xff) << 16;
right |= (in[inOff + 6] & 0xff) << 8;
right |= (in[inOff + 7] & 0xff);
work = ((left >>> 4) ^ right) & 0x0f0f0f0f;
right ^= work;
left ^= (work << 4);
work = ((left >>> 16) ^ right) & 0x0000ffff;
right ^= work;
left ^= (work << 16);
work = ((right >>> 2) ^ left) & 0x33333333;
left ^= work;
right ^= (work << 2);
work = ((right >>> 8) ^ left) & 0x00ff00ff;
left ^= work;
right ^= (work << 8);
right = ((right << 1) | ((right >>> 31) & 1)) & 0xffffffff;
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = ((left << 1) | ((left >>> 31) & 1)) & 0xffffffff;
for (int round = 0; round < 8; round++)
{
int fval;
work = (right << 28) | (right >>> 4);
work ^= wKey[round * 4 + 0];
fval = SP7[work & 0x3f];
fval |= SP5[(work >>> 8) & 0x3f];
fval |= SP3[(work >>> 16) & 0x3f];
fval |= SP1[(work >>> 24) & 0x3f];
work = right ^ wKey[round * 4 + 1];
fval |= SP8[work & 0x3f];
fval |= SP6[(work >>> 8) & 0x3f];
fval |= SP4[(work >>> 16) & 0x3f];
fval |= SP2[(work >>> 24) & 0x3f];
left ^= fval;
work = (left << 28) | (left >>> 4);
work ^= wKey[round * 4 + 2];
fval = SP7[work & 0x3f];
fval |= SP5[(work >>> 8) & 0x3f];
fval |= SP3[(work >>> 16) & 0x3f];
fval |= SP1[(work >>> 24) & 0x3f];
work = left ^ wKey[round * 4 + 3];
fval |= SP8[work & 0x3f];
fval |= SP6[(work >>> 8) & 0x3f];
fval |= SP4[(work >>> 16) & 0x3f];
fval |= SP2[(work >>> 24) & 0x3f];
right ^= fval;
}
right = (right << 31) | (right >>> 1);
work = (left ^ right) & 0xaaaaaaaa;
left ^= work;
right ^= work;
left = (left << 31) | (left >>> 1);
work = ((left >>> 8) ^ right) & 0x00ff00ff;
right ^= work;
left ^= (work << 8);
work = ((left >>> 2) ^ right) & 0x33333333;
right ^= work;
left ^= (work << 2);
work = ((right >>> 16) ^ left) & 0x0000ffff;
left ^= work;
right ^= (work << 16);
work = ((right >>> 4) ^ left) & 0x0f0f0f0f;
left ^= work;
right ^= (work << 4);
out[outOff + 0] = (byte) ((right >>> 24) & 0xff);
out[outOff + 1] = (byte) ((right >>> 16) & 0xff);
out[outOff + 2] = (byte) ((right >>> 8) & 0xff);
out[outOff + 3] = (byte) (right & 0xff);
out[outOff + 4] = (byte) ((left >>> 24) & 0xff);
out[outOff + 5] = (byte) ((left >>> 16) & 0xff);
out[outOff + 6] = (byte) ((left >>> 8) & 0xff);
out[outOff + 7] = (byte) (left & 0xff);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class CTRMode implements BlockCipher
{
byte[] X;
byte[] Xenc;
BlockCipher bc;
int blockSize;
boolean doEncrypt;
int count = 0;
@Override
public void init(boolean forEncryption, byte[] key)
{
}
public CTRMode(BlockCipher tc, byte[] iv, boolean doEnc) throws IllegalArgumentException
{
bc = tc;
blockSize = bc.getBlockSize();
doEncrypt = doEnc;
if (blockSize != iv.length)
throw new IllegalArgumentException("IV must be " + blockSize + " bytes long! (currently " + iv.length + ")");
X = new byte[blockSize];
Xenc = new byte[blockSize];
System.arraycopy(iv, 0, X, 0, blockSize);
}
@Override
public final int getBlockSize()
{
return blockSize;
}
@Override
public final void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
bc.transformBlock(X, 0, Xenc, 0);
for (int i = 0; i < blockSize; i++)
{
dst[dstoff + i] = (byte) (src[srcoff + i] ^ Xenc[i]);
}
for (int i = (blockSize - 1); i >= 0; i--)
{
X[i]++;
if (X[i] != 0)
break;
}
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.io.*;
/**
*
* @author XuanHung
*/
public class CipherOutputStream
{
BlockCipher currentCipher;
OutputStream bo;
byte[] buffer;
byte[] enc;
int blockSize;
int pos;
/*
* We cannot use java.io.BufferedOutputStream, since that is not available
* in J2ME. Everything could be improved here alot.
*/
final int BUFF_SIZE = 2048;
byte[] out_buffer = new byte[BUFF_SIZE];
int out_buffer_pos = 0;
public CipherOutputStream(BlockCipher tc, OutputStream bo)
{
this.bo = bo;
changeCipher(tc);
}
private void internal_write(byte[] src, int off, int len) throws IOException
{
while (len > 0)
{
int space = BUFF_SIZE - out_buffer_pos;
int copy = (len > space) ? space : len;
System.arraycopy(src, off, out_buffer, out_buffer_pos, copy);
off += copy;
out_buffer_pos += copy;
len -= copy;
if (out_buffer_pos >= BUFF_SIZE)
{
bo.write(out_buffer, 0, BUFF_SIZE);
out_buffer_pos = 0;
}
}
}
private void internal_write(int b) throws IOException
{
out_buffer[out_buffer_pos++] = (byte) b;
if (out_buffer_pos >= BUFF_SIZE)
{
bo.write(out_buffer, 0, BUFF_SIZE);
out_buffer_pos = 0;
}
}
public void flush() throws IOException
{
if (pos != 0)
throw new IOException("FATAL: cannot flush since crypto buffer is not aligned.");
if (out_buffer_pos > 0)
{
bo.write(out_buffer, 0, out_buffer_pos);
out_buffer_pos = 0;
}
bo.flush();
}
public void changeCipher(BlockCipher bc)
{
this.currentCipher = bc;
blockSize = bc.getBlockSize();
buffer = new byte[blockSize];
enc = new byte[blockSize];
pos = 0;
}
private void writeBlock() throws IOException
{
try
{
currentCipher.transformBlock(buffer, 0, enc, 0);
}
catch (Exception e)
{
throw (IOException) new IOException("Error while decrypting block.").initCause(e);
}
internal_write(enc, 0, blockSize);
pos = 0;
}
public void write(byte[] src, int off, int len) throws IOException
{
while (len > 0)
{
int avail = blockSize - pos;
int copy = Math.min(avail, len);
System.arraycopy(src, off, buffer, pos, copy);
pos += copy;
off += copy;
len -= copy;
if (pos >= blockSize)
writeBlock();
}
}
public void write(int b) throws IOException
{
buffer[pos++] = (byte) b;
if (pos >= blockSize)
writeBlock();
}
public void writePlain(int b) throws IOException
{
if (pos != 0)
throw new IOException("Cannot write plain since crypto buffer is not aligned.");
internal_write(b);
}
public void writePlain(byte[] b, int off, int len) throws IOException
{
if (pos != 0)
throw new IOException("Cannot write plain since crypto buffer is not aligned.");
internal_write(b, off, len);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.util.Vector;
/**
*
* @author XuanHung
*/
public class BlockCipherFactory
{
static class CipherEntry
{
String type;
int blocksize;
int keysize;
String cipherClass;
public CipherEntry(String type, int blockSize, int keySize, String cipherClass)
{
this.type = type;
this.blocksize = blockSize;
this.keysize = keySize;
this.cipherClass = cipherClass;
}
}
static Vector<CipherEntry> ciphers = new Vector<>();
static
{
/* Higher Priority First */
ciphers.addElement(new CipherEntry("aes256-ctr", 16, 32, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes192-ctr", 16, 24, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes128-ctr", 16, 16, "encrypt.AES"));
ciphers.addElement(new CipherEntry("blowfish-ctr", 8, 16, "encrypt.BlowFish"));
ciphers.addElement(new CipherEntry("aes256-cbc", 16, 32, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes192-cbc", 16, 24, "encrypt.AES"));
ciphers.addElement(new CipherEntry("aes128-cbc", 16, 16, "encrypt.AES"));
ciphers.addElement(new CipherEntry("blowfish-cbc", 8, 16, "encrypt.BlowFish"));
ciphers.addElement(new CipherEntry("3des-ctr", 8, 24, "encrypt.DESede"));
ciphers.addElement(new CipherEntry("3des-cbc", 8, 24, "encrypt.DESede"));
}
public static String[] getDefaultCipherList()
{
String list[] = new String[ciphers.size()];
for (int i = 0; i < ciphers.size(); i++)
{
CipherEntry ce = ciphers.elementAt(i);
list[i] = ce.type;
}
return list;
}
public static void checkCipherList(String[] cipherCandidates)
{
for (String cipherCandidate : cipherCandidates) {
getEntry(cipherCandidate);
}
}
public static BlockCipher createCipher(String type, boolean encrypt, byte[] key, byte[] iv)
{
try
{
CipherEntry ce = getEntry(type);
Class cc = Class.forName(ce.cipherClass);
BlockCipher bc = (BlockCipher) cc.newInstance();
if (type.endsWith("-cbc"))
{
bc.init(encrypt, key);
return new CBCMode(bc, iv, encrypt);
}
else if (type.endsWith("-ctr"))
{
bc.init(true, key);
return new CTRMode(bc, iv, encrypt);
}
throw new IllegalArgumentException("Cannot instantiate " + type);
}
catch (ClassNotFoundException | InstantiationException | IllegalAccessException | IllegalArgumentException e)
{
throw new IllegalArgumentException("Cannot instantiate " + type);
}
}
private static CipherEntry getEntry(String type)
{
for (int i = 0; i < ciphers.size(); i++)
{
CipherEntry ce = ciphers.elementAt(i);
if (ce.type.equals(type))
return ce;
}
throw new IllegalArgumentException("Unkown algorithm " + type);
}
public static int getBlockSize(String type)
{
CipherEntry ce = getEntry(type);
return ce.blocksize;
}
public static int getKeySize(String type)
{
CipherEntry ce = getEntry(type);
return ce.keysize;
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public interface BlockCipher
{
public void init(boolean forEncryption, byte[] key);
public int getBlockSize();
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff);
} | Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
import java.security.PublicKey;
/**
*
* @author XuanHung
*/
class pkCipher {
static void init(int ENCRYPT_MODE, PublicKey pk) {
throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates.
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class DESede extends DES
{
private int[] key1 = null;
private int[] key2 = null;
private int[] key3 = null;
private boolean encrypt;
/**
* standard constructor.
*/
public DESede()
{
}
/**
* initialise a DES cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the parameters required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
@Override
public void init(boolean encrypting, byte[] key)
{
key1 = generateWorkingKey(encrypting, key, 0);
key2 = generateWorkingKey(!encrypting, key, 8);
key3 = generateWorkingKey(encrypting, key, 16);
encrypt = encrypting;
}
@Override
public String getAlgorithmName()
{
return "DESede";
}
/**
*
* @return
*/
@Override
public int getBlockSize()
{
return 8;
}
@Override
public void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (key1 == null)
{
throw new IllegalStateException("DESede engine not initialised!");
}
if (encrypt)
{
desFunc(key1, in, inOff, out, outOff);
desFunc(key2, out, outOff, out, outOff);
desFunc(key3, out, outOff, out, outOff);
}
else
{
desFunc(key3, in, inOff, out, outOff);
desFunc(key2, out, outOff, out, outOff);
desFunc(key1, out, outOff, out, outOff);
}
}
@Override
public void reset()
{
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class BlowFish implements BlockCipher
{
private final static int[] KP = { 0x243F6A88, 0x85A308D3, 0x13198A2E, 0x03707344, 0xA4093822, 0x299F31D0,
0x082EFA98, 0xEC4E6C89, 0x452821E6, 0x38D01377, 0xBE5466CF, 0x34E90C6C, 0xC0AC29B7, 0xC97C50DD, 0x3F84D5B5,
0xB5470917, 0x9216D5D9, 0x8979FB1B },
KS0 = { 0xD1310BA6, 0x98DFB5AC, 0x2FFD72DB, 0xD01ADFB7, 0xB8E1AFED, 0x6A267E96, 0xBA7C9045, 0xF12C7F99, 0x24A19947,
0xB3916CF7, 0x0801F2E2, 0x858EFC16, 0x636920D8, 0x71574E69, 0xA458FEA3, 0xF4933D7E, 0x0D95748F, 0x728EB658,
0x718BCD58, 0x82154AEE, 0x7B54A41D, 0xC25A59B5, 0x9C30D539, 0x2AF26013, 0xC5D1B023, 0x286085F0, 0xCA417918,
0xB8DB38EF, 0x8E79DCB0, 0x603A180E, 0x6C9E0E8B, 0xB01E8A3E, 0xD71577C1, 0xBD314B27, 0x78AF2FDA, 0x55605C60,
0xE65525F3, 0xAA55AB94, 0x57489862, 0x63E81440, 0x55CA396A, 0x2AAB10B6, 0xB4CC5C34, 0x1141E8CE, 0xA15486AF,
0x7C72E993, 0xB3EE1411, 0x636FBC2A, 0x2BA9C55D, 0x741831F6, 0xCE5C3E16, 0x9B87931E, 0xAFD6BA33, 0x6C24CF5C,
0x7A325381, 0x28958677, 0x3B8F4898, 0x6B4BB9AF, 0xC4BFE81B, 0x66282193, 0x61D809CC, 0xFB21A991, 0x487CAC60,
0x5DEC8032, 0xEF845D5D, 0xE98575B1, 0xDC262302, 0xEB651B88, 0x23893E81, 0xD396ACC5, 0x0F6D6FF3, 0x83F44239,
0x2E0B4482, 0xA4842004, 0x69C8F04A, 0x9E1F9B5E, 0x21C66842, 0xF6E96C9A, 0x670C9C61, 0xABD388F0, 0x6A51A0D2,
0xD8542F68, 0x960FA728, 0xAB5133A3, 0x6EEF0B6C, 0x137A3BE4, 0xBA3BF050, 0x7EFB2A98, 0xA1F1651D, 0x39AF0176,
0x66CA593E, 0x82430E88, 0x8CEE8619, 0x456F9FB4, 0x7D84A5C3, 0x3B8B5EBE, 0xE06F75D8, 0x85C12073, 0x401A449F,
0x56C16AA6, 0x4ED3AA62, 0x363F7706, 0x1BFEDF72, 0x429B023D, 0x37D0D724, 0xD00A1248, 0xDB0FEAD3, 0x49F1C09B,
0x075372C9, 0x80991B7B, 0x25D479D8, 0xF6E8DEF7, 0xE3FE501A, 0xB6794C3B, 0x976CE0BD, 0x04C006BA, 0xC1A94FB6,
0x409F60C4, 0x5E5C9EC2, 0x196A2463, 0x68FB6FAF, 0x3E6C53B5, 0x1339B2EB, 0x3B52EC6F, 0x6DFC511F, 0x9B30952C,
0xCC814544, 0xAF5EBD09, 0xBEE3D004, 0xDE334AFD, 0x660F2807, 0x192E4BB3, 0xC0CBA857, 0x45C8740F, 0xD20B5F39,
0xB9D3FBDB, 0x5579C0BD, 0x1A60320A, 0xD6A100C6, 0x402C7279, 0x679F25FE, 0xFB1FA3CC, 0x8EA5E9F8, 0xDB3222F8,
0x3C7516DF, 0xFD616B15, 0x2F501EC8, 0xAD0552AB, 0x323DB5FA, 0xFD238760, 0x53317B48, 0x3E00DF82, 0x9E5C57BB,
0xCA6F8CA0, 0x1A87562E, 0xDF1769DB, 0xD542A8F6, 0x287EFFC3, 0xAC6732C6, 0x8C4F5573, 0x695B27B0, 0xBBCA58C8,
0xE1FFA35D, 0xB8F011A0, 0x10FA3D98, 0xFD2183B8, 0x4AFCB56C, 0x2DD1D35B, 0x9A53E479, 0xB6F84565, 0xD28E49BC,
0x4BFB9790, 0xE1DDF2DA, 0xA4CB7E33, 0x62FB1341, 0xCEE4C6E8, 0xEF20CADA, 0x36774C01, 0xD07E9EFE, 0x2BF11FB4,
0x95DBDA4D, 0xAE909198, 0xEAAD8E71, 0x6B93D5A0, 0xD08ED1D0, 0xAFC725E0, 0x8E3C5B2F, 0x8E7594B7, 0x8FF6E2FB,
0xF2122B64, 0x8888B812, 0x900DF01C, 0x4FAD5EA0, 0x688FC31C, 0xD1CFF191, 0xB3A8C1AD, 0x2F2F2218, 0xBE0E1777,
0xEA752DFE, 0x8B021FA1, 0xE5A0CC0F, 0xB56F74E8, 0x18ACF3D6, 0xCE89E299, 0xB4A84FE0, 0xFD13E0B7, 0x7CC43B81,
0xD2ADA8D9, 0x165FA266, 0x80957705, 0x93CC7314, 0x211A1477, 0xE6AD2065, 0x77B5FA86, 0xC75442F5, 0xFB9D35CF,
0xEBCDAF0C, 0x7B3E89A0, 0xD6411BD3, 0xAE1E7E49, 0x00250E2D, 0x2071B35E, 0x226800BB, 0x57B8E0AF, 0x2464369B,
0xF009B91E, 0x5563911D, 0x59DFA6AA, 0x78C14389, 0xD95A537F, 0x207D5BA2, 0x02E5B9C5, 0x83260376, 0x6295CFA9,
0x11C81968, 0x4E734A41, 0xB3472DCA, 0x7B14A94A, 0x1B510052, 0x9A532915, 0xD60F573F, 0xBC9BC6E4, 0x2B60A476,
0x81E67400, 0x08BA6FB5, 0x571BE91F, 0xF296EC6B, 0x2A0DD915, 0xB6636521, 0xE7B9F9B6, 0xFF34052E, 0xC5855664,
0x53B02D5D, 0xA99F8FA1, 0x08BA4799, 0x6E85076A },
KS1 = { 0x4B7A70E9, 0xB5B32944, 0xDB75092E, 0xC4192623, 0xAD6EA6B0, 0x49A7DF7D, 0x9CEE60B8, 0x8FEDB266, 0xECAA8C71,
0x699A17FF, 0x5664526C, 0xC2B19EE1, 0x193602A5, 0x75094C29, 0xA0591340, 0xE4183A3E, 0x3F54989A, 0x5B429D65,
0x6B8FE4D6, 0x99F73FD6, 0xA1D29C07, 0xEFE830F5, 0x4D2D38E6, 0xF0255DC1, 0x4CDD2086, 0x8470EB26, 0x6382E9C6,
0x021ECC5E, 0x09686B3F, 0x3EBAEFC9, 0x3C971814, 0x6B6A70A1, 0x687F3584, 0x52A0E286, 0xB79C5305, 0xAA500737,
0x3E07841C, 0x7FDEAE5C, 0x8E7D44EC, 0x5716F2B8, 0xB03ADA37, 0xF0500C0D, 0xF01C1F04, 0x0200B3FF, 0xAE0CF51A,
0x3CB574B2, 0x25837A58, 0xDC0921BD, 0xD19113F9, 0x7CA92FF6, 0x94324773, 0x22F54701, 0x3AE5E581, 0x37C2DADC,
0xC8B57634, 0x9AF3DDA7, 0xA9446146, 0x0FD0030E, 0xECC8C73E, 0xA4751E41, 0xE238CD99, 0x3BEA0E2F, 0x3280BBA1,
0x183EB331, 0x4E548B38, 0x4F6DB908, 0x6F420D03, 0xF60A04BF, 0x2CB81290, 0x24977C79, 0x5679B072, 0xBCAF89AF,
0xDE9A771F, 0xD9930810, 0xB38BAE12, 0xDCCF3F2E, 0x5512721F, 0x2E6B7124, 0x501ADDE6, 0x9F84CD87, 0x7A584718,
0x7408DA17, 0xBC9F9ABC, 0xE94B7D8C, 0xEC7AEC3A, 0xDB851DFA, 0x63094366, 0xC464C3D2, 0xEF1C1847, 0x3215D908,
0xDD433B37, 0x24C2BA16, 0x12A14D43, 0x2A65C451, 0x50940002, 0x133AE4DD, 0x71DFF89E, 0x10314E55, 0x81AC77D6,
0x5F11199B, 0x043556F1, 0xD7A3C76B, 0x3C11183B, 0x5924A509, 0xF28FE6ED, 0x97F1FBFA, 0x9EBABF2C, 0x1E153C6E,
0x86E34570, 0xEAE96FB1, 0x860E5E0A, 0x5A3E2AB3, 0x771FE71C, 0x4E3D06FA, 0x2965DCB9, 0x99E71D0F, 0x803E89D6,
0x5266C825, 0x2E4CC978, 0x9C10B36A, 0xC6150EBA, 0x94E2EA78, 0xA5FC3C53, 0x1E0A2DF4, 0xF2F74EA7, 0x361D2B3D,
0x1939260F, 0x19C27960, 0x5223A708, 0xF71312B6, 0xEBADFE6E, 0xEAC31F66, 0xE3BC4595, 0xA67BC883, 0xB17F37D1,
0x018CFF28, 0xC332DDEF, 0xBE6C5AA5, 0x65582185, 0x68AB9802, 0xEECEA50F, 0xDB2F953B, 0x2AEF7DAD, 0x5B6E2F84,
0x1521B628, 0x29076170, 0xECDD4775, 0x619F1510, 0x13CCA830, 0xEB61BD96, 0x0334FE1E, 0xAA0363CF, 0xB5735C90,
0x4C70A239, 0xD59E9E0B, 0xCBAADE14, 0xEECC86BC, 0x60622CA7, 0x9CAB5CAB, 0xB2F3846E, 0x648B1EAF, 0x19BDF0CA,
0xA02369B9, 0x655ABB50, 0x40685A32, 0x3C2AB4B3, 0x319EE9D5, 0xC021B8F7, 0x9B540B19, 0x875FA099, 0x95F7997E,
0x623D7DA8, 0xF837889A, 0x97E32D77, 0x11ED935F, 0x16681281, 0x0E358829, 0xC7E61FD6, 0x96DEDFA1, 0x7858BA99,
0x57F584A5, 0x1B227263, 0x9B83C3FF, 0x1AC24696, 0xCDB30AEB, 0x532E3054, 0x8FD948E4, 0x6DBC3128, 0x58EBF2EF,
0x34C6FFEA, 0xFE28ED61, 0xEE7C3C73, 0x5D4A14D9, 0xE864B7E3, 0x42105D14, 0x203E13E0, 0x45EEE2B6, 0xA3AAABEA,
0xDB6C4F15, 0xFACB4FD0, 0xC742F442, 0xEF6ABBB5, 0x654F3B1D, 0x41CD2105, 0xD81E799E, 0x86854DC7, 0xE44B476A,
0x3D816250, 0xCF62A1F2, 0x5B8D2646, 0xFC8883A0, 0xC1C7B6A3, 0x7F1524C3, 0x69CB7492, 0x47848A0B, 0x5692B285,
0x095BBF00, 0xAD19489D, 0x1462B174, 0x23820E00, 0x58428D2A, 0x0C55F5EA, 0x1DADF43E, 0x233F7061, 0x3372F092,
0x8D937E41, 0xD65FECF1, 0x6C223BDB, 0x7CDE3759, 0xCBEE7460, 0x4085F2A7, 0xCE77326E, 0xA6078084, 0x19F8509E,
0xE8EFD855, 0x61D99735, 0xA969A7AA, 0xC50C06C2, 0x5A04ABFC, 0x800BCADC, 0x9E447A2E, 0xC3453484, 0xFDD56705,
0x0E1E9EC9, 0xDB73DBD3, 0x105588CD, 0x675FDA79, 0xE3674340, 0xC5C43465, 0x713E38D8, 0x3D28F89E, 0xF16DFF20,
0x153E21E7, 0x8FB03D4A, 0xE6E39F2B, 0xDB83ADF7 },
KS2 = { 0xE93D5A68, 0x948140F7, 0xF64C261C, 0x94692934, 0x411520F7, 0x7602D4F7, 0xBCF46B2E, 0xD4A20068, 0xD4082471,
0x3320F46A, 0x43B7D4B7, 0x500061AF, 0x1E39F62E, 0x97244546, 0x14214F74, 0xBF8B8840, 0x4D95FC1D, 0x96B591AF,
0x70F4DDD3, 0x66A02F45, 0xBFBC09EC, 0x03BD9785, 0x7FAC6DD0, 0x31CB8504, 0x96EB27B3, 0x55FD3941, 0xDA2547E6,
0xABCA0A9A, 0x28507825, 0x530429F4, 0x0A2C86DA, 0xE9B66DFB, 0x68DC1462, 0xD7486900, 0x680EC0A4, 0x27A18DEE,
0x4F3FFEA2, 0xE887AD8C, 0xB58CE006, 0x7AF4D6B6, 0xAACE1E7C, 0xD3375FEC, 0xCE78A399, 0x406B2A42, 0x20FE9E35,
0xD9F385B9, 0xEE39D7AB, 0x3B124E8B, 0x1DC9FAF7, 0x4B6D1856, 0x26A36631, 0xEAE397B2, 0x3A6EFA74, 0xDD5B4332,
0x6841E7F7, 0xCA7820FB, 0xFB0AF54E, 0xD8FEB397, 0x454056AC, 0xBA489527, 0x55533A3A, 0x20838D87, 0xFE6BA9B7,
0xD096954B, 0x55A867BC, 0xA1159A58, 0xCCA92963, 0x99E1DB33, 0xA62A4A56, 0x3F3125F9, 0x5EF47E1C, 0x9029317C,
0xFDF8E802, 0x04272F70, 0x80BB155C, 0x05282CE3, 0x95C11548, 0xE4C66D22, 0x48C1133F, 0xC70F86DC, 0x07F9C9EE,
0x41041F0F, 0x404779A4, 0x5D886E17, 0x325F51EB, 0xD59BC0D1, 0xF2BCC18F, 0x41113564, 0x257B7834, 0x602A9C60,
0xDFF8E8A3, 0x1F636C1B, 0x0E12B4C2, 0x02E1329E, 0xAF664FD1, 0xCAD18115, 0x6B2395E0, 0x333E92E1, 0x3B240B62,
0xEEBEB922, 0x85B2A20E, 0xE6BA0D99, 0xDE720C8C, 0x2DA2F728, 0xD0127845, 0x95B794FD, 0x647D0862, 0xE7CCF5F0,
0x5449A36F, 0x877D48FA, 0xC39DFD27, 0xF33E8D1E, 0x0A476341, 0x992EFF74, 0x3A6F6EAB, 0xF4F8FD37, 0xA812DC60,
0xA1EBDDF8, 0x991BE14C, 0xDB6E6B0D, 0xC67B5510, 0x6D672C37, 0x2765D43B, 0xDCD0E804, 0xF1290DC7, 0xCC00FFA3,
0xB5390F92, 0x690FED0B, 0x667B9FFB, 0xCEDB7D9C, 0xA091CF0B, 0xD9155EA3, 0xBB132F88, 0x515BAD24, 0x7B9479BF,
0x763BD6EB, 0x37392EB3, 0xCC115979, 0x8026E297, 0xF42E312D, 0x6842ADA7, 0xC66A2B3B, 0x12754CCC, 0x782EF11C,
0x6A124237, 0xB79251E7, 0x06A1BBE6, 0x4BFB6350, 0x1A6B1018, 0x11CAEDFA, 0x3D25BDD8, 0xE2E1C3C9, 0x44421659,
0x0A121386, 0xD90CEC6E, 0xD5ABEA2A, 0x64AF674E, 0xDA86A85F, 0xBEBFE988, 0x64E4C3FE, 0x9DBC8057, 0xF0F7C086,
0x60787BF8, 0x6003604D, 0xD1FD8346, 0xF6381FB0, 0x7745AE04, 0xD736FCCC, 0x83426B33, 0xF01EAB71, 0xB0804187,
0x3C005E5F, 0x77A057BE, 0xBDE8AE24, 0x55464299, 0xBF582E61, 0x4E58F48F, 0xF2DDFDA2, 0xF474EF38, 0x8789BDC2,
0x5366F9C3, 0xC8B38E74, 0xB475F255, 0x46FCD9B9, 0x7AEB2661, 0x8B1DDF84, 0x846A0E79, 0x915F95E2, 0x466E598E,
0x20B45770, 0x8CD55591, 0xC902DE4C, 0xB90BACE1, 0xBB8205D0, 0x11A86248, 0x7574A99E, 0xB77F19B6, 0xE0A9DC09,
0x662D09A1, 0xC4324633, 0xE85A1F02, 0x09F0BE8C, 0x4A99A025, 0x1D6EFE10, 0x1AB93D1D, 0x0BA5A4DF, 0xA186F20F,
0x2868F169, 0xDCB7DA83, 0x573906FE, 0xA1E2CE9B, 0x4FCD7F52, 0x50115E01, 0xA70683FA, 0xA002B5C4, 0x0DE6D027,
0x9AF88C27, 0x773F8641, 0xC3604C06, 0x61A806B5, 0xF0177A28, 0xC0F586E0, 0x006058AA, 0x30DC7D62, 0x11E69ED7,
0x2338EA63, 0x53C2DD94, 0xC2C21634, 0xBBCBEE56, 0x90BCB6DE, 0xEBFC7DA1, 0xCE591D76, 0x6F05E409, 0x4B7C0188,
0x39720A3D, 0x7C927C24, 0x86E3725F, 0x724D9DB9, 0x1AC15BB4, 0xD39EB8FC, 0xED545578, 0x08FCA5B5, 0xD83D7CD3,
0x4DAD0FC4, 0x1E50EF5E, 0xB161E6F8, 0xA28514D9, 0x6C51133C, 0x6FD5C7E7, 0x56E14EC4, 0x362ABFCE, 0xDDC6C837,
0xD79A3234, 0x92638212, 0x670EFA8E, 0x406000E0 },
KS3 = { 0x3A39CE37, 0xD3FAF5CF, 0xABC27737, 0x5AC52D1B, 0x5CB0679E, 0x4FA33742, 0xD3822740, 0x99BC9BBE, 0xD5118E9D,
0xBF0F7315, 0xD62D1C7E, 0xC700C47B, 0xB78C1B6B, 0x21A19045, 0xB26EB1BE, 0x6A366EB4, 0x5748AB2F, 0xBC946E79,
0xC6A376D2, 0x6549C2C8, 0x530FF8EE, 0x468DDE7D, 0xD5730A1D, 0x4CD04DC6, 0x2939BBDB, 0xA9BA4650, 0xAC9526E8,
0xBE5EE304, 0xA1FAD5F0, 0x6A2D519A, 0x63EF8CE2, 0x9A86EE22, 0xC089C2B8, 0x43242EF6, 0xA51E03AA, 0x9CF2D0A4,
0x83C061BA, 0x9BE96A4D, 0x8FE51550, 0xBA645BD6, 0x2826A2F9, 0xA73A3AE1, 0x4BA99586, 0xEF5562E9, 0xC72FEFD3,
0xF752F7DA, 0x3F046F69, 0x77FA0A59, 0x80E4A915, 0x87B08601, 0x9B09E6AD, 0x3B3EE593, 0xE990FD5A, 0x9E34D797,
0x2CF0B7D9, 0x022B8B51, 0x96D5AC3A, 0x017DA67D, 0xD1CF3ED6, 0x7C7D2D28, 0x1F9F25CF, 0xADF2B89B, 0x5AD6B472,
0x5A88F54C, 0xE029AC71, 0xE019A5E6, 0x47B0ACFD, 0xED93FA9B, 0xE8D3C48D, 0x283B57CC, 0xF8D56629, 0x79132E28,
0x785F0191, 0xED756055, 0xF7960E44, 0xE3D35E8C, 0x15056DD4, 0x88F46DBA, 0x03A16125, 0x0564F0BD, 0xC3EB9E15,
0x3C9057A2, 0x97271AEC, 0xA93A072A, 0x1B3F6D9B, 0x1E6321F5, 0xF59C66FB, 0x26DCF319, 0x7533D928, 0xB155FDF5,
0x03563482, 0x8ABA3CBB, 0x28517711, 0xC20AD9F8, 0xABCC5167, 0xCCAD925F, 0x4DE81751, 0x3830DC8E, 0x379D5862,
0x9320F991, 0xEA7A90C2, 0xFB3E7BCE, 0x5121CE64, 0x774FBE32, 0xA8B6E37E, 0xC3293D46, 0x48DE5369, 0x6413E680,
0xA2AE0810, 0xDD6DB224, 0x69852DFD, 0x09072166, 0xB39A460A, 0x6445C0DD, 0x586CDECF, 0x1C20C8AE, 0x5BBEF7DD,
0x1B588D40, 0xCCD2017F, 0x6BB4E3BB, 0xDDA26A7E, 0x3A59FF45, 0x3E350A44, 0xBCB4CDD5, 0x72EACEA8, 0xFA6484BB,
0x8D6612AE, 0xBF3C6F47, 0xD29BE463, 0x542F5D9E, 0xAEC2771B, 0xF64E6370, 0x740E0D8D, 0xE75B1357, 0xF8721671,
0xAF537D5D, 0x4040CB08, 0x4EB4E2CC, 0x34D2466A, 0x0115AF84, 0xE1B00428, 0x95983A1D, 0x06B89FB4, 0xCE6EA048,
0x6F3F3B82, 0x3520AB82, 0x011A1D4B, 0x277227F8, 0x611560B1, 0xE7933FDC, 0xBB3A792B, 0x344525BD, 0xA08839E1,
0x51CE794B, 0x2F32C9B7, 0xA01FBAC9, 0xE01CC87E, 0xBCC7D1F6, 0xCF0111C3, 0xA1E8AAC7, 0x1A908749, 0xD44FBD9A,
0xD0DADECB, 0xD50ADA38, 0x0339C32A, 0xC6913667, 0x8DF9317C, 0xE0B12B4F, 0xF79E59B7, 0x43F5BB3A, 0xF2D519FF,
0x27D9459C, 0xBF97222C, 0x15E6FC2A, 0x0F91FC71, 0x9B941525, 0xFAE59361, 0xCEB69CEB, 0xC2A86459, 0x12BAA8D1,
0xB6C1075E, 0xE3056A0C, 0x10D25065, 0xCB03A442, 0xE0EC6E0E, 0x1698DB3B, 0x4C98A0BE, 0x3278E964, 0x9F1F9532,
0xE0D392DF, 0xD3A0342B, 0x8971F21E, 0x1B0A7441, 0x4BA3348C, 0xC5BE7120, 0xC37632D8, 0xDF359F8D, 0x9B992F2E,
0xE60B6F47, 0x0FE3F11D, 0xE54CDA54, 0x1EDAD891, 0xCE6279CF, 0xCD3E7E6F, 0x1618B166, 0xFD2C1D05, 0x848FD2C5,
0xF6FB2299, 0xF523F357, 0xA6327623, 0x93A83531, 0x56CCCD02, 0xACF08162, 0x5A75EBB5, 0x6E163697, 0x88D273CC,
0xDE966292, 0x81B949D0, 0x4C50901B, 0x71C65614, 0xE6C6C7BD, 0x327A140A, 0x45E1D006, 0xC3F27B9A, 0xC9AA53FD,
0x62A80F00, 0xBB25BFE2, 0x35BDD2F6, 0x71126905, 0xB2040222, 0xB6CBCF7C, 0xCD769C2B, 0x53113EC0, 0x1640E3D3,
0x38ABBD60, 0x2547ADF0, 0xBA38209C, 0xF746CE76, 0x77AFA1C5, 0x20756060, 0x85CBFE4E, 0x8AE88DD8, 0x7AAAF9B0,
0x4CF9AA7E, 0x1948C25C, 0x02FB8A8C, 0x01C36AE4, 0xD6EBE1F9, 0x90D4F869, 0xA65CDEA0, 0x3F09252D, 0xC208E69F,
0xB74E6132, 0xCE77E25B, 0x578FDFE3, 0x3AC372E6 };
// ====================================
// Useful constants
// ====================================
private static final int ROUNDS = 16;
private static final int BLOCK_SIZE = 8; // bytes = 64 bits
private static final int SBOX_SK = 256;
private static final int P_SZ = ROUNDS + 2;
private final int[] S0, S1, S2, S3; // the s-boxes
private final int[] P; // the p-array
private boolean doEncrypt = false;
private byte[] workingKey = null;
public BlowFish()
{
S0 = new int[SBOX_SK];
S1 = new int[SBOX_SK];
S2 = new int[SBOX_SK];
S3 = new int[SBOX_SK];
P = new int[P_SZ];
}
/**
* initialise a Blowfish cipher.
*
* @param encrypting
* whether or not we are for encryption.
* @param key
* the key required to set up the cipher.
* @exception IllegalArgumentException
* if the params argument is inappropriate.
*/
public void init(boolean encrypting, byte[] key)
{
this.doEncrypt = encrypting;
this.workingKey = key;
setKey(this.workingKey);
}
public String getAlgorithmName()
{
return "Blowfish";
}
public final void transformBlock(byte[] in, int inOff, byte[] out, int outOff)
{
if (workingKey == null)
{
throw new IllegalStateException("Blowfish not initialised");
}
if (doEncrypt)
{
encryptBlock(in, inOff, out, outOff);
}
else
{
decryptBlock(in, inOff, out, outOff);
}
}
public void reset()
{
}
public int getBlockSize()
{
return BLOCK_SIZE;
}
// ==================================
// Private Implementation
// ==================================
private int F(int x)
{
return (((S0[(x >>> 24)] + S1[(x >>> 16) & 0xff]) ^ S2[(x >>> 8) & 0xff]) + S3[x & 0xff]);
}
/**
* apply the encryption cycle to each value pair in the table.
*/
private void processTable(int xl, int xr, int[] table)
{
int size = table.length;
for (int s = 0; s < size; s += 2)
{
xl ^= P[0];
for (int i = 1; i < ROUNDS; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[ROUNDS + 1];
table[s] = xr;
table[s + 1] = xl;
xr = xl; // end of cycle swap
xl = table[s];
}
}
private void setKey(byte[] key)
{
/*
* - comments are from _Applied Crypto_, Schneier, p338 please be
* careful comparing the two, AC numbers the arrays from 1, the enclosed
* code from 0.
*
* (1) Initialise the S-boxes and the P-array, with a fixed string This
* string contains the hexadecimal digits of pi (3.141...)
*/
System.arraycopy(KS0, 0, S0, 0, SBOX_SK);
System.arraycopy(KS1, 0, S1, 0, SBOX_SK);
System.arraycopy(KS2, 0, S2, 0, SBOX_SK);
System.arraycopy(KS3, 0, S3, 0, SBOX_SK);
System.arraycopy(KP, 0, P, 0, P_SZ);
/*
* (2) Now, XOR P[0] with the first 32 bits of the key, XOR P[1] with
* the second 32-bits of the key, and so on for all bits of the key (up
* to P[17]). Repeatedly cycle through the key bits until the entire
* P-array has been XOR-ed with the key bits
*/
int keyLength = key.length;
int keyIndex = 0;
for (int i = 0; i < P_SZ; i++)
{
// get the 32 bits of the key, in 4 * 8 bit chunks
int data = 0x0000000;
for (int j = 0; j < 4; j++)
{
// create a 32 bit block
data = (data << 8) | (key[keyIndex++] & 0xff);
// wrap when we get to the end of the key
if (keyIndex >= keyLength)
{
keyIndex = 0;
}
}
// XOR the newly created 32 bit chunk onto the P-array
P[i] ^= data;
}
/*
* (3) Encrypt the all-zero string with the Blowfish algorithm, using
* the subkeys described in (1) and (2)
*
* (4) Replace P1 and P2 with the output of step (3)
*
* (5) Encrypt the output of step(3) using the Blowfish algorithm, with
* the modified subkeys.
*
* (6) Replace P3 and P4 with the output of step (5)
*
* (7) Continue the process, replacing all elements of the P-array and
* then all four S-boxes in order, with the output of the continuously
* changing Blowfish algorithm
*/
processTable(0, 0, P);
processTable(P[P_SZ - 2], P[P_SZ - 1], S0);
processTable(S0[SBOX_SK - 2], S0[SBOX_SK - 1], S1);
processTable(S1[SBOX_SK - 2], S1[SBOX_SK - 1], S2);
processTable(S2[SBOX_SK - 2], S2[SBOX_SK - 1], S3);
}
/**
* Encrypt the given input starting at the given offset and place the result
* in the provided buffer starting at the given offset. The input will be an
* exact multiple of our blocksize.
*/
private void encryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[0];
for (int i = 1; i < ROUNDS; i += 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i + 1];
}
xr ^= P[ROUNDS + 1];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
/**
* Decrypt the given input starting at the given offset and place the result
* in the provided buffer starting at the given offset. The input will be an
* exact multiple of our blocksize.
*/
private void decryptBlock(byte[] src, int srcIndex, byte[] dst, int dstIndex)
{
int xl = BytesTo32bits(src, srcIndex);
int xr = BytesTo32bits(src, srcIndex + 4);
xl ^= P[ROUNDS + 1];
for (int i = ROUNDS; i > 0; i -= 2)
{
xr ^= F(xl) ^ P[i];
xl ^= F(xr) ^ P[i - 1];
}
xr ^= P[0];
Bits32ToBytes(xr, dst, dstIndex);
Bits32ToBytes(xl, dst, dstIndex + 4);
}
private int BytesTo32bits(byte[] b, int i)
{
return ((b[i] & 0xff) << 24) | ((b[i + 1] & 0xff) << 16) | ((b[i + 2] & 0xff) << 8) | ((b[i + 3] & 0xff));
}
private void Bits32ToBytes(int in, byte[] b, int offset)
{
b[offset + 3] = (byte) in;
b[offset + 2] = (byte) (in >> 8);
b[offset + 1] = (byte) (in >> 16);
b[offset] = (byte) (in >> 24);
}
}
| Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package encrypt;
/**
*
* @author XuanHung
*/
public class NullCipher implements BlockCipher
{
private int blockSize = 8;
public NullCipher()
{
}
public NullCipher(int blockSize)
{
this.blockSize = blockSize;
}
@Override
public void init(boolean forEncryption, byte[] key)
{
}
@Override
public int getBlockSize()
{
return blockSize;
}
@Override
public void transformBlock(byte[] src, int srcoff, byte[] dst, int dstoff)
{
System.arraycopy(src, srcoff, dst, dstoff, blockSize);
}
}
| Java |
package Util;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import org.hibernate.cfg.AnnotationConfiguration;
import org.hibernate.SessionFactory;
/**
* Hibernate Utility class with a convenient method to get Session Factory
* object.
*
* @author Sy Dai
*/
public class HibernateUtil2 {
private static final SessionFactory sessionFactory;
static {
try {
// Create the SessionFactory from standard (hibernate.cfg.xml)
// config file.
sessionFactory = new AnnotationConfiguration().configure().buildSessionFactory();
} catch (Throwable ex) {
// Log the exception.
System.err.println("Initial SessionFactory creation failed." + ex);
throw new ExceptionInInitializerError(ex);
}
}
public static SessionFactory getSessionFactory() {
return sessionFactory;
}
}
| Java |
package banvetauserver;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
public class Serializer {
public static byte[] serialize(Object obj) throws IOException {
ByteArrayOutputStream b = new ByteArrayOutputStream();
ObjectOutputStream o = new ObjectOutputStream(b);
o.writeObject(obj);
return b.toByteArray();
}
public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
ByteArrayInputStream b = new ByteArrayInputStream(bytes);
ObjectInputStream o = new ObjectInputStream(b);
return o.readObject();
}
} | Java |
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
package banvetauserver;
import dal.user;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.ServerSocket;
import java.net.Socket;
import pojo.Orders;
import pojo.Users;
/**
*
* @author XuanHung
*/
public class BanVeTauServer {
public static ServerSocket srvSocket = null;
public static ObjectInputStream cis = null;
public static ObjectOutputStream cos = null;
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
try {
ServerSocket srvSocket = new ServerSocket(10000);
System.out.println("Waiting...");
Socket client = srvSocket.accept();
System.out.println("Have client...");
cos = new ObjectOutputStream(client.getOutputStream());
cis = new ObjectInputStream(client.getInputStream());
System.out.println("Connected to stream...");
int funcNunber = cis.read();
if (funcNunber == 1) {
System.out.println("Login Function");
byte[] infoBytes = new byte[cis.read()];
cis.read(infoBytes);
String[] s = (String[]) Serializer.deserialize(infoBytes);
System.out.println(s[0] + "," + s[1]);
pojo.Users us = new Users();
us.setEmail(s[0]);
us.setPassword(user.MD5(s[1]));
boolean result = dal.user.login(us);
cos.writeBoolean(result);
} else if (funcNunber == 2) {
System.out.println("Register Function");
byte[] infoBytes = new byte[cis.read()];
cis.read(infoBytes);
String[] s = (String[]) Serializer.deserialize(infoBytes);
System.out.println(s[0] + "," + s[1]);
pojo.Users us = new Users();
us.setEmail(s[0]);
us.setPassword(user.MD5(s[1]));
boolean result = dal.user.register(us);
cos.writeBoolean(result);
} else if (funcNunber == 2) {
System.out.println("Buy Ticket Function");
byte[] infoBytes = new byte[cis.read()];
cis.read(infoBytes);
String[] s = (String[]) Serializer.deserialize(infoBytes);
System.out.println(s[0] + "," + s[1]);
pojo.Orders ord = new Orders();
ord.setTrain_id(Integer.parseInt(s[0]));
ord.setAmount(Integer.parseInt(s[1]));
ord.setTotal(Double.parseDouble(s[1]));
boolean result = dal.order.add_order(ord);
} else {
System.out.println("Logout Function");
byte[] infoBytes = new byte[cis.read()];
cis.read(infoBytes);
String[] s = (String[]) Serializer.deserialize(infoBytes);
System.out.println(s[0] + "," + s[1]);
}
} catch (Exception e) {
e.printStackTrace();
}
//process
// dal.user us = new user();
// pojo.Users user = new pojo.Users();
// us.login(user);
}
}
| Java |
package CommonObject;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author admin
*/
public class InfoChuyenTau implements java.io.Serializable {
public int IdChuyenDi;
public String TenChuyen;
public String TenGaDi;
public String TenGaDen;
public String TenLoaiGhe;
public double Price;
public String ToString()
{
return TenChuyen;
}
}
| Java |
package CommonObject;
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
*
* @author admin
*/
public class InfoDangKyVe implements java.io.Serializable {
public int TrainId;
public int Ammount;
public double Total;
}
| Java |
package pl.polidea.sectionedlist;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;
/**
* Example activity.
*/
public class SectionListActivity extends Activity {
private class StandardArrayAdapter extends ArrayAdapter<SectionListItem> {
private final SectionListItem[] items;
public StandardArrayAdapter(final Context context,
final int textViewResourceId, final SectionListItem[] items) {
super(context, textViewResourceId, items);
this.items = items;
}
@Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
View view = convertView;
if (view == null) {
final LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.example_list_view, null);
}
final SectionListItem currentItem = items[position];
if (currentItem != null) {
final TextView textView = (TextView) view
.findViewById(R.id.example_text_view);
if (textView != null) {
textView.setText(currentItem.item.toString());
}
}
return view;
}
}
SectionListItem[] exampleArray = { // Comment to prevent re-format
new SectionListItem("Test 1 - A", "A"), //
new SectionListItem("Test 2 - A", "A"), //
new SectionListItem("Test 3 - A", "A"), //
new SectionListItem("Test 4 - A", "A"), //
new SectionListItem("Test 5 - A", "A"), //
new SectionListItem("Test 6 - B", "B"), //
new SectionListItem("Test 7 - B", "B"), //
new SectionListItem("Test 8 - B", "B"), //
new SectionListItem("Test 9 - Long", "Long section"), //
new SectionListItem("Test 10 - Long", "Long section"), //
new SectionListItem("Test 11 - Long", "Long section"), //
new SectionListItem("Test 12 - Long", "Long section"), //
new SectionListItem("Test 13 - Long", "Long section"), //
new SectionListItem("Test 14 - A again", "A"), //
new SectionListItem("Test 15 - A again", "A"), //
new SectionListItem("Test 16 - A again", "A"), //
new SectionListItem("Test 17 - B again", "B"), //
new SectionListItem("Test 18 - B again", "B"), //
new SectionListItem("Test 19 - B again", "B"), //
new SectionListItem("Test 20 - B again", "B"), //
new SectionListItem("Test 21 - B again", "B"), //
new SectionListItem("Test 22 - B again", "B"), //
new SectionListItem("Test 23 - C", "C"), //
new SectionListItem("Test 24 - C", "C"), //
new SectionListItem("Test 25 - C", "C"), //
new SectionListItem("Test 26 - C", "C"), //
};
private StandardArrayAdapter arrayAdapter;
private SectionListAdapter sectionAdapter;
private SectionListView listView;
@Override
public void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrayAdapter = new StandardArrayAdapter(this, R.id.example_text_view,
exampleArray);
sectionAdapter = new SectionListAdapter(getLayoutInflater(),
arrayAdapter);
listView = (SectionListView) findViewById(getResources().getIdentifier(
"section_list_view", "id",
this.getClass().getPackage().getName()));
listView.setAdapter(sectionAdapter);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.test_menu, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.standard_list:
arrayAdapter = new StandardArrayAdapter(this,
R.id.example_text_view, exampleArray);
sectionAdapter = new SectionListAdapter(getLayoutInflater(),
arrayAdapter);
listView.setAdapter(sectionAdapter);
return true;
case R.id.empty_list:
arrayAdapter = new StandardArrayAdapter(this,
R.id.example_text_view, new SectionListItem[] {});
sectionAdapter = new SectionListAdapter(getLayoutInflater(),
arrayAdapter);
listView.setAdapter(sectionAdapter);
return true;
default:
return super.onOptionsItemSelected(item);
}
}
} | Java |
/**
* Provides simple implementation of section list.
*/
package pl.polidea.sectionedlist; | Java |
package pl.polidea.sectionedlist;
/**
* Item definition including the section.
*/
public class SectionListItem {
public Object item;
public String section;
public SectionListItem(final Object item, final String section) {
super();
this.item = item;
this.section = section;
}
@Override
public String toString() {
return item.toString();
}
}
| Java |
package pl.polidea.sectionedlist;
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewParent;
import android.widget.AbsListView;
import android.widget.AbsListView.OnScrollListener;
import android.widget.FrameLayout;
import android.widget.ListAdapter;
import android.widget.ListView;
/**
* View displaying the list with sectioned header.
*/
public class SectionListView extends ListView implements OnScrollListener {
private View transparentView;
public SectionListView(final Context context, final AttributeSet attrs,
final int defStyle) {
super(context, attrs, defStyle);
commonInitialisation();
}
public SectionListView(final Context context, final AttributeSet attrs) {
super(context, attrs);
commonInitialisation();
}
public SectionListView(final Context context) {
super(context);
commonInitialisation();
}
protected final void commonInitialisation() {
setOnScrollListener(this);
setVerticalFadingEdgeEnabled(false);
setFadingEdgeLength(0);
}
@Override
public void setAdapter(final ListAdapter adapter) {
if (!(adapter instanceof SectionListAdapter)) {
throw new IllegalArgumentException(
"The adapter needds to be of type "
+ SectionListAdapter.class + " and is "
+ adapter.getClass());
}
super.setAdapter(adapter);
final ViewParent parent = getParent();
if (!(parent instanceof FrameLayout)) {
throw new IllegalStateException(
"Section List should have FrameLayout as parent!");
}
if (transparentView != null) {
((FrameLayout) parent).removeView(transparentView);
}
transparentView = ((SectionListAdapter) adapter)
.getTransparentSectionView();
final FrameLayout.LayoutParams lp = new FrameLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
((FrameLayout) parent).addView(transparentView, lp);
if (adapter.isEmpty()) {
transparentView.setVisibility(View.INVISIBLE);
}
}
@Override
public void onScroll(final AbsListView view, final int firstVisibleItem,
final int visibleItemCount, final int totalItemCount) {
final SectionListAdapter adapter = (SectionListAdapter) getAdapter();
if (adapter != null) {
adapter.makeSectionInvisibleIfFirstInList(firstVisibleItem);
}
}
@Override
public void onScrollStateChanged(final AbsListView view,
final int scrollState) {
// do nothing
}
}
| Java |
package pl.polidea.sectionedlist;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Map.Entry;
import android.database.DataSetObserver;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
/**
* Adapter for sections.
*/
public class SectionListAdapter extends BaseAdapter implements ListAdapter,
OnItemClickListener {
private final DataSetObserver dataSetObserver = new DataSetObserver() {
@Override
public void onChanged() {
super.onChanged();
updateSessionCache();
}
@Override
public void onInvalidated() {
super.onInvalidated();
updateSessionCache();
};
};
private final ListAdapter linkedAdapter;
private final Map<Integer, String> sectionPositions = new LinkedHashMap<Integer, String>();
private final Map<Integer, Integer> itemPositions = new LinkedHashMap<Integer, Integer>();
private final Map<View, String> currentViewSections = new HashMap<View, String>();
private int viewTypeCount;
protected final LayoutInflater inflater;
private View transparentSectionView;
private OnItemClickListener linkedListener;
public SectionListAdapter(final LayoutInflater inflater,
final ListAdapter linkedAdapter) {
this.linkedAdapter = linkedAdapter;
this.inflater = inflater;
linkedAdapter.registerDataSetObserver(dataSetObserver);
updateSessionCache();
}
private boolean isTheSame(final String previousSection,
final String newSection) {
if (previousSection == null) {
return newSection == null;
} else {
return previousSection.equals(newSection);
}
}
private synchronized void updateSessionCache() {
int currentPosition = 0;
sectionPositions.clear();
itemPositions.clear();
viewTypeCount = linkedAdapter.getViewTypeCount() + 1;
String currentSection = null;
final int count = linkedAdapter.getCount();
for (int i = 0; i < count; i++) {
final SectionListItem item = (SectionListItem) linkedAdapter
.getItem(i);
if (!isTheSame(currentSection, item.section)) {
sectionPositions.put(currentPosition, item.section);
currentSection = item.section;
currentPosition++;
}
itemPositions.put(currentPosition, i);
currentPosition++;
}
}
@Override
public synchronized int getCount() {
return sectionPositions.size() + itemPositions.size();
}
@Override
public synchronized Object getItem(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
final int linkedItemPosition = getLinkedPosition(position);
return linkedAdapter.getItem(linkedItemPosition);
}
}
public synchronized boolean isSection(final int position) {
return sectionPositions.containsKey(position);
}
public synchronized String getSectionName(final int position) {
if (isSection(position)) {
return sectionPositions.get(position);
} else {
return null;
}
}
@Override
public long getItemId(final int position) {
if (isSection(position)) {
return sectionPositions.get(position).hashCode();
} else {
return linkedAdapter.getItemId(getLinkedPosition(position));
}
}
protected Integer getLinkedPosition(final int position) {
return itemPositions.get(position);
}
@Override
public int getItemViewType(final int position) {
if (isSection(position)) {
return viewTypeCount - 1;
}
return linkedAdapter.getItemViewType(getLinkedPosition(position));
}
private View getSectionView(final View convertView, final String section) {
View theView = convertView;
if (theView == null) {
theView = createNewSectionView();
}
setSectionText(section, theView);
replaceSectionViewsInMaps(section, theView);
return theView;
}
protected void setSectionText(final String section, final View sectionView) {
final TextView textView = (TextView) sectionView
.findViewById(R.id.listTextView);
textView.setText(section);
}
protected synchronized void replaceSectionViewsInMaps(final String section,
final View theView) {
if (currentViewSections.containsKey(theView)) {
currentViewSections.remove(theView);
}
currentViewSections.put(theView, section);
}
protected View createNewSectionView() {
return inflater.inflate(R.layout.section_view, null);
}
@Override
public View getView(final int position, final View convertView,
final ViewGroup parent) {
if (isSection(position)) {
return getSectionView(convertView, sectionPositions.get(position));
}
return linkedAdapter.getView(getLinkedPosition(position), convertView,
parent);
}
@Override
public int getViewTypeCount() {
return viewTypeCount;
}
@Override
public boolean hasStableIds() {
return linkedAdapter.hasStableIds();
}
@Override
public boolean isEmpty() {
return linkedAdapter.isEmpty();
}
@Override
public void registerDataSetObserver(final DataSetObserver observer) {
linkedAdapter.registerDataSetObserver(observer);
}
@Override
public void unregisterDataSetObserver(final DataSetObserver observer) {
linkedAdapter.unregisterDataSetObserver(observer);
}
@Override
public boolean areAllItemsEnabled() {
return linkedAdapter.areAllItemsEnabled();
}
@Override
public boolean isEnabled(final int position) {
if (isSection(position)) {
return true;
}
return linkedAdapter.isEnabled(getLinkedPosition(position));
}
public void makeSectionInvisibleIfFirstInList(final int firstVisibleItem) {
final String section = getSectionName(firstVisibleItem);
// only make invisible the first section with that name in case there
// are more with the same name
boolean alreadySetFirstSectionIvisible = false;
for (final Entry<View, String> itemView : currentViewSections
.entrySet()) {
if (itemView.getValue().equals(section)
&& !alreadySetFirstSectionIvisible) {
itemView.getKey().setVisibility(View.INVISIBLE);
alreadySetFirstSectionIvisible = true;
} else {
itemView.getKey().setVisibility(View.VISIBLE);
}
}
for (final Entry<Integer, String> entry : sectionPositions.entrySet()) {
if (entry.getKey() > firstVisibleItem + 1) {
break;
}
setSectionText(entry.getValue(), getTransparentSectionView());
}
}
public synchronized View getTransparentSectionView() {
if (transparentSectionView == null) {
transparentSectionView = createNewSectionView();
}
return transparentSectionView;
}
protected void sectionClicked(final String section) {
// do nothing
}
@Override
public void onItemClick(final AdapterView< ? > parent, final View view,
final int position, final long id) {
if (isSection(position)) {
sectionClicked(getSectionName(position));
} else if (linkedListener != null) {
linkedListener.onItemClick(parent, view,
getLinkedPosition(position), id);
}
}
public void setOnItemClickListener(final OnItemClickListener linkedListener) {
this.linkedListener = linkedListener;
}
}
| Java |
package com.thimbleware.jmemcached;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.Set;
import java.util.Map;
import java.util.HashMap;
import java.util.HashSet;
import static java.lang.String.*;
/**
* Abstract implementation of a cache handler for the memcache daemon; provides some convenience methods and
* a general framework for implementation
*/
public abstract class AbstractCache<CACHE_ELEMENT extends CacheElement> implements Cache<CACHE_ELEMENT> {
protected final AtomicLong started = new AtomicLong();
protected final AtomicInteger getCmds = new AtomicInteger();
protected final AtomicInteger setCmds = new AtomicInteger();
protected final AtomicInteger getHits = new AtomicInteger();
protected final AtomicInteger getMisses = new AtomicInteger();
protected final AtomicLong casCounter = new AtomicLong(1);
public AbstractCache() {
initStats();
}
/**
* @return the current time in seconds (from epoch), used for expiries, etc.
*/
public static int Now() {
return (int) (System.currentTimeMillis());
}
protected abstract Set<Key> keys();
public abstract long getCurrentItems();
public abstract long getLimitMaxBytes();
public abstract long getCurrentBytes();
public final int getGetCmds() {
return getCmds.get();
}
public final int getSetCmds() {
return setCmds.get();
}
public final int getGetHits() {
return getHits.get();
}
public final int getGetMisses() {
return getMisses.get();
}
/**
* Return runtime statistics
*
* @param arg additional arguments to the stats command
* @return the full command response
*/
public final Map<String, Set<String>> stat(String arg) {
Map<String, Set<String>> result = new HashMap<String, Set<String>>();
// stats we know
multiSet(result, "version", MemCacheDaemon.memcachedVersion);
multiSet(result, "cmd_gets", valueOf(getGetCmds()));
multiSet(result, "cmd_sets", valueOf(getSetCmds()));
multiSet(result, "get_hits", valueOf(getGetHits()));
multiSet(result, "get_misses", valueOf(getGetMisses()));
multiSet(result, "time", valueOf(valueOf(Now())));
multiSet(result, "uptime", valueOf(Now() - this.started.longValue()));
multiSet(result, "cur_items", valueOf(this.getCurrentItems()));
multiSet(result, "limit_maxbytes", valueOf(this.getLimitMaxBytes()));
multiSet(result, "current_bytes", valueOf(this.getCurrentBytes()));
multiSet(result, "free_bytes", valueOf(Runtime.getRuntime().freeMemory()));
// Not really the same thing precisely, but meaningful nonetheless. potentially this should be renamed
multiSet(result, "pid", valueOf(Thread.currentThread().getId()));
// stuff we know nothing about; gets faked only because some clients expect this
multiSet(result, "rusage_user", "0:0");
multiSet(result, "rusage_system", "0:0");
multiSet(result, "connection_structures", "0");
// TODO we could collect these stats
multiSet(result, "bytes_read", "0");
multiSet(result, "bytes_written", "0");
return result;
}
private void multiSet(Map<String, Set<String>> map, String key, String val) {
Set<String> cur = map.get(key);
if (cur == null) {
cur = new HashSet<String>();
}
cur.add(val);
map.put(key, cur);
}
/**
* Initialize all statistic counters
*/
protected void initStats() {
started.set(System.currentTimeMillis());
// getCmds.set(0);
// setCmds.set(0);
// getHits.set(0);
// getMisses.set(0);
}
public abstract void asyncEventPing();
}
| Java |
package com.thimbleware.jmemcached.protocol;
import com.thimbleware.jmemcached.Cache;
import com.thimbleware.jmemcached.CacheElement;
import java.io.Serializable;
import java.util.Set;
import java.util.Map;
/**
* Represents the response to a command.
*/
public final class ResponseMessage<CACHE_ELEMENT extends CacheElement> implements Serializable {
public ResponseMessage(CommandMessage cmd) {
this.cmd = cmd;
}
public CommandMessage<CACHE_ELEMENT> cmd;
public CACHE_ELEMENT[] elements;
public Cache.StoreResponse response;
public Map<String, Set<String>> stats;
public String version;
public Cache.DeleteResponse deleteResponse;
public Integer incrDecrResponse;
public boolean flushSuccess;
public ResponseMessage<CACHE_ELEMENT> withElements(CACHE_ELEMENT[] elements) {
this.elements = elements;
return this;
}
public ResponseMessage<CACHE_ELEMENT> withResponse(Cache.StoreResponse response) {
this.response = response;
return this;
}
public ResponseMessage<CACHE_ELEMENT> withDeleteResponse(Cache.DeleteResponse deleteResponse) {
this.deleteResponse = deleteResponse;
return this;
}
public ResponseMessage<CACHE_ELEMENT> withIncrDecrResponse(Integer incrDecrResp) {
this.incrDecrResponse = incrDecrResp;
return this;
}
public ResponseMessage<CACHE_ELEMENT> withStatResponse(Map<String, Set<String>> stats) {
this.stats = stats;
return this;
}
public ResponseMessage<CACHE_ELEMENT> withFlushResponse(boolean success) {
this.flushSuccess = success;
return this;
}
}
| Java |
package com.thimbleware.jmemcached.protocol.exceptions;
/**
*/
public class MalformedCommandException extends ClientException {
public MalformedCommandException() {
}
public MalformedCommandException(String s) {
super(s);
}
public MalformedCommandException(String s, Throwable throwable) {
super(s, throwable);
}
public MalformedCommandException(Throwable throwable) {
super(throwable);
}
} | Java |
package com.thimbleware.jmemcached.protocol.exceptions;
/**
*/
public class IncorrectlyTerminatedPayloadException extends ClientException {
public IncorrectlyTerminatedPayloadException() {
}
public IncorrectlyTerminatedPayloadException(String s) {
super(s);
}
public IncorrectlyTerminatedPayloadException(String s, Throwable throwable) {
super(s, throwable);
}
public IncorrectlyTerminatedPayloadException(Throwable throwable) {
super(throwable);
}
}
| Java |
package com.thimbleware.jmemcached.protocol.exceptions;
/**
*/
public class UnknownCommandException extends ClientException {
public UnknownCommandException() {
}
public UnknownCommandException(String s) {
super(s);
}
public UnknownCommandException(String s, Throwable throwable) {
super(s, throwable);
}
public UnknownCommandException(Throwable throwable) {
super(throwable);
}
}
| Java |
package com.thimbleware.jmemcached.protocol.exceptions;
/**
*/
public class InvalidProtocolStateException extends Exception {
public InvalidProtocolStateException() {
}
public InvalidProtocolStateException(String s) {
super(s);
}
public InvalidProtocolStateException(String s, Throwable throwable) {
super(s, throwable);
}
public InvalidProtocolStateException(Throwable throwable) {
super(throwable);
}
}
| Java |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.