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.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*&lt;any char except "=", ",", ";", &lt;"&gt; and * white space&gt; * quoted-string = &lt;"&gt; *( text | quoted-char ) &lt;"&gt; * text = any char except &lt;"&gt; * 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. &copy; */ 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. &copy; */ 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, &lt;!DOCTYPE&gt;, or internal DTD).</DD> * <DT>Element</DT> * <DD>All element names are uppercased.</DD> * <DD>Empty elements are written as <code>&lt;BR&gt;</code> instead of <code>&lt;BR/&gt;</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. &copy; * @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 &quot;1&quot;. * <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. &copy; */ 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. &copy; */ 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. &copy; */ 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 com.vercer.engine.persist.festival; import java.util.LinkedList; import java.util.List; import java.util.Locale; import com.vercer.engine.persist.annotation.Child; import com.vercer.engine.persist.annotation.Id; public class Band { enum HairStyle { LONG_LIKE_A_GIRL, UNKEMPT_FLOPPY, NAVY_SHORT, BALD }; @Id String name; Locale locale; LinkedList<Musician> members = new LinkedList<Musician>(); @Child List<Album> albums; Band.HairStyle hair; @Override public String toString() { return "Band [albums=" + albums + ", hair=" + hair + ", locale=" + locale + ", members=" + members + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((albums == null) ? 0 : albums.hashCode()); result = prime * result + ((hair == null) ? 0 : hair.hashCode()); result = prime * result + ((locale == null) ? 0 : locale.hashCode()); result = prime * result + ((members == null) ? 0 : members.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Band)) { return false; } Band other = (Band) obj; if (albums == null) { if (other.albums != null) { return false; } } else if (!albums.equals(other.albums)) { return false; } if (hair == null) { if (other.hair != null) { return false; } } else if (!hair.equals(other.hair)) { return false; } if (locale == null) { if (other.locale != null) { return false; } } else if (!locale.equals(other.locale)) { return false; } if (members == null) { if (other.members != null) { return false; } } else if (!members.equals(other.members)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } }
Java
/** * */ package com.vercer.engine.persist.festival; import java.util.Arrays; import java.util.Date; import com.google.appengine.api.datastore.Text; import com.vercer.engine.persist.annotation.Embed; import com.vercer.engine.persist.annotation.Id; import com.vercer.engine.persist.annotation.Type; public class Album { @Id String name; String label; // @Entity(Relationship.PARENT) // Band band; Date released; boolean rocksTheHouse; long sold; @Embed Track[] tracks; public static class Track { @Override public String toString() { return "Track [details=" + details + ", length=" + length + ", title=" + title + "]"; } public static class SingleDetails { String bside; int released; } @Type(Text.class) String title; float length; SingleDetails details; @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + Float.floatToIntBits(length); result = prime * result + ((title == null) ? 0 : title.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Track)) { return false; } Track other = (Track) obj; if (Float.floatToIntBits(length) != Float.floatToIntBits(other.length)) { return false; } if (title == null) { if (other.title != null) { return false; } } else if (!title.equals(other.title)) { return false; } return true; } } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); // result = prime * result + ((band == null) ? 0 : band.hashCode()); result = prime * result + ((label == null) ? 0 : label.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); result = prime * result + ((released == null) ? 0 : released.hashCode()); result = prime * result + (rocksTheHouse ? 1231 : 1237); result = prime * result + (int) (sold ^ (sold >>> 32)); result = prime * result + Arrays.hashCode(tracks); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof Album)) { return false; } Album other = (Album) obj; if (label == null) { if (other.label != null) { return false; } } else if (!label.equals(other.label)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } if (released == null) { if (other.released != null) { return false; } } else if (!released.equals(other.released)) { return false; } if (rocksTheHouse != other.rocksTheHouse) { return false; } if (sold != other.sold) { return false; } if (!Arrays.equals(tracks, other.tracks)) { System.out.println("Tracks not equal: " + this + " : " + other); return false; } return true; } @Override public String toString() { return "Album [" /* band=" + band + ", */ + "label=" + label + ", name=" + name + ", released=" + released + ", rocksTheHouse=" + rocksTheHouse + ", sold=" + sold + ", tracks=" + Arrays.toString(tracks) + "]"; } }
Java
/** * */ package com.vercer.engine.persist.festival; public class DanceBand extends Band { int tabletsConfiscated; @Override public String toString() { return "DanceBand [tabletsConfiscated=" + tabletsConfiscated + ", albums=" + albums + ", hair=" + hair + ", locale=" + locale + ", members=" + members + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + tabletsConfiscated; return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof DanceBand)) { return false; } DanceBand other = (DanceBand) obj; if (tabletsConfiscated != other.tabletsConfiscated) { return false; } return true; } }
Java
package com.vercer.engine.persist.festival; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertNotNull; import static junit.framework.Assert.assertNull; import static junit.framework.Assert.assertTrue; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotSame; import java.text.DateFormat; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Arrays; import java.util.Collections; import java.util.Iterator; import java.util.LinkedList; import java.util.Locale; import java.util.Map; import java.util.concurrent.ExecutionException; import java.util.concurrent.Future; import org.junit.Test; import com.google.appengine.api.datastore.Blob; import com.google.appengine.api.datastore.DatastoreService; import com.google.appengine.api.datastore.DatastoreServiceFactory; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.QueryResultIterator; import com.google.appengine.api.datastore.Transaction; import com.google.common.base.Predicate; import com.google.common.collect.ImmutableList; import com.google.common.collect.Iterators; import com.vercer.engine.persist.LocalDatastoreTestCase; import com.vercer.engine.persist.annotation.AnnotationObjectDatastore; import com.vercer.engine.persist.annotation.Embed; import com.vercer.engine.persist.annotation.Id; import com.vercer.engine.persist.festival.Album.Track; import com.vercer.engine.persist.festival.Band.HairStyle; import com.vercer.engine.persist.util.PredicateToRestrictionAdaptor; public class MusicFestivalTestCase extends LocalDatastoreTestCase { private AnnotationObjectDatastore datastore; @Override public void setUp() { super.setUp(); datastore = new AnnotationObjectDatastore(); } public static MusicFestival createFestival() throws ParseException { DateFormat dateFormat = new SimpleDateFormat("d MMM yyyy", Locale.ENGLISH); MusicFestival musicFestival = new MusicFestival(); RockBand ledzep = new RockBand(); ledzep.name = "Led Zeppelin"; ledzep.locale = Locale.UK; ledzep.hair = Band.HairStyle.LONG_LIKE_A_GIRL; ledzep.chargedForBrokenTelevisions = true; Musician page = new Musician(); page.name = "Jimmy Page"; page.birthday = dateFormat.parse("9 January 1944"); ledzep.members = new LinkedList<Musician>(); ledzep.members.add(page); Musician jones = new Musician(); jones.name = "John Paul Jones"; jones.birthday = dateFormat.parse("3 January 1946"); ledzep.members.add(jones); Musician plant = new Musician(); plant.name = "Robert Plant"; plant.birthday = dateFormat.parse("20 August 1948"); ledzep.members.add(plant); Musician bonham = new Musician(); bonham.name = "John Bonham"; bonham.birthday = dateFormat.parse("31 May 1948"); ledzep.members.add(bonham); Album houses = new Album(); houses.name = "Houses of the Holy"; houses.released = dateFormat.parse("28 March 1973"); houses.label = "Atlantic"; houses.rocksTheHouse = true; houses.sold = 18000000; ledzep.albums = new ArrayList<Album>(); ledzep.albums.add(houses); houses.tracks = new Album.Track[3]; houses.tracks[0] = new Album.Track(); houses.tracks[0].title = "The Song Remains the Same"; houses.tracks[0].length = 5.32f; houses.tracks[1] = new Album.Track(); houses.tracks[1].title = "The Rain Song"; houses.tracks[1].length = 7.39f; houses.tracks[2] = new Album.Track(); houses.tracks[2].title = "Over the Hills and Far Away"; houses.tracks[2].length = 4.50f; // set an entity inside an embedded class Album.Track.SingleDetails details = new Album.Track.SingleDetails(); details.released = 3; details.bside = "Do ya make er"; houses.tracks[2].details = details; Album iv = new Album(); iv.name = "Led Zeppelin IV"; iv.released = dateFormat.parse("8 November 1971"); iv.label = "Atlantic"; iv.rocksTheHouse = true; iv.sold = 22000000; // iv.band = ledzep; ledzep.albums.add(iv); musicFestival.bands.add(ledzep); RockBand firm = new RockBand(); firm.name = "The Firm"; firm.hair = HairStyle.BALD; firm.members = new LinkedList<Musician>(); firm.members.add(page); Musician rogers = new Musician(); rogers.name = "Paul Rogers"; rogers.birthday = dateFormat.parse("17 December 1949"); firm.members.add(rogers); musicFestival.bands.add(firm); DanceBand soulwax = new DanceBand(); soulwax.name = "Soulwax"; soulwax.locale = new Locale("nl", "be"); soulwax.members = new LinkedList<Musician>(); soulwax.members.add(new Musician("Stephen Dewaele")); soulwax.members.add(new Musician("David Dewaele")); soulwax.hair = Band.HairStyle.UNKEMPT_FLOPPY; soulwax.tabletsConfiscated = 12; // but they are still acting suspiciously Album swradio = new Album(); soulwax.albums = new ArrayList<Album>(); soulwax.albums.add(swradio); swradio.name = "As Heard on Radio Soulwax Pt. 2"; swradio.label = "Play It Again Sam"; swradio.released = dateFormat.parse("17 February 2003"); swradio.rocksTheHouse = true; swradio.sold = 500000; // swradio.band = soulwax; swradio.tracks = new Album.Track[2]; swradio.tracks[0] = new Album.Track(); swradio.tracks[0].title = "Where's Your Head At"; swradio.tracks[0].length = 2.49f; swradio.tracks[1] = new Album.Track(); swradio.tracks[1].title = "A really long track name that is certainly over 500 chars" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again" + "long expecially because it is repeated again and again and again"; swradio.tracks[1].length = 1.38f; musicFestival.bands.add(soulwax); return musicFestival; } @Test public void testLoadDifferentEqualInstances() throws ParseException { MusicFestival musicFestival = createFestival(); Key key = datastore.store(musicFestival); AnnotationObjectDatastore typesafe2 = new AnnotationObjectDatastore(); typesafe2.setActivationDepth(5); Object reloaded = typesafe2.load(key); // they should be different instances from distinct sessions assertNotSame(musicFestival, reloaded); // they should have the same data assertEquals(musicFestival, reloaded); } @Test public void testEntityFilter() throws ParseException { MusicFestival musicFestival = createFestival(); datastore.store(musicFestival); Predicate<Entity> predicate = new Predicate<Entity>() { public boolean apply(Entity input) { return input.getKey().getName().equals("Led Zeppelin"); } }; PredicateToRestrictionAdaptor<Entity> restriction = new PredicateToRestrictionAdaptor<Entity>(predicate); Iterator<RockBand> results = datastore.find().type(RockBand.class).restrictEntities(restriction).returnResultsNow(); assertEquals(Iterators.size(results), 1); } @Test public void testDeleteAll() throws ParseException { MusicFestival musicFestival = createFestival(); datastore.store(musicFestival); Iterator<Album> albums = datastore.find(Album.class); assertTrue(albums.hasNext()); datastore.deleteAll(ImmutableList.copyOf(albums)); albums = datastore.find(Album.class); assertFalse(albums.hasNext()); } @Test public void testLists() { Album album = new Album(); album.name = "Greatest Hits"; album.tracks = new Track[1]; album.tracks[0] = new Track(); album.tracks[0].title = "Friday I'm in Love"; datastore.store(album); datastore.disassociateAll(); Album load = datastore.load(Album.class, album.name); assertEquals(load, album); } @Test public void batchedStoreMulti() throws ParseException, InterruptedException, ExecutionException { MusicFestival musicFestival = createFestival(); Band band1 = musicFestival.bands.get(1); Band band2 = musicFestival.bands.get(2); Map<Band, Key> keys = datastore.store().instances(Arrays.asList(band1, band2)).batch().returnKeysNow(); assertTrue(keys.size() > 2); } @Test public void testNumericKeys() { LongKeyType longKeyType = new LongKeyType(); longKeyType.key = 9l; datastore.store(longKeyType); datastore.disassociateAll(); QueryResultIterator<LongKeyType> found = datastore.find(LongKeyType.class); while (found.hasNext()) { System.out.println(found.next().key); } LongKeyType longKeyType2 = datastore.load(LongKeyType.class, 9l); assertEquals(longKeyType2.key.longValue(), 9l); PrimitiveLongKeyType plongKeyType = new PrimitiveLongKeyType(); plongKeyType.key = 9l; datastore.store(plongKeyType); datastore.disassociateAll(); PrimitiveLongKeyType plongKeyType2 = datastore.load(PrimitiveLongKeyType.class, 9l); assertEquals(plongKeyType2.key, 9l); IntKeyType intKeyType = new IntKeyType(); intKeyType.key = 9; datastore.store(intKeyType); datastore.disassociateAll(); IntKeyType intKeyType2 = datastore.load(IntKeyType.class, 9); assertEquals(intKeyType2.key.intValue(), 9); } public static class LongKeyType { @Id Long key; } public static class PrimitiveLongKeyType { @Id long key; } public static class IntKeyType { @Id Integer key; } public static class DoubleKeyType { @Id Double key; } @Test public void asyncQueryTest() throws ParseException, InterruptedException, ExecutionException { MusicFestival musicFestival = createFestival(); datastore.store(musicFestival); Future<QueryResultIterator<RockBand>> frbs = datastore.find().type(RockBand.class).returnResultsLater(); Future<QueryResultIterator<DanceBand>> fdbs = datastore.find().type(DanceBand.class).returnResultsLater(); QueryResultIterator<RockBand> rbs = frbs.get(); QueryResultIterator<DanceBand> dbs = fdbs.get(); assertTrue(rbs.hasNext()); assertTrue(dbs.hasNext()); } @Test public void asyncStoreSingle() throws ParseException, InterruptedException, ExecutionException { MusicFestival musicFestival = createFestival(); Band band1 = musicFestival.bands.get(0); Band band2 = musicFestival.bands.get(1); Future<Key> future1 = datastore.store().instance(band1).returnKeyLater(); Future<Key> future2 = datastore.store().instance(band2).returnKeyLater(); assertEquals("Led Zeppelin", future1.get().getName()); assertEquals("The Firm", future2.get().getName()); } @Test public void ensureUniqueKey() { Band band1 = new Band(); band1.name = "Kasier Chiefs"; Band band2 = new Band(); band2.name = "Chemical Brothers"; datastore.storeAll(Arrays.asList(band1, band2)); Transaction txn = datastore.beginTransaction(); // overwrite band1 Band band3 = new Band(); band3.name = "Kasier Chiefs"; datastore.store().instance(band3); txn.commit(); txn = datastore.beginTransaction(); Band band4 = new Band(); band4.name = "Kasier Chiefs"; boolean threw = false; try { datastore.store().instance(band4).ensureUniqueKey().returnKeyNow(); } catch (Exception e) { threw = true; } txn.rollback(); assertTrue(threw); } @Test public void asyncStoreMulti() throws ParseException, InterruptedException, ExecutionException { MusicFestival musicFestival = createFestival(); Band band1 = musicFestival.bands.get(0); Band band2 = musicFestival.bands.get(1); Future<Map<Band, Key>> future1 = datastore.store().instances(Arrays.asList(band1, band2)).returnKeysLater(); Map<Band, Key> map = future1.get(); assertEquals(2, map.size()); assertNotNull(map.get(band1)); assertNotNull(map.get(band2)); } @Test public void activationDepth() throws ParseException { MusicFestival musicFestival = createFestival(); datastore.setActivationDepth(1); Key stored = datastore.store(musicFestival); datastore.disassociateAll(); // musicians have depth 3 MusicFestival reloaded = datastore.load(stored); assertNull(reloaded.bands.get(0).hair); datastore.refresh(reloaded.bands.get(0)); assertNotNull(reloaded.bands.get(0).hair); datastore.setActivationDepth(2); datastore.disassociateAll(); reloaded = datastore.load(stored); assertNotNull(reloaded.bands.get(0).hair); } @Test public void storeDuplicate() { Band band = new Band(); band.name = "The XX"; datastore.store().instance(band).ensureUniqueKey().returnKeyNow(); band = new Band(); band.name = "The XX"; boolean threw = false; try { datastore.store().instance(band).ensureUniqueKey().returnKeyNow(); } catch (Exception e) { threw = true; } assertTrue(threw); } @Test public void countEntites() throws ParseException { MusicFestival musicFestival = createFestival(); datastore.store(musicFestival); int count = datastore.find().type(Musician.class).countResultsNow(); assertEquals(7, count); } @Test public void testClassNameEscape() { Type_with__under___scores instance = new Type_with__under___scores(); instance.hello = "world"; datastore.store(instance); datastore.refresh(instance); } @Test public void testNoKeysWithAncestor() { Band band = new Band(); band.name = "Janes Addiction"; Album album = new Album(); album.name = "Jane Says"; band.albums = Collections.singletonList(album); datastore.store(band); datastore.disassociateAll(); band = datastore.load(Band.class, "Janes Addiction"); datastore.find() .type(Album.class) .ancestor(band) .fetchNoFields() .returnResultsNow(); } @Test public void testUpdate() { Band band = new Band(); band.name = "Pearl Jam"; band.hair = HairStyle.BALD; datastore.store(band); assertNotNull(datastore.load(Band.class, "Pearl Jam")); band.hair = HairStyle.LONG_LIKE_A_GIRL; datastore.update(band); datastore.disassociateAll(); assertEquals(HairStyle.LONG_LIKE_A_GIRL, datastore.load(Band.class, "Pearl Jam").hair); } @Test public void testEmbeddedPrimitives() { ClassWithEmbeddedPrimitives testType = new ClassWithEmbeddedPrimitives(); testType.number = 8; testType.blob = new Blob(new byte[] { 3, 4 }); boolean threw = false; try { datastore.store(testType); } catch (IllegalStateException e) { threw = true; } assertTrue(threw); } public static class ClassWithEmbeddedPrimitives { @Embed long number; @Embed Blob blob; @Embed ClassWithEmbeddedPrimitives inner; } }
Java
/** * */ package com.vercer.engine.persist.festival; class RockBand extends Band { boolean chargedForBrokenTelevisions; @Override public int hashCode() { final int prime = 31; int result = super.hashCode(); result = prime * result + (chargedForBrokenTelevisions ? 1231 : 1237); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (!super.equals(obj)) { return false; } if (!(obj instanceof RockBand)) { return false; } RockBand other = (RockBand) obj; if (chargedForBrokenTelevisions != other.chargedForBrokenTelevisions) { return false; } return true; } }
Java
package com.vercer.engine.persist.festival; import com.vercer.engine.persist.annotation.Version; @Version(2) public class Type_with__under___scores { String hello; }
Java
/** * */ package com.vercer.engine.persist.festival; import java.util.ArrayList; import java.util.List; public class MusicFestival { public List<Band> bands = new ArrayList<Band>(); @Override public String toString() { return "Festival [performances=" + bands + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((bands == null) ? 0 : bands.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof MusicFestival)) { return false; } MusicFestival other = (MusicFestival) obj; if (bands == null) { if (other.bands != null) { return false; } } else if (!bands.equals(other.bands)) { return false; } return true; } }
Java
package com.vercer.engine.persist.festival; import java.util.Date; public class Musician { String name; Date birthday; Integer favouriteNumber; public Musician(String name) { this.name = name; } public Musician() { } @Override public String toString() { return "Musician [birthday=" + birthday + ", name=" + name + "]"; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((birthday == null) ? 0 : birthday.hashCode()); result = prime * result + ((name == null) ? 0 : name.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Musician)) { return false; } Musician other = (Musician) obj; if (birthday == null) { if (other.birthday != null) { return false; } } else if (!birthday.equals(other.birthday)) { return false; } if (name == null) { if (other.name != null) { return false; } } else if (!name.equals(other.name)) { return false; } return true; } }
Java
package com.vercer.engine.persist; import org.junit.After; import org.junit.Before; import com.google.appengine.tools.development.testing.LocalDatastoreServiceTestConfig; import com.google.appengine.tools.development.testing.LocalServiceTestHelper; public abstract class LocalDatastoreTestCase { private final LocalServiceTestHelper helper = new LocalServiceTestHelper(new LocalDatastoreServiceTestConfig()); @Before public void setUp() { helper.setUp(); } @After public void tearDown() { helper.tearDown(); } }
Java
/** * */ package com.vercer.engine.persist; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import com.google.appengine.api.datastore.Blob; import com.vercer.engine.persist.annotation.Type; public class TypeWithCollections { public static class TypeWithEnum { public enum MyEnum { JOHN, WAS, HAIR, TWOK10 }; MyEnum watsit; } @Type(Blob.class) Collection<Class<?>> classes = new ArrayList<Class<?>>(); @Type(Blob.class) HashSet<TypeWithEnum> things = new HashSet<TypeWithEnum>(); }
Java
/** * */ package com.vercer.util.collections; import java.util.AbstractSet; import java.util.Arrays; import java.util.Comparator; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.SortedSet; import com.google.common.base.Preconditions; import com.google.common.collect.UnmodifiableIterator; public class ArraySortedSet<T extends Comparable<T>> extends AbstractSet<T> implements SortedSet<T> { private final T[] elements; private final static Comparator<?> comparator = new Comparator<Comparable<Object>>() { public int compare(Comparable<Object> o1, Comparable<Object> o2) { return o1.compareTo(o2); } }; private final int offset; private final int length; public ArraySortedSet(T[] elements) { this(elements, 0, elements.length); } public ArraySortedSet(T[] elements, int offset, int length) { this.elements = elements; this.offset = offset; this.length = length; } @Override public Iterator<T> iterator() { // copied from non-visible Google Collections Iterators final int end = offset + length; Preconditions.checkPositionIndexes(offset, end, elements.length); return new UnmodifiableIterator<T>() { int i = offset; public boolean hasNext() { return i < end; } public T next() { if (!hasNext()) { throw new NoSuchElementException(); } return elements[i++]; } }; } @Override public int size() { return length; } @SuppressWarnings("unchecked") public Comparator<? super T> comparator() { return (Comparator<? super T>) comparator; } public T first() { return elements[0]; } public SortedSet<T> headSet(T toElement) { int index = Arrays.binarySearch(elements, toElement); return new ArraySortedSet<T>(elements, 0, index + 1); } public T last() { return elements[offset + length - 1]; } public SortedSet<T> subSet(T fromElement, T toElement) { int from = Arrays.binarySearch(elements, fromElement); int to = Arrays.binarySearch(elements, toElement); return new ArraySortedSet<T>(elements, from, to - from + 1); } public SortedSet<T> tailSet(T fromElement) { int index = Arrays.binarySearch(elements, fromElement); return new ArraySortedSet<T>(elements, index, length); } }
Java
package com.vercer.util.collections; import java.util.AbstractSet; import java.util.Iterator; import java.util.Set; public class PrependSet<E> extends AbstractSet<E> { private final E item; private final Set<E> set; public PrependSet(E item, Set<E> list) { this.item = item; this.set = list; } @Override public int size() { return set.size() + (item == null ? 0 : 1); } @Override public Iterator<E> iterator() { return new Iterator<E>() { boolean returnItem = true; Iterator<E> iterator = set.iterator(); public boolean hasNext() { return returnItem && item != null || iterator.hasNext(); } public E next() { if (returnItem) { returnItem = false; return item; } else { return iterator.next(); } } public void remove() { throw new UnsupportedOperationException(); } }; } public E getItem() { return item; } public Set<E> getSet() { return set; } }
Java
package com.vercer.util.collections; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.Iterator; import java.util.List; import com.google.common.collect.Iterators; public class MergeSet<T> extends AbstractSet<T> { private int size; private final List<Collection<? extends T>> sets; public MergeSet() { this.sets = new ArrayList<Collection<? extends T>>(); } public MergeSet(int size) { this.sets = new ArrayList<Collection<? extends T>>(size); } @Override public Iterator<T> iterator() { Iterator<Iterator<? extends T>> iterators = new Iterator<Iterator<? extends T>>() { Iterator<Collection<? extends T>> iterator = sets.iterator(); public boolean hasNext() { return iterator.hasNext(); } public Iterator<? extends T> next() { return iterator.next().iterator(); } public void remove() { throw new UnsupportedOperationException(); } }; return Iterators.concat(iterators); } @Override public boolean addAll(Collection<? extends T> set) { if (set.isEmpty()) { return true; } size += set.size(); return sets.add(set); } @Override public boolean add(T o) { return sets.add(Collections.singleton(o)); }; @Override public int size() { return size; } }
Java
package com.vercer.util.reference; public class StaticObjectReference<T> implements ObjectReference<T> { private static Object object; @SuppressWarnings("unchecked") public T get() { return (T) object; } public void set(T object) { StaticObjectReference.object = object; } }
Java
package com.vercer.util.reference; import java.io.Serializable; public class SimpleObjectReference<T> implements ObjectReference<T>, Serializable { private static final long serialVersionUID = 1L; private T object; public SimpleObjectReference() { } public SimpleObjectReference(T object) { this.object = object; } public T get() { return object; } public void set(T object) { this.object = object; } }
Java
package com.vercer.util.reference; public abstract class ReadOnlyObjectReference<T> implements ObjectReference<T> { public void set(T object) { throw new UnsupportedOperationException(); }; }
Java
package com.vercer.util.reference; public interface ObjectReference<T> { T get(); void set(T object); }
Java
package com.vercer.util.reference; public class ThreadLocalObjectReference<T> implements ObjectReference<T> { private ThreadLocal<T> localObjects = new ThreadLocal<T>(); public T get() { return localObjects.get(); } public void set(T object) { localObjects.set(object); } }
Java
package com.vercer.util; public class Pair<F, S> { private final F first; private final S second; public Pair(F first, S second) { this.first = first; this.second = second; } public F getFirst() { return first; } public S getSecond() { return second; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((first == null) ? 0 : first.hashCode()); result = prime * result + ((second == null) ? 0 : second.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Pair<?, ?>)) { return false; } Pair<?, ?> other = (Pair<?, ?>) obj; if (first == null) { if (other.first != null) { return false; } } else if (!first.equals(other.first)) { return false; } if (second == null) { if (other.second != null) { return false; } } else if (!second.equals(other.second)) { return false; } return true; } }
Java
package com.vercer.util; import java.lang.reflect.Constructor; import java.lang.reflect.Field; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Iterator; import java.util.List; public class Reflection { public static String toString(Object object) { StringBuilder builder = new StringBuilder(); builder.append("["); String name = object.getClass().getName(); builder.append(name.substring(name.lastIndexOf(".") + 1)); builder.append(" "); Iterator<Field> fields = getAccessibleFields(object.getClass()).iterator(); while (fields.hasNext()) { Field field = fields.next(); String fieldName = field.getName(); if (fieldName.startsWith("_")) { fieldName = fieldName.substring(1); } builder.append(fieldName); builder.append("="); Object value; try { value = field.get(object); } catch (Exception e) { return "No permitted to access field"; } if (value == null) { builder.append("null"); } else { builder.append(value.toString()); } if (fields.hasNext()) { builder.append(" "); } } builder.append("]"); return builder.toString(); } public static List<Field> getAccessibleFields(Class<?> type) { List<Field> fields = new ArrayList<Field>(); while (!Object.class.equals(type)) { Field[] declaredFields = type.getDeclaredFields(); for (Field field : declaredFields) { if (Modifier.isStatic(field.getModifiers()) == false) { // do not include system fields like $assertionsDisabled if (!field.getName().startsWith("$")) { fields.add(field); field.setAccessible(true); } } } type = type.getSuperclass(); } return fields; } public static <T> T constructCopyWith(T original, Object... arguments) throws SecurityException, NoSuchMethodException, InstantiationException, IllegalAccessException, InvocationTargetException { @SuppressWarnings("unchecked") Constructor<T>[] constructors = (Constructor<T>[]) original.getClass().getConstructors(); Constructor<T> constructor = null; next: for (Constructor<T> possible : constructors) { Class<?>[] parameterTypes = possible.getParameterTypes(); if (parameterTypes.length == arguments.length) { for (int i = 0; i < parameterTypes.length; i++) { Class<?> type = parameterTypes[i]; if (!type.isAssignableFrom(arguments[i].getClass())) { continue next; } } constructor = possible; } } if (constructors == null) { throw new IllegalArgumentException("Could not find constructor"); } return constructor.newInstance(arguments); } }
Java
package com.vercer.util; import java.lang.reflect.InvocationHandler; import java.lang.reflect.Method; import java.lang.reflect.Proxy; public abstract class LazyProxy<T> { private static final class LaxyInvocationHandler<T> implements InvocationHandler { private T instance; private final LazyProxy<T> lazyProxy; public LaxyInvocationHandler(LazyProxy<T> lazyProxy) { this.lazyProxy = lazyProxy; } public Object invoke(Object proxy, Method method, Object[] args) throws Throwable { if (instance == null) { instance = lazyProxy.newInstance(); } return method.invoke(instance, args); } } private final Class<?> interfaceClass; public LazyProxy(Class<?> interfaceClass) { this.interfaceClass = interfaceClass; } @SuppressWarnings("unchecked") public T newProxy() { InvocationHandler handler = new LaxyInvocationHandler(this); return (T) Proxy.newProxyInstance(this.getClass().getClassLoader(), new Class[] {interfaceClass}, handler); } protected abstract T newInstance(); @SuppressWarnings("unchecked") public static <T> T getInstance(T proxy) { LaxyInvocationHandler<T> handler = (LaxyInvocationHandler<T>) Proxy.getInvocationHandler(proxy); return handler.instance; } }
Java
package com.vercer.util; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.StringTokenizer; public final class Strings { private Strings() { } public static int firstIndexOf(String source, char... chars) { return firstIndexOf(source, 0, chars); } public static int firstIndexOf(String source, int start, char... chars) { for (int i = start; i < source.length(); i ++) { char c = source.charAt(i); for (char d : chars) { if (c == d) { return i; } } } return -1; } public static int lastIndexOf(String source, int start, char... chars) { for (int i = start; i >= 0; i--) { char c = source.charAt(i); for (char d : chars) { if (c == d) { return i; } } } return -1; } public static int nthIndexOf(String source, int n, char... chars) { int index = -1; for (int i = 0; i < n; i++) { index = firstIndexOf(source, index + 1, chars); } return index; } public static String[] split(String source, boolean include, char... chars) { List<String> result = new ArrayList<String>(); for (int start = 0; start < source.length() && start >= 0; ) { int next = firstIndexOf(source, start, chars); if (next > 0) { result.add(source.substring(start, include ? next + 1 : next)); } else { result.add(source.substring(start)); break; } start = next + 1; } return result.toArray(new String[result.size()]); } public static String onlyCharacterTypes(String source, int... types) { StringBuilder builder = new StringBuilder(source.length()); for (int i = 0 ; i < source.length(); i++) { char c = source.charAt(i); for (int j = 0; j < types.length; j++) { if (Character.getType(c) == types[j]) { builder.append(c); break; } } } return builder.toString(); } private static final Collection<String> noCaps = new ArrayList<String>(); static { noCaps.add("to"); noCaps.add("a"); noCaps.add("an"); noCaps.add("on"); noCaps.add("to"); noCaps.add("be"); noCaps.add("am"); noCaps.add("are"); noCaps.add("were"); noCaps.add("in"); noCaps.add("near"); noCaps.add("the"); noCaps.add("with"); noCaps.add("and"); noCaps.add("or"); } /** * See http://answers.google.com/answers/threadview?id=349913 for rules * @param title * @return */ public static String toTitleCase(String title) { StringBuilder builder = new StringBuilder(); StringTokenizer tokenizer = new StringTokenizer(title, " ", true); while (tokenizer.hasMoreTokens()) { String token = tokenizer.nextToken(); if (builder.length() == 0 || // always first word tokenizer.hasMoreTokens() == false || // always last word noCaps.contains(token) == false) // try to avoid conjunctions and short prepositions { builder.append(Character.toUpperCase(token.charAt(0))); if (token.length() > 1) { builder.append(token.substring(1)); } } else { builder.append(token); } } return builder.toString(); } }
Java
/** * */ package com.vercer.engine.persist; public interface Restriction<T> { boolean allow(T candidate); }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Independent { }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Id { }
Java
package com.vercer.engine.persist.annotation; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import com.vercer.engine.persist.strategy.CombinedStrategy; import com.vercer.engine.persist.strategy.DefaultFieldStrategy; import com.vercer.engine.persist.util.generic.GenericTypeReflector; public class AnnotationStrategy extends DefaultFieldStrategy implements CombinedStrategy { private final boolean indexed; public AnnotationStrategy(boolean indexPropertiesDefault, int defaultVersion) { super(defaultVersion); this.indexed = indexPropertiesDefault; } public boolean child(Field field) { return field.isAnnotationPresent(Child.class); } public boolean parent(Field field) { return field.isAnnotationPresent(Parent.class); } public boolean embed(Field field) { Embed annotation = field.getAnnotation(Embed.class); if (annotation == null) { annotation = field.getType().getAnnotation(Embed.class); } if (annotation != null) { return annotation.value(); } else { return false; } } public boolean store(Field field) { Store annotation = field.getAnnotation(Store.class); if (annotation != null) { return annotation.value(); } else { int modifiers = field.getModifiers(); if (Modifier.isFinal(modifiers)) { String name = field.getName(); if (name.matches(".*this\\$[0-9]+")) { throw new IllegalStateException("Inner class " + field.getDeclaringClass() + " must be declared static"); } else { throw new IllegalStateException("Final field " + field + " cannot be stored"); } } return !Modifier.isTransient(modifiers) ; } } public boolean index(Field field) { Index annotation = field.getDeclaringClass().getAnnotation(Index.class); if (field.getAnnotation(Index.class) != null) { annotation = field.getAnnotation(Index.class); } if (annotation != null) { return annotation.value(); } else { return indexed; } } @SuppressWarnings("deprecation") public boolean key(Field field) { return field.isAnnotationPresent(Key.class) || field.isAnnotationPresent(Id.class); } @Override public java.lang.reflect.Type typeOf(Field field) { Type annotation = field.getAnnotation(Type.class); if (annotation == null) { return super.typeOf(field); } else { return annotation.value(); } } @Override protected String typeToName(java.lang.reflect.Type type) { Class<?> erased = GenericTypeReflector.erase(type); Entity annotation = erased.getAnnotation(Entity.class); if (annotation != null && annotation.kind().length() > 0) { return annotation.kind(); } return super.typeToName(type); } public boolean polymorphic(Field field) { Embed annotation = field.getAnnotation(Embed.class); if (annotation == null) { annotation = field.getType().getAnnotation(Embed.class); } if (annotation != null) { return annotation.polymorphic(); } else { // final classes cannot be polymorphic - all others can return !Modifier.isFinal(field.getType().getModifiers()); } } public boolean entity(Field field) { return field.isAnnotationPresent(Parent.class) || field.isAnnotationPresent(Child.class) || field.isAnnotationPresent(Independent.class); } public int activationDepth(Field field, int depth) { Activate annotation = field.getDeclaringClass().getAnnotation(Activate.class); if (field.getAnnotation(Activate.class) != null) { annotation = field.getAnnotation(Activate.class); } if (annotation != null) { return annotation.value(); } return depth; } @Override protected int version(java.lang.reflect.Type type) { Class<?> clazz = GenericTypeReflector.erase(type); if (clazz.isAnnotationPresent(Version.class)) { return clazz.getAnnotation(Version.class).value(); } else { return super.version(type); } } }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Child { }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Store { boolean value() default true; }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Type { Class<?> value(); }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Inherited @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface Version { int value() default 0; }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Parent { }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Deprecated @Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface Key { }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) public @interface Index { boolean value() default true; boolean declared() default true; }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Embed { boolean value() default true; boolean polymorphic() default false; boolean declared() default true; }
Java
package com.vercer.engine.persist.annotation; import com.vercer.engine.persist.standard.StrategyObjectDatastore; import com.vercer.engine.persist.strategy.FieldStrategy; public class AnnotationObjectDatastore extends StrategyObjectDatastore { public AnnotationObjectDatastore() { this(true, 0); } public AnnotationObjectDatastore(boolean indexed, int defaultVersion) { this(new AnnotationStrategy(indexed, defaultVersion)); } public AnnotationObjectDatastore(boolean indexed) { this(new AnnotationStrategy(indexed, 0)); } public AnnotationObjectDatastore(FieldStrategy fields) { this(new AnnotationStrategy(true, 0), fields); } protected AnnotationObjectDatastore(AnnotationStrategy strategy, FieldStrategy fields) { super(strategy, strategy, strategy, strategy, fields); } }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Activate { int value() default 1; }
Java
package com.vercer.engine.persist.annotation; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target({ElementType.FIELD, ElementType.TYPE}) @Retention(RetentionPolicy.RUNTIME) @Inherited public @interface Entity { String kind() default ""; }
Java
package com.vercer.engine.persist; import java.util.Collection; import java.util.Map; import java.util.concurrent.Future; import com.google.appengine.api.datastore.Key; public interface StoreCommand { <T> SingleStoreCommand<T> instance(T instance); <T> MultipleStoreCommand<T> instances(Collection<T> instances); <T> MultipleStoreCommand<T> instances(T... instances); interface CommonStoreCommand<T, C extends CommonStoreCommand<T, C>> { C parent(Object parent); C batch(); C ensureUniqueKey(); } interface SingleStoreCommand<T> extends CommonStoreCommand<T, SingleStoreCommand<T>> { Key returnKeyNow(); Future<Key> returnKeyLater(); } interface MultipleStoreCommand<T> extends CommonStoreCommand<T, MultipleStoreCommand<T>> { Map<T, Key> returnKeysNow(); Future<Map<T, Key>> returnKeysLater(); } }
Java
package com.vercer.engine.persist.strategy; import java.util.Collection; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; public interface CacheStrategy { }
Java
package com.vercer.engine.persist.strategy; import java.lang.reflect.Field; /** * Determines if and how a field is stored in the datastore * * @author John Patterson <john@vercer.com> */ public interface StorageStrategy { /** * @param field The reflected Field to be examined * @return true to store as a component of the referencing Entity */ boolean embed(Field field); /** * Should this field value be stored as a separate Entity * @param field * @return true to store as a datastore Entity */ boolean entity(Field field); /** * Should the field be included in the single field indexes * * Creates a property using Entity.setUnindexedProperty(String, Object) * * @param field The reflected Field to be examined * @return true if the field is indexed */ boolean index(Field field); /** * Should the field be stored at all * @param field The reflected Field to be examined * @return true to store the field */ boolean store(Field field); /** * Can this field hold sub-types of the declared field type * @param field * @return true if sub-types are allowed */ boolean polymorphic(Field field); }
Java
package com.vercer.engine.persist.strategy; public interface CombinedStrategy extends ActivationStrategy, CacheStrategy, FieldStrategy, RelationshipStrategy,StorageStrategy { }
Java
package com.vercer.engine.persist.strategy; import java.lang.reflect.Field; import java.lang.reflect.Type; public interface FieldStrategy { /** * @return The property name used for this field */ String name(Field field); /** * @return The kind name used in the Entity that stores this type */ String typeToKind(Type type); /** * @return The Type that is represented by this kind name in the Entity */ Type kindToType(String kind); /** * @return The Type that field values should be converted to */ Type typeOf(Field field); }
Java
package com.vercer.engine.persist.strategy; import java.lang.reflect.Field; public interface ActivationStrategy { int activationDepth(Field field, int depth); }
Java
package com.vercer.engine.persist.strategy; public interface InstanceStrategy { }
Java
package com.vercer.engine.persist.strategy; import java.lang.reflect.Field; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import com.vercer.engine.persist.conversion.PrimitiveTypeConverter; import com.vercer.engine.persist.util.generic.GenericTypeReflector; /** * @author John Patterson <john@vercer.com> * */ public class DefaultFieldStrategy implements FieldStrategy { private static final class ReplacedListType implements ParameterizedType { private final Type type; private final Type replaced; private ReplacedListType(Type type, Type replaced) { this.type = type; this.replaced = replaced; } public Type getRawType() { return ArrayList.class; } public Type getOwnerType() { return null; } public Type[] getActualTypeArguments() { return new Type[] { replaced }; } @Override public String toString() { return "(Replaced " + type + " with List<" + replaced + ">)"; } } private final int defaultVersion; public DefaultFieldStrategy(int defaultVersion) { this.defaultVersion = defaultVersion; } /** * Decode a type name - possibly abbreviated - into a type. * * @param name The portion of the kind name that specifies the Type */ protected Type nameToType(String name) { try { return Class.forName(name); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } private final static Pattern pattern = Pattern.compile("v\\d_"); public final Type kindToType(String name) { Matcher matcher = pattern.matcher(name); if (matcher.lookingAt()) { name = name.substring(matcher.end()); } //use space as a place holder as it cannot exist in property names name = name.replaceAll("__", " "); name = name.replace('_', '.'); name = name.replace(' ', '_'); return nameToType(name); } /** * * @see com.vercer.engine.persist.strategy.FieldStrategy#name(java.lang.reflect.Field) */ public final String name(Field field) { String name = field.getName(); if (name.charAt(0) == '_') { name = name.substring(1); } return name; } public final String typeToKind(Type type) { String kind = typeToName(type); kind = kind.replace('.', ' '); kind = kind.replaceAll("_", "__"); kind = kind.replace(' ', '_'); int version = version(type); if (version > 0) { kind = "v" + version + "_" + kind; } return kind; } /** * The converse method nametoType must understand how to "decode" type * names encoded by this method * * @return A representation that can unambiguously specify the type */ protected String typeToName(Type type) { Class<?> clazz = GenericTypeReflector.erase(type); String kind = clazz.getName(); return kind; } /** * @return The datastore version to store this type under */ protected int version(Type type) { return defaultVersion; } /** * Replaces all Collection types and Arrays with List. Converts all elements of * the collection to the component type. * * @see com.vercer.engine.persist.strategy.FieldStrategy#typeOf(java.lang.reflect.Field) */ public Type typeOf(Field field) { return replace(field.getGenericType()); } protected Type replace(final Type type) { // turn every collection or array into an array list Type componentType = null; Class<?> erased = GenericTypeReflector.erase(type); if (type instanceof GenericArrayType) { // we have a generic array like Provider<Twig>[] GenericArrayType arrayType = (GenericArrayType) type; componentType = arrayType.getGenericComponentType(); } else if (erased.isArray()) { // we have a normal array like Twig[] componentType = erased.getComponentType(); } else if (Collection.class.isAssignableFrom(erased) && !ArrayList.class.isAssignableFrom(erased)) { // we have some kind of collection like Set<Twig> Type exact = GenericTypeReflector.getExactSuperType(type, Collection.class); componentType = ((ParameterizedType) exact).getActualTypeArguments()[0]; } else { // we have a non-collection type return type; } // we have a collection type so need to convert it to // recurse in case we have e.g. List<Twig[]> Type replaced = replace(componentType); // use wrapper type for primitives if (GenericTypeReflector.erase(replaced).isPrimitive()) { replaced = PrimitiveTypeConverter.getWrapperClassForPrimitive((Class<?>) replaced); } // replace the collection type with a list type return new ReplacedListType(type, replaced); } }
Java
package com.vercer.engine.persist.strategy; import java.lang.reflect.Field; public interface RelationshipStrategy { /** * @param field The reflected Field to be examined * @return */ boolean parent(Field field); /** * @param field The reflected Field to be examined * @return */ boolean child(Field field); /** * The key field value will be converted to a String and become the name * of the key which will not be stored as a property. The value must not * be null and must be convertible to and from a String unambiguously. * * @param field The reflected Field to examine * @return <code>true</code> if the field holds a unique key for this type */ boolean key(Field field); }
Java
package com.vercer.engine.persist; import java.lang.reflect.Type; import java.util.Collection; import java.util.Map; import com.google.appengine.api.datastore.DatastoreServiceConfig; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.QueryResultIterator; import com.google.appengine.api.datastore.Transaction; public interface ObjectDatastore extends Activator { // fluent style methods StoreCommand store(); FindCommand find(); LoadCommand load(); // convenience store methods Key store(Object instance); Key store(Object instance, Object parent); <T> Map<T, Key> storeAll(Collection<? extends T> instances); <T> Map<T, Key> storeAll(Collection<? extends T> instances, Object parent); // updating void update(Object instance); void storeOrUpdate(Object instance); void storeOrUpdate(Object instance, Object parent); // convenience load methods <T> T load(Key key); <T> T load(Class<T> type, Object key); <T> T load(Class<T> type, Object key, Object parent); <I, T> Map<I, T> loadAll(Class<? extends T> type, Collection<I> ids); // convenience find methods <T> QueryResultIterator<T> find(Class<T> type); <T> QueryResultIterator<T> find(Class<T> type, Object ancestor); // convenience delete methods void delete(Object instance); void deleteAll(Type type); void deleteAll(Collection<?> instances); // activation int getActivationDepth(); void setActivationDepth(int depth); /** * Refresh an associated instance with the latest version from the datastore */ void refresh(Object instance); void refreshAll(Collection<?> instances); // cache control operations void associate(Object instance); void associate(Object instance, Key key); void disassociate(Object instance); void disassociateAll(); Key associatedKey(Object instance); void setConfiguration(DatastoreServiceConfig config); // transactions Transaction beginTransaction(); Transaction getTransaction(); }
Java
package com.vercer.engine.persist; import java.lang.reflect.Type; import java.util.Set; public interface PropertyTranslator { // TODO both should have parameters (Object, Type, Set<Property>, Path):void public Object propertiesToTypesafe(Set<Property> properties, Path path, Type type); public Set<Property> typesafeToProperties(Object instance, Path path, boolean indexed); // TODO make a special value for could-not-handle instead public static Object NULL_VALUE = new Object(); // TODO should have instantiate method like GWT generator? // Object instantiate(Type, Set<Property>) }
Java
package com.vercer.engine.persist.conversion; import java.lang.reflect.Type; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; import com.vercer.engine.persist.util.generic.GenericTypeReflector; public class PrimitiveTypeConverter implements TypeConverter { private static final Map<Class<?>, Class<?>> primitives = new HashMap<Class<?>, Class<?>>(); private static final Set<Class<?>> wrappers = new HashSet<Class<?>>(); static { primitives.put(Integer.TYPE, Integer.class); primitives.put(Long.TYPE, Long.class); primitives.put(Float.TYPE, Float.class); primitives.put(Double.TYPE, Double.class); primitives.put(Boolean.TYPE, Boolean.class); primitives.put(Short.TYPE, Short.class); primitives.put(Byte.TYPE, Byte.class); primitives.put(Character.TYPE, Character.class); wrappers.addAll(primitives.values()); } @SuppressWarnings("unchecked") public <T> T convert(Object source, Type type) { Class<?> erased = GenericTypeReflector.erase(type); if (source == null && !erased.isPrimitive()) { // consider null a primitive value return (T) nullValue; } // if we have a primitive or wrapper get the wrapper Class<?> wrapper = null; if (erased.isPrimitive()) { wrapper = primitives.get(erased); if (source == null) { if (Number.class.isAssignableFrom(wrapper)) { source = 0; } else if (Boolean.class == wrapper) { source = false; } else if (Character.class == wrapper) { source = Character.MIN_VALUE; } else { throw new IllegalStateException("Unkonwn primitive default " + type); } } if (source.getClass() == wrapper) { // we do not need to convert a wrapper to primitive T result = (T) source; return result; } } else if (wrappers.contains(erased)) { wrapper = erased; } // convert any primitives to string if (type == String.class && (primitives.containsKey(source.getClass()) || wrappers.contains(source.getClass()))) { return (T) source.toString(); } // we need a primitive wrapper so convert directly if (wrapper == null) { return null; // signal that we cannot convert this type } else { // please tell me if you know a better way to do this! if (wrapper == Integer.class) { if (source instanceof Long) { return (T) Integer.valueOf(((Long) source).intValue()); } else if (source instanceof Double) { return (T) Integer.valueOf(((Double) source).intValue()); } else if (source instanceof Float) { return (T) Integer.valueOf(((Float) source).intValue()); } else if (source instanceof Short) { return (T) Integer.valueOf(((Short) source).intValue()); } else if (source instanceof Byte) { return (T) Integer.valueOf(((Byte) source).intValue()); } else if (source instanceof String) { return (T) Integer.decode((String) source); } } else if (wrapper == Long.class) { if (source instanceof Integer) { return (T) Long.valueOf(((Integer) source).longValue()); } else if (source instanceof Double) { return (T) Long.valueOf(((Double) source).longValue()); } else if (source instanceof Float) { return (T) Long.valueOf(((Float) source).longValue()); } else if (source instanceof Short) { return (T) Long.valueOf(((Short) source).longValue()); } else if (source instanceof Byte) { return (T) Long.valueOf(((Byte) source).longValue()); } else if (source instanceof String) { return (T) Long.decode((String) source); } } else if (wrapper == Float.class) { if (source instanceof Long) { return (T) Float.valueOf(((Long) source).floatValue()); } else if (source instanceof Double) { return (T) Float.valueOf(((Double) source).floatValue()); } else if (source instanceof Integer) { return (T) Float.valueOf(((Integer) source).floatValue()); } else if (source instanceof Short) { return (T) Float.valueOf(((Short) source).floatValue()); } else if (source instanceof Byte) { return (T) Float.valueOf(((Byte) source).floatValue()); } else if (source instanceof String) { return (T) Float.valueOf((String) source); } } else if (wrapper == Double.class) { if (source instanceof Long) { return (T) Double.valueOf(((Long) source).doubleValue()); } else if (source instanceof Integer) { return (T) Double.valueOf(((Integer) source).doubleValue()); } else if (source instanceof Float) { return (T) Double.valueOf(((Float) source).doubleValue()); } else if (source instanceof Short) { return (T) Double.valueOf(((Short) source).doubleValue()); } else if (source instanceof Byte) { return (T) Double.valueOf(((Byte) source).doubleValue()); } else if (source instanceof String) { return (T) Double.valueOf((String) source); } } else if (wrapper == Short.class) { if (source instanceof Number) { return (T) Short.valueOf(((Number) source).shortValue()); } else if (source instanceof String) { return (T) Short.decode((String) source); } } else if (wrapper == Byte.class) { if (source instanceof Long) { return (T) Byte.valueOf(((Long) source).byteValue()); } else if (source instanceof Integer) { return (T) Byte.valueOf(((Integer) source).byteValue()); } else if (source instanceof Float) { return (T) Byte.valueOf(((Float) source).byteValue()); } else if (source instanceof Double) { return (T) Byte.valueOf(((Double) source).byteValue()); } else if (source instanceof Short) { return (T) Byte.valueOf(((Short) source).byteValue()); } else if (source instanceof String) { return (T) Byte.decode((String) source); } } throw new IllegalArgumentException("Could not convert from " + source + " to wrapper " + wrapper); } } public static Class<?> getWrapperClassForPrimitive(Class<?> primitive) { return primitives.get(primitive); } }
Java
package com.vercer.engine.persist.conversion; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.Serializable; import java.lang.reflect.Type; import java.text.DateFormat; import java.text.ParseException; import java.util.Date; import java.util.Map; import java.util.concurrent.ConcurrentHashMap; import com.google.appengine.api.datastore.Blob; import com.google.appengine.api.datastore.Text; import com.vercer.engine.persist.util.generic.GenericTypeReflector; import com.vercer.engine.persist.util.io.NoDescriptorObjectInputStream; import com.vercer.engine.persist.util.io.NoDescriptorObjectOutputStream; import com.vercer.util.Pair; public class DefaultTypeConverter extends CombinedTypeConverter { private static Map<Pair<Type, Class<?>>, Boolean> superTypes = new ConcurrentHashMap<Pair<Type, Class<?>>, Boolean>(); public DefaultTypeConverter() { register(new PrimitiveTypeConverter()); register(new CollectionConverter(this)); register(new StringToText()); register(new TextToString()); register(new StringToDate()); register(new DateToString()); register(new ByteArrayToBlob()); register(new BlobToByteArray()); register(new SerializableToBlob()); register(new BlobToAnything()); } @SuppressWarnings("unchecked") @Override public <T> T convert(Object source, Type type) { if (source != null && isSuperType(type, source.getClass())) { return (T) source; } else { // use the registered converters return (T) super.convert(source, type); } } private static boolean isSuperType(Type type, Class<? extends Object> clazz) { if (type == clazz) { return true; } Pair<Type, Class<?>> key = new Pair<Type, Class<?>>(type, clazz); Boolean superType = superTypes.get(key); if (superType != null) { return superType; } else { boolean result = GenericTypeReflector.isSuperType(type, clazz); superTypes.put(key, result); return result; } } public static class StringToText implements SpecificTypeConverter<String, Text> { public Text convert(String source) { return new Text(source); } } public static class TextToString implements SpecificTypeConverter<Text, String> { public String convert(Text source) { return source.getValue(); } } public static class ByteArrayToBlob implements SpecificTypeConverter<byte[], Blob> { public Blob convert(byte[] source) { return new Blob(source); } } public static class BlobToByteArray implements SpecificTypeConverter<Blob, byte[]> { public byte[] convert(Blob source) { return source.getBytes(); } } public static class SerializableToBlob implements SpecificTypeConverter<Serializable, Blob> { public Blob convert(Serializable source) { try { ByteArrayOutputStream baos = new ByteArrayOutputStream(256); ObjectOutputStream stream = createObjectOutputStream(baos); stream.writeObject(source); return new Blob(baos.toByteArray()); } catch (Exception e) { throw new IllegalStateException(e); } } protected ObjectOutputStream createObjectOutputStream(ByteArrayOutputStream baos) throws IOException { return new NoDescriptorObjectOutputStream(baos); } } public static class SlowSerializableToBlob extends SerializableToBlob { @Override protected ObjectOutputStream createObjectOutputStream(ByteArrayOutputStream baos) throws IOException { return new ObjectOutputStream(baos); } } public static class BlobToAnything implements TypeConverter { public Object convert(Blob blob) { try { ByteArrayInputStream bais = new ByteArrayInputStream(blob.getBytes()); ObjectInputStream stream = createObjectInputStream(bais); return stream.readObject(); } catch (Exception e) { throw new IllegalStateException(e); } } protected ObjectInputStream createObjectInputStream(ByteArrayInputStream bais) throws IOException { return new NoDescriptorObjectInputStream(bais); } @SuppressWarnings("unchecked") public <T> T convert(Object source, Type type) { if (source != null && source.getClass() == Blob.class) { return (T) convert((Blob) source); } return null; } } public static class SlowBlobToAnything extends BlobToAnything { @Override protected ObjectInputStream createObjectInputStream(ByteArrayInputStream bais) throws IOException { return new ObjectInputStream(bais); } } static DateFormat format = DateFormat.getDateTimeInstance(); public static class DateToString implements SpecificTypeConverter<Date, String> { public String convert(Date source) { return format.format(source); } } public static class StringToDate implements SpecificTypeConverter<String, Date> { public Date convert(String source) { try { return format.parse(source); } catch (ParseException e) { throw new IllegalStateException(e); } } } public static class ClassToString implements SpecificTypeConverter<Class<?>, String> { public String convert(Class<?> source) { return source.getName(); } } public static class StringToClass implements SpecificTypeConverter<String, Class<?>> { public Class<?> convert(String source) { try { return Class.forName(source); } catch (ClassNotFoundException e) { throw new IllegalStateException(e); } } } }
Java
package com.vercer.engine.persist.conversion; public interface SpecificTypeConverter<S, T> { T convert(S source); }
Java
package com.vercer.engine.persist.conversion; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import com.vercer.engine.persist.util.generic.GenericTypeReflector; import com.vercer.util.Pair; public class CombinedTypeConverter implements TypeConverter { private final List<SpecificTypeConverter<?, ?>> specifics = new ArrayList<SpecificTypeConverter<?,?>>(); private final List<TypeConverter> generals = new ArrayList<TypeConverter>(); private final Map<Pair<Type, Type>, SpecificTypeConverter<?, ?>> cache = new HashMap<Pair<Type,Type>, SpecificTypeConverter<?,?>>(); /* (non-Javadoc) * @see com.vercer.engine.persist.conversion.TypeConverter#convert(java.lang.Object, java.lang.reflect.Type) */ @SuppressWarnings("unchecked") public <T> T convert(Object source, Type type) { // try the specific converters first SpecificTypeConverter<? super Object, ? extends T> specific = null; if (source != null) { specific = (SpecificTypeConverter<? super Object, ? extends T>) converter(source.getClass(), type); } if (specific == null) { // try the general converters for (TypeConverter general : generals) { Object result = general.convert(source, type); if (result != null) { if (result == nullValue) { return null; } else { return (T) result; } } } throw new IllegalStateException("Cannot convert " + source + " to " + type); } else { return specific.convert(source); } } public void register(SpecificTypeConverter<?, ?> specific) { specifics.add(specific); } public void register(TypeConverter general) { generals.add(general); } public void prepend(TypeConverter converter) { generals.add(0, converter); } public void prepend(SpecificTypeConverter<?, ?> converter) { specifics.add(0, converter); } public SpecificTypeConverter<?, ?> converter(Type from, Type to) { Pair<Type, Type> pair = new Pair<Type, Type>(from, to); if (cache.containsKey(pair)) { return cache.get(pair); } else { for (SpecificTypeConverter<?, ?> converter : specifics) { Type type = GenericTypeReflector.getExactSuperType(converter.getClass(), SpecificTypeConverter.class); Type[] arguments = ((ParameterizedType) type).getActualTypeArguments(); if (GenericTypeReflector.isSuperType(arguments[0], from) && GenericTypeReflector.isSuperType(to, arguments[1])) { cache.put(pair, converter); return converter; } } return null; } } }
Java
package com.vercer.engine.persist.conversion; import java.lang.reflect.Type; public interface TypeConverter { <T> T convert(Object source, Type type); Object nullValue = new Object(); }
Java
/** * */ package com.vercer.engine.persist.conversion; import java.lang.reflect.Array; import java.lang.reflect.GenericArrayType; import java.lang.reflect.ParameterizedType; import java.lang.reflect.Type; import java.util.ArrayList; import java.util.Collection; import java.util.EnumSet; import java.util.HashSet; import java.util.List; import com.vercer.engine.persist.util.generic.GenericTypeReflector; /** * Handles conversions from any Collection type or Array to either a HashSet, * ArrayList or Array. * * Generic Collections and Arrays will be converted into the correct generic * Array type. * * To add a conversion to a more specific Collection type you will need to add a * SpecificTypeConverter<S, T> * * @author John Patterson <john@vercer.com> */ public class CollectionConverter implements TypeConverter { private final TypeConverter delegate; public CollectionConverter(TypeConverter delegate) { this.delegate = delegate; } public <T> T convert(Object source, Type type) { // attempt to convert input into an array Object[] items = null; if (source instanceof Collection<?>) { items = ((Collection<?>) source).toArray(); } else if (source instanceof Object[]) { items = (Object[]) source; } else if (source.getClass().isArray()) { // must be a primitive array Class<?> componentType = source.getClass().getComponentType(); Class<?> wrapper = PrimitiveTypeConverter.getWrapperClassForPrimitive(componentType); int length = Array.getLength(source); items = (Object[]) Array.newInstance(wrapper, length); for (int i = 0; i < length; i++) { items[i] = Array.get(source, i); } } if (items == null) { // signal we did not handle the conversion by returning null return null; } else { // get the item type so we can convert them Class<?> erased = GenericTypeReflector.erase(type); Type componentType = null; if (type instanceof GenericArrayType) { // we need a generic array like Provider<Twig>[] componentType = ((GenericArrayType) type).getGenericComponentType(); } else if (erased.isArray()) { // we need an array like Twig[] componentType = erased.getComponentType(); } else if (Collection.class.isAssignableFrom(erased)) { // we need some type of collection like Set<Twig> Type exact = GenericTypeReflector.getExactSuperType(type, Collection.class); componentType = ((ParameterizedType) exact).getActualTypeArguments()[0]; } else { throw new IllegalArgumentException("Unsupported collection type " + type); } // convert all the items List<Object> convertedItems = new ArrayList<Object>(items.length); for (Object item : items) { if (item != null) { item = delegate.convert(item, componentType); if (item == null) { throw new IllegalStateException("Could not convert list item " + item + " to " + componentType); } } convertedItems.add(item); } return this.<T>createCollectionInstance(erased, componentType, convertedItems); } } @SuppressWarnings("unchecked") protected <T> T createCollectionInstance(Class<?> erased, Type componentType, List<Object> convertedItems) { // convert the list of items to the required collection type if (erased.isAssignableFrom(HashSet.class)) { T result = (T) new HashSet<Object>(convertedItems); return result; } else if (erased.isAssignableFrom(ArrayList.class)) { T result = (T) convertedItems; return result; } else if (erased.isAssignableFrom(EnumSet.class)) { EnumSet enumSet = EnumSet.noneOf((Class<? extends Enum>) componentType); for (Object item : convertedItems) { Enum<?> e; if (item instanceof Enum<?> == false) { Enum<?> tmp = Enum.valueOf((Class<? extends Enum>) erased, (String) item); e = tmp; } else { e = (Enum<?>) item; } enumSet.add(e); } return (T) enumSet; } else if (erased.isArray()) { Class<?> arrayClass = GenericTypeReflector.erase(componentType); Object[] array = (Object[]) Array.newInstance(arrayClass, convertedItems.size()); T result = (T) convertedItems.toArray(array); return result; } else { throw new IllegalArgumentException("Unsupported Collection type " + erased + ". Try declaring the interface instead of the concrete collection type."); } } }
Java
package com.vercer.engine.persist; import java.util.AbstractList; import java.util.Arrays; import java.util.Iterator; import java.util.List; import com.google.common.collect.AbstractIterator; import com.vercer.util.Strings; public class Path implements Comparable<Path> { private final static char FIELD = '.'; private final static char TYPE = '$'; private final static char[] SEPERATORS = { FIELD, TYPE }; public static final Path EMPTY_PATH = new Path(""); public static class Builder { private final StringBuilder builder = new StringBuilder(); public Builder(String property) { builder.append(property); } public Builder(Path base) { builder.append(base.toString()); } public Path build() { return new Path(builder.toString()); } public Builder field(String name) { ensureValidPart(name); if (builder.length() > 0) { builder.append(FIELD); } builder.append(name); return this; } private void ensureValidPart(String name) { if (Strings.firstIndexOf(name, SEPERATORS) >= 0) { throw new IllegalArgumentException("Path parts cannot contain " + Arrays.toString(SEPERATORS)); } } public Builder meta(String name) { builder.append(TYPE); builder.append(name); return this; } public Builder append(Path tail) { assert tail.isAbsolute() == false; builder.append(tail.value); return this; } public Builder append(Part part) { builder.append(part.text); return this; } } public static class Part { @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((text == null) ? 0 : text.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; Part other = (Part) obj; if (text == null) { if (other.text != null) return false; } else if (!text.equals(other.text)) return false; return true; } private final String text; private Part(String text) { this.text = text; } public boolean isField() { return text.charAt(0) == FIELD; } public boolean isMeta() { return text.charAt(0) == TYPE; } public boolean isRoot() { char c = text.charAt(0); for (char seperator : SEPERATORS) { if (c == seperator) { return false; } } return true; } public String getName() { if (isRoot()) { return text; } else { return text.substring(1); } } public int getIndex() { return Integer.parseInt(getName()); } } private final String value; public Path(String value) { this.value = value; } public List<Part> getParts() { return new AbstractList<Part>() { @Override public Part get(int index) { int begin; if (index == 0) { begin = 0; } else { begin = Strings.nthIndexOf(value, index, SEPERATORS); } if (begin >= 0) { int end = Strings.firstIndexOf(value, begin + 1, SEPERATORS); if (end > 0) { return new Part(value.substring(begin, end)); } else { return new Part(value.substring(begin)); } } else { return null; } } @Override public int size() { if (value.length() == 0) { return 0; } int index = 0; int count = 0; do { index = Strings.firstIndexOf(value, index + 2, SEPERATORS); count++; } while (index > 0); return count; } @Override public Iterator<Part> iterator() { return new AbstractIterator<Part>() { private int index; @Override protected Part computeNext() { if (index < 0) { return null; } int nextIndex = Strings.firstIndexOf(value, index + 1, SEPERATORS); String substring; if (nextIndex > 0) { substring = value.substring(index, nextIndex); } else { substring = value.substring(index); } index = nextIndex; return new Part(substring); } }; } }; } public Path tail(int start) { int index = Strings.nthIndexOf(value, start, SEPERATORS); return new Path(value.substring(index)); } public Path head() { int index = Strings.lastIndexOf(value, value.length() - 1, SEPERATORS); return new Path(value.substring(0, index)); } public Path head(int end) { int index = Strings.nthIndexOf(value, end, SEPERATORS); return new Path(value.substring(0, index)); } public Part firstPart() { int index = Strings.firstIndexOf(value, SEPERATORS); if (index > 0) { return new Part(value.substring(0, index)); } else { return new Part(value); } } public boolean isEmpty() { return value.length() == 0; } public boolean isAbsolute() { char c = value.charAt(0); for (char seperator : SEPERATORS) { if (c == seperator) { return false; } } return true; } @Override public String toString() { return value; } public boolean hasPrefix(Path path) { return path.isEmpty() || (value.startsWith(path.value) && (value.length() == path.value.length() || isSeperator(value.charAt(path.value.length())))); } private boolean isSeperator(char c) { for (char sperator : SEPERATORS) { if (c == sperator) { return true; } } return false; } public Part firstPartAfterPrefix(Path prefix) { assert hasPrefix(prefix); return getParts().get(prefix.getParts().size()); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((value == null) ? 0 : value.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (!(obj instanceof Path)) { return false; } Path other = (Path) obj; if (!value.equals(other.value)) { return false; } return true; } public int compareTo(Path o) { return value.compareTo(o.value); } public static Builder builder(Path path) { return new Builder(path); } }
Java
package com.vercer.engine.persist.standard; public class StandardCommand { final StrategyObjectDatastore datastore; public StandardCommand(StrategyObjectDatastore datastore) { this.datastore = datastore; if (datastore.getTransaction() != null && datastore.getTransaction().isActive() == false) { datastore.removeTransaction(); } } }
Java
package com.vercer.engine.persist.standard; import java.util.Arrays; import java.util.Collection; import com.vercer.engine.persist.StoreCommand; public class StandardStoreCommand extends StandardCommand implements StoreCommand { public StandardStoreCommand(StrategyObjectDatastore datastore) { super(datastore); } public <T> SingleStoreCommand<T> instance(T instance) { return new StandardSingleStoreCommand<T>(this, instance); } public <T> MultipleStoreCommand<T> instances(Collection<T> instances) { return new StandardMultipleStoreCommand<T>(this, instances); } public <T> MultipleStoreCommand<T> instances(T... instances) { return new StandardMultipleStoreCommand<T>(this, Arrays.asList(instances)); }; }
Java
package com.vercer.engine.persist.standard; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import com.google.appengine.api.datastore.Key; import com.google.common.collect.MapMaker; import com.vercer.util.reference.ObjectReference; import com.vercer.util.reference.SimpleObjectReference; public class KeyCache { private static class ActivatableKeyReference extends SimpleObjectReference<Key> { private static final long serialVersionUID = 1L; private boolean activated; public ActivatableKeyReference(Key object) { super(object); } } private Map<Key, Object> cacheByKey = new MapMaker() .weakValues() .concurrencyLevel(1) .makeMap(); private Map<Object, ObjectReference<Key>> cacheByValue = new MapMaker() .weakKeys() .concurrencyLevel(1) .makeMap(); public void cache(Key key, Object object) { cacheByKey.put(key, object); SimpleObjectReference<Key> reference = new ActivatableKeyReference(key); cacheByValue.put(object, reference); } public void cacheKeyReferenceForInstance(Object object, ObjectReference<Key> keyReference) { if (cacheByValue.put(object, keyReference) != null) { throw new IllegalStateException("Object already existed: " + object); } } public void clear() { this.cacheByKey.clear(); this.cacheByValue.clear(); } public Key evictInstance(Object reference) { ObjectReference<Key> keyReference = cacheByValue.remove(reference); if (keyReference != null) { Key key = keyReference.get(); cacheByKey.remove(key); return key; } else { return null; } } public Object evictKey(Key key) { Object object = cacheByKey.remove(key); if (object == null) { throw new NoSuchElementException("Key " + key + " was not cached"); } ObjectReference<Key> removed = cacheByValue.remove(object); assert removed.get() == key; return object; } @SuppressWarnings("unchecked") public <T> T getInstance(Key key) { return (T) cacheByKey.get(key); } public Key getKey(Object instance) { ObjectReference<Key> reference = cacheByValue.get(instance); if (reference != null) { return reference.get(); } else { return null; } } public ObjectReference<Key> getKeyReference(Object instance) { return cacheByValue.get(instance); } public Set<Key> getAllKeys() { return cacheByKey.keySet(); } public Key getKeyAndActivate(Object instance) { // we are sure of the key reference type because the full key and instance must have been added ActivatableKeyReference reference = (ActivatableKeyReference) cacheByValue.get(instance); if (reference != null) { if (reference.activated) { throw new IllegalStateException("Instance was already activated"); } reference.activated = true; return reference.get(); } else { return null; } } public boolean containsKey(Key key) { return cacheByKey.containsKey(key); } }
Java
package com.vercer.engine.persist.standard; import com.google.appengine.api.datastore.Query; import com.vercer.engine.persist.FindCommand.ChildFindCommand; final class StandardBranchFindCommand<T> extends StandardTypedFindCommand<T, ChildFindCommand<T>> implements ChildFindCommand<T> { private final StandardTypedFindCommand<T, ?> parent; StandardBranchFindCommand(StandardTypedFindCommand<T, ?> parent) { super(parent.datastore); this.parent = parent; } @Override protected Query newQuery() { Query query = parent.newQuery(); applyFilters(query); return query; } @Override public StandardRootFindCommand<T> getRootCommand() { return parent.getRootCommand(); } }
Java
package com.vercer.engine.persist.standard; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.Query.SortPredicate; public class StandardMergeParentsCommand<P> extends StandardBaseParentsCommand<P> { private final List<Iterator<Entity>> childEntityIterators; private final List<SortPredicate> sorts; public StandardMergeParentsCommand(StandardTypedFindCommand<?, ?> command, List<Iterator<Entity>> childEntityIterators, List<SortPredicate> sorts) { super(command); this.childEntityIterators = childEntityIterators; this.sorts = sorts; } public Iterator<P> returnParentsNow() { // keys only child queries cannot be sorted as fields are missing if (childCommand.getRootCommand().isKeysOnly()) { // make an entity cache with room to hold a round of fetches final int maxSize = getFetchSize() * childEntityIterators.size() ; LinkedHashMap<Key, Entity> keyToEntity = new LinkedHashMap<Key, Entity>((int) (maxSize / 0.75)) { private static final long serialVersionUID = 1L; @Override protected boolean removeEldestEntry(java.util.Map.Entry<Key, Entity> eldest) { return size() >= maxSize; } }; // cannot merge children so must get parent entities first List<Iterator<Entity>> parentEntityIterators = new ArrayList<Iterator<Entity>>(childEntityIterators.size()); for (Iterator<Entity> child : childEntityIterators) { // convert children to parents - may be dups so use a cache Iterator<Entity> parentEntities = childEntitiesToParentEntities(child, keyToEntity); parentEntities = applyEntityFilter(parentEntities); parentEntityIterators.add(parentEntities); } // merge all the parent iterators into a single iterator Iterator<Entity> mergedParentEntities = mergeEntities(parentEntityIterators, sorts); // convert the entities into instances to return return entityToInstanceIterator(mergedParentEntities, false); } else { // we can merge the children first which gets rid of duplicates Iterator<Entity> mergedChildEntities = mergeEntities(childEntityIterators, sorts); mergedChildEntities = applyEntityFilter(mergedChildEntities); // get parents for all children at the same time - no dups so no cache Iterator<Entity> parentEntities = childEntitiesToParentEntities(mergedChildEntities, null); return entityToInstanceIterator(parentEntities, false); } } }
Java
package com.vercer.engine.persist.standard; import com.vercer.engine.persist.FindCommand; public class StandardFindCommand extends StandardCommand implements FindCommand { public StandardFindCommand(StrategyObjectDatastore datastore) { super(datastore); } public <T> RootFindCommand<T> type(Class<T> type) { return new StandardRootFindCommand<T>(type, datastore); } }
Java
package com.vercer.engine.persist.standard; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.concurrent.Future; import com.google.appengine.api.datastore.AsyncDatastoreHelper; import com.google.appengine.api.datastore.Entity; import com.google.appengine.api.datastore.Key; import com.google.appengine.api.datastore.Transaction; import com.google.appengine.api.utils.FutureWrapper; import com.google.common.collect.Maps; import com.vercer.engine.persist.StoreCommand.CommonStoreCommand; abstract class StandardBaseStoreCommand<T, C extends CommonStoreCommand<T, C>> implements CommonStoreCommand<T, C> { final StandardStoreCommand command; Collection<T> instances; Object parent; boolean batch; boolean unique; public StandardBaseStoreCommand(StandardStoreCommand command) { this.command = command; } @SuppressWarnings("unchecked") public C parent(Object parent) { return (C) this; } @SuppressWarnings("unchecked") public C batch() { batch = true; return (C) this; } @SuppressWarnings("unchecked") public C ensureUniqueKey() { unique = true; return (C) this; } void checkUniqueKeys(Collection<Entity> entities) { List<Key> keys = new ArrayList<Key>(entities.size()); for (Entity entity : entities) { keys.add(entity.getKey()); } Map<Key, Entity> map = command.datastore.serviceGet(keys); if (!map.isEmpty()) { throw new IllegalStateException("Keys already exist: " + map); } } Future<Map<T, Key>> storeResultsLater() { Transaction transaction = command.datastore.getTransaction(); final Map<T, Entity> entities = command.datastore.instancesToEntities(instances, parent, batch); if (unique) { checkUniqueKeys(entities.values()); } final Future<List<Key>> put = AsyncDatastoreHelper.put(transaction, entities.values()); return new FutureWrapper<List<Key>, Map<T,Key>>(put) { @Override protected Throwable convertException(Throwable t) { return t; } @Override protected Map<T, Key> wrap(List<Key> list) throws Exception { LinkedHashMap<T, Key> result = Maps.newLinkedHashMap(); Iterator<T> instances = entities.keySet().iterator(); Iterator<Key> keys = list.iterator(); while (instances.hasNext()) { result.put(instances.next(), keys.next()); } return result; } }; } }
Java