code
stringlengths
3
1.18M
language
stringclasses
1 value
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.impl; import java.io.IOException; import java.net.Socket; import org.apache.ogt.http.params.HttpConnectionParams; import org.apache.ogt.http.params.HttpParams; /** * Default implementation of a client-side HTTP connection. * <p> * The following parameters can be used to customize the behavior of this * class: * <ul> * <li>{@link org.apache.ogt.http.params.CoreProtocolPNames#HTTP_ELEMENT_CHARSET}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#TCP_NODELAY}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_TIMEOUT}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SO_LINGER}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#SOCKET_BUFFER_SIZE}</li> * <li>{@link org.apache.ogt.http.params.CoreConnectionPNames#MAX_LINE_LENGTH}</li> * </ul> * * @since 4.0 */ public class DefaultHttpClientConnection extends SocketHttpClientConnection { public DefaultHttpClientConnection() { super(); } public void bind( final Socket socket, final HttpParams params) throws IOException { if (socket == null) { throw new IllegalArgumentException("Socket may not be null"); } if (params == null) { throw new IllegalArgumentException("HTTP parameters may not be null"); } assertNotOpen(); socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(params)); socket.setSoTimeout(HttpConnectionParams.getSoTimeout(params)); int linger = HttpConnectionParams.getLinger(params); if (linger >= 0) { socket.setSoLinger(linger > 0, linger); } super.bind(socket, params); } public String toString() { StringBuffer buffer = new StringBuffer(); buffer.append("["); if (isOpen()) { buffer.append(getRemotePort()); } else { buffer.append("closed"); } buffer.append("]"); return buffer.toString(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * Signals that an HTTP method is not supported. * * @since 4.0 */ public class MethodNotSupportedException extends HttpException { private static final long serialVersionUID = 3365359036840171201L; /** * Creates a new MethodNotSupportedException with the specified detail message. * * @param message The exception detail message */ public MethodNotSupportedException(final String message) { super(message); } /** * Creates a new MethodNotSupportedException with the specified detail message and cause. * * @param message the exception detail message * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt> * if the cause is unavailable, unknown, or not a <tt>Throwable</tt> */ public MethodNotSupportedException(final String message, final Throwable cause) { super(message, cause); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.Serializable; import java.util.Locale; import org.apache.ogt.http.util.CharArrayBuffer; import org.apache.ogt.http.util.LangUtils; /** * Holds all of the variables needed to describe an HTTP connection to a host. * This includes remote host name, port and scheme. * * * @since 4.0 */ //@Immutable public final class HttpHost implements Cloneable, Serializable { private static final long serialVersionUID = -7529410654042457626L; /** The default scheme is "http". */ public static final String DEFAULT_SCHEME_NAME = "http"; /** The host to use. */ protected final String hostname; /** The lowercase host, for {@link #equals} and {@link #hashCode}. */ protected final String lcHostname; /** The port to use. */ protected final int port; /** The scheme (lowercased) */ protected final String schemeName; /** * Creates a new {@link HttpHost HttpHost}, specifying all values. * Constructor for HttpHost. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * <code>-1</code> indicates the scheme default port. * @param scheme the name of the scheme. * <code>null</code> indicates the * {@link #DEFAULT_SCHEME_NAME default scheme} */ public HttpHost(final String hostname, int port, final String scheme) { super(); if (hostname == null) { throw new IllegalArgumentException("Host name may not be null"); } this.hostname = hostname; this.lcHostname = hostname.toLowerCase(Locale.ENGLISH); if (scheme != null) { this.schemeName = scheme.toLowerCase(Locale.ENGLISH); } else { this.schemeName = DEFAULT_SCHEME_NAME; } this.port = port; } /** * Creates a new {@link HttpHost HttpHost}, with default scheme. * * @param hostname the hostname (IP or DNS name) * @param port the port number. * <code>-1</code> indicates the scheme default port. */ public HttpHost(final String hostname, int port) { this(hostname, port, null); } /** * Creates a new {@link HttpHost HttpHost}, with default scheme and port. * * @param hostname the hostname (IP or DNS name) */ public HttpHost(final String hostname) { this(hostname, -1, null); } /** * Copy constructor for {@link HttpHost HttpHost}. * * @param httphost the HTTP host to copy details from */ public HttpHost (final HttpHost httphost) { this(httphost.hostname, httphost.port, httphost.schemeName); } /** * Returns the host name. * * @return the host name (IP or DNS name) */ public String getHostName() { return this.hostname; } /** * Returns the port. * * @return the host port, or <code>-1</code> if not set */ public int getPort() { return this.port; } /** * Returns the scheme name. * * @return the scheme name */ public String getSchemeName() { return this.schemeName; } /** * Return the host URI, as a string. * * @return the host URI */ public String toURI() { CharArrayBuffer buffer = new CharArrayBuffer(32); buffer.append(this.schemeName); buffer.append("://"); buffer.append(this.hostname); if (this.port != -1) { buffer.append(':'); buffer.append(Integer.toString(this.port)); } return buffer.toString(); } /** * Obtains the host string, without scheme prefix. * * @return the host string, for example <code>localhost:8080</code> */ public String toHostString() { if (this.port != -1) { //the highest port number is 65535, which is length 6 with the addition of the colon CharArrayBuffer buffer = new CharArrayBuffer(this.hostname.length() + 6); buffer.append(this.hostname); buffer.append(":"); buffer.append(Integer.toString(this.port)); return buffer.toString(); } else { return this.hostname; } } public String toString() { return toURI(); } public boolean equals(final Object obj) { if (this == obj) return true; if (obj instanceof HttpHost) { HttpHost that = (HttpHost) obj; return this.lcHostname.equals(that.lcHostname) && this.port == that.port && this.schemeName.equals(that.schemeName); } else { return false; } } /** * @see java.lang.Object#hashCode() */ public int hashCode() { int hash = LangUtils.HASH_SEED; hash = LangUtils.hashCode(hash, this.lcHostname); hash = LangUtils.hashCode(hash, this.port); hash = LangUtils.hashCode(hash, this.schemeName); return hash; } public Object clone() throws CloneNotSupportedException { return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; /** * Signals a malformed chunked stream. * * @since 4.0 */ public class MalformedChunkCodingException extends IOException { private static final long serialVersionUID = 2158560246948994524L; /** * Creates a MalformedChunkCodingException without a detail message. */ public MalformedChunkCodingException() { super(); } /** * Creates a MalformedChunkCodingException with the specified detail message. * * @param message The exception detail message */ public MalformedChunkCodingException(final String message) { super(message); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; /** * A client-side HTTP connection, which can be used for sending * requests and receiving responses. * * @since 4.0 */ public interface HttpClientConnection extends HttpConnection { /** * Checks if response data is available from the connection. May wait for * the specified time until some data becomes available. Note that some * implementations may completely ignore the timeout parameter. * * @param timeout the maximum time in milliseconds to wait for data * @return true if data is available; false if there was no data available * even after waiting for <code>timeout</code> milliseconds. * @throws IOException if an error happens on the connection */ boolean isResponseAvailable(int timeout) throws IOException; /** * Sends the request line and all headers over the connection. * @param request the request whose headers to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendRequestHeader(HttpRequest request) throws HttpException, IOException; /** * Sends the request entity over the connection. * @param request the request whose entity to send. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void sendRequestEntity(HttpEntityEnclosingRequest request) throws HttpException, IOException; /** * Receives the request line and headers of the next response available from * this connection. The caller should examine the HttpResponse object to * find out if it should try to receive a response entity as well. * * @return a new HttpResponse object with status line and headers * initialized. * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ HttpResponse receiveResponseHeader() throws HttpException, IOException; /** * Receives the next response entity available from this connection and * attaches it to an existing HttpResponse object. * * @param response the response to attach the entity to * @throws HttpException in case of HTTP protocol violation * @throws IOException in case of an I/O error */ void receiveResponseEntity(HttpResponse response) throws HttpException, IOException; /** * Writes out all pending buffered data over the open connection. * * @throws IOException in case of an I/O error */ void flush() throws IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * Signals that an HTTP protocol violation has occurred. * For example a malformed status line or headers, a missing message body, etc. * * * @since 4.0 */ public class ProtocolException extends HttpException { private static final long serialVersionUID = -2143571074341228994L; /** * Creates a new ProtocolException with a <tt>null</tt> detail message. */ public ProtocolException() { super(); } /** * Creates a new ProtocolException with the specified detail message. * * @param message The exception detail message */ public ProtocolException(String message) { super(message); } /** * Creates a new ProtocolException with the specified detail message and cause. * * @param message the exception detail message * @param cause the <tt>Throwable</tt> that caused this exception, or <tt>null</tt> * if the cause is unavailable, unknown, or not a <tt>Throwable</tt> */ public ProtocolException(String message, Throwable cause) { super(message, cause); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * The first line of a Response message is the Status-Line, consisting * of the protocol version followed by a numeric status code and its * associated textual phrase, with each element separated by SP * characters. No CR or LF is allowed except in the final CRLF sequence. * <pre> * Status-Line = HTTP-Version SP Status-Code SP Reason-Phrase CRLF * </pre> * * @see HttpStatus * @version $Id: StatusLine.java 937295 2010-04-23 13:44:00Z olegk $ * * @since 4.0 */ public interface StatusLine { ProtocolVersion getProtocolVersion(); int getStatusCode(); String getReasonPhrase(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.util.Locale; /** * After receiving and interpreting a request message, a server responds * with an HTTP response message. * <pre> * Response = Status-Line * *(( general-header * | response-header * | entity-header ) CRLF) * CRLF * [ message-body ] * </pre> * * @since 4.0 */ public interface HttpResponse extends HttpMessage { /** * Obtains the status line of this response. * The status line can be set using one of the * {@link #setStatusLine setStatusLine} methods, * or it can be initialized in a constructor. * * @return the status line, or <code>null</code> if not yet set */ StatusLine getStatusLine(); /** * Sets the status line of this response. * * @param statusline the status line of this response */ void setStatusLine(StatusLine statusline); /** * Sets the status line of this response. * The reason phrase will be determined based on the current * {@link #getLocale locale}. * * @param ver the HTTP version * @param code the status code */ void setStatusLine(ProtocolVersion ver, int code); /** * Sets the status line of this response with a reason phrase. * * @param ver the HTTP version * @param code the status code * @param reason the reason phrase, or <code>null</code> to omit */ void setStatusLine(ProtocolVersion ver, int code, String reason); /** * Updates the status line of this response with a new status code. * The status line can only be updated if it is available. It must * have been set either explicitly or in a constructor. * <br/> * The reason phrase will be updated according to the new status code, * based on the current {@link #getLocale locale}. It can be set * explicitly using {@link #setReasonPhrase setReasonPhrase}. * * @param code the HTTP status code. * * @throws IllegalStateException * if the status line has not be set * * @see HttpStatus * @see #setStatusLine(StatusLine) * @see #setStatusLine(ProtocolVersion,int) */ void setStatusCode(int code) throws IllegalStateException; /** * Updates the status line of this response with a new reason phrase. * The status line can only be updated if it is available. It must * have been set either explicitly or in a constructor. * * @param reason the new reason phrase as a single-line string, or * <code>null</code> to unset the reason phrase * * @throws IllegalStateException * if the status line has not be set * * @see #setStatusLine(StatusLine) * @see #setStatusLine(ProtocolVersion,int) */ void setReasonPhrase(String reason) throws IllegalStateException; /** * Obtains the message entity of this response, if any. * The entity is provided by calling {@link #setEntity setEntity}. * * @return the response entity, or * <code>null</code> if there is none */ HttpEntity getEntity(); /** * Associates a response entity with this response. * * @param entity the entity to associate with this response, or * <code>null</code> to unset */ void setEntity(HttpEntity entity); /** * Obtains the locale of this response. * The locale is used to determine the reason phrase * for the {@link #setStatusCode status code}. * It can be changed using {@link #setLocale setLocale}. * * @return the locale of this response, never <code>null</code> */ Locale getLocale(); /** * Changes the locale of this response. * If there is a status line, it's reason phrase will be updated * according to the status code and new locale. * * @param loc the new locale * * @see #getLocale getLocale * @see #setStatusCode setStatusCode */ void setLocale(Locale loc); }
Java
/* * $Header: $ * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * A request with an entity. * * @since 4.0 */ public interface HttpEntityEnclosingRequest extends HttpRequest { /** * Tells if this request should use the expect-continue handshake. * The expect continue handshake gives the server a chance to decide * whether to accept the entity enclosing request before the possibly * lengthy entity is sent across the wire. * @return true if the expect continue handshake should be used, false if * not. */ boolean expectContinue(); /** * Associates the entity with this request. * * @param entity the entity to send. */ void setEntity(HttpEntity entity); /** * Returns the entity associated with this request. * * @return entity */ HttpEntity getEntity(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * A request message from a client to a server includes, within the * first line of that message, the method to be applied to the resource, * the identifier of the resource, and the protocol version in use. * <pre> * Request = Request-Line * *(( general-header * | request-header * | entity-header ) CRLF) * CRLF * [ message-body ] * </pre> * * @since 4.0 */ public interface HttpRequest extends HttpMessage { /** * Returns the request line of this request. * @return the request line. */ RequestLine getRequestLine(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import org.apache.ogt.http.params.HttpParams; /** * HTTP messages consist of requests from client to server and responses * from server to client. * <pre> * HTTP-message = Request | Response ; HTTP/1.1 messages * </pre> * <p> * HTTP messages use the generic message format of RFC 822 for * transferring entities (the payload of the message). Both types * of message consist of a start-line, zero or more header fields * (also known as "headers"), an empty line (i.e., a line with nothing * preceding the CRLF) indicating the end of the header fields, * and possibly a message-body. * </p> * <pre> * generic-message = start-line * *(message-header CRLF) * CRLF * [ message-body ] * start-line = Request-Line | Status-Line * </pre> * * @since 4.0 */ public interface HttpMessage { /** * Returns the protocol version this message is compatible with. */ ProtocolVersion getProtocolVersion(); /** * Checks if a certain header is present in this message. Header values are * ignored. * * @param name the header name to check for. * @return true if at least one header with this name is present. */ boolean containsHeader(String name); /** * Returns all the headers with a specified name of this message. Header values * are ignored. Headers are orderd in the sequence they will be sent over a * connection. * * @param name the name of the headers to return. * @return the headers whose name property equals <code>name</code>. */ Header[] getHeaders(String name); /** * Returns the first header with a specified name of this message. Header * values are ignored. If there is more than one matching header in the * message the first element of {@link #getHeaders(String)} is returned. * If there is no matching header in the message <code>null</code> is * returned. * * @param name the name of the header to return. * @return the first header whose name property equals <code>name</code> * or <code>null</code> if no such header could be found. */ Header getFirstHeader(String name); /** * Returns the last header with a specified name of this message. Header values * are ignored. If there is more than one matching header in the message the * last element of {@link #getHeaders(String)} is returned. If there is no * matching header in the message <code>null</code> is returned. * * @param name the name of the header to return. * @return the last header whose name property equals <code>name</code>. * or <code>null</code> if no such header could be found. */ Header getLastHeader(String name); /** * Returns all the headers of this message. Headers are orderd in the sequence * they will be sent over a connection. * * @return all the headers of this message */ Header[] getAllHeaders(); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param header the header to append. */ void addHeader(Header header); /** * Adds a header to this message. The header will be appended to the end of * the list. * * @param name the name of the header. * @param value the value of the header. */ void addHeader(String name, String value); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param header the header to set. */ void setHeader(Header header); /** * Overwrites the first header with the same name. The new header will be appended to * the end of the list, if no header with the given name can be found. * * @param name the name of the header. * @param value the value of the header. */ void setHeader(String name, String value); /** * Overwrites all the headers in the message. * * @param headers the array of headers to set. */ void setHeaders(Header[] headers); /** * Removes a header from this message. * * @param header the header to remove. */ void removeHeader(Header header); /** * Removes all headers with a certain name from this message. * * @param name The name of the headers to remove. */ void removeHeaders(String name); /** * Returns an iterator of all the headers. * * @return Iterator that returns Header objects in the sequence they are * sent over a connection. */ HeaderIterator headerIterator(); /** * Returns an iterator of the headers with a given name. * * @param name the name of the headers over which to iterate, or * <code>null</code> for all headers * * @return Iterator that returns Header objects with the argument name * in the sequence they are sent over a connection. */ HeaderIterator headerIterator(String name); /** * Returns the parameters effective for this message as set by * {@link #setParams(HttpParams)}. */ HttpParams getParams(); /** * Provides parameters to be used for the processing of this message. * @param params the parameters */ void setParams(HttpParams params); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.util; import java.io.Serializable; /** * A resizable byte array. * * @since 4.0 */ public final class ByteArrayBuffer implements Serializable { private static final long serialVersionUID = 4359112959524048036L; private byte[] buffer; private int len; /** * Creates an instance of {@link ByteArrayBuffer} with the given initial * capacity. * * @param capacity the capacity */ public ByteArrayBuffer(int capacity) { super(); if (capacity < 0) { throw new IllegalArgumentException("Buffer capacity may not be negative"); } this.buffer = new byte[capacity]; } private void expand(int newlen) { byte newbuffer[] = new byte[Math.max(this.buffer.length << 1, newlen)]; System.arraycopy(this.buffer, 0, newbuffer, 0, this.len); this.buffer = newbuffer; } /** * Appends <code>len</code> bytes to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> bytes. * * @param b the bytes to be appended. * @param off the index of the first byte to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> if out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final byte[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int newlen = this.len + len; if (newlen > this.buffer.length) { expand(newlen); } System.arraycopy(b, off, this.buffer, this.len, len); this.len = newlen; } /** * Appends <code>b</code> byte to this buffer. The capacity of the buffer * is increased, if necessary, to accommodate the additional byte. * * @param b the byte to be appended. */ public void append(int b) { int newlen = this.len + 1; if (newlen > this.buffer.length) { expand(newlen); } this.buffer[this.len] = (byte)b; this.len = newlen; } /** * Appends <code>len</code> chars to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased if necessary to accommodate all <code>len</code> chars. * <p> * The chars are converted to bytes using simple cast. * * @param b the chars to be appended. * @param off the index of the first char to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> if out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final char[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int oldlen = this.len; int newlen = oldlen + len; if (newlen > this.buffer.length) { expand(newlen); } for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) { this.buffer[i2] = (byte) b[i1]; } this.len = newlen; } /** * Appends <code>len</code> chars to this buffer from the given source * char array buffer starting at index <code>off</code>. The capacity * of the buffer is increased if necessary to accommodate all * <code>len</code> chars. * <p> * The chars are converted to bytes using simple cast. * * @param b the chars to be appended. * @param off the index of the first char to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> if out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final CharArrayBuffer b, int off, int len) { if (b == null) { return; } append(b.buffer(), off, len); } /** * Clears content of the buffer. The underlying byte array is not resized. */ public void clear() { this.len = 0; } /** * Converts the content of this buffer to an array of bytes. * * @return byte array */ public byte[] toByteArray() { byte[] b = new byte[this.len]; if (this.len > 0) { System.arraycopy(this.buffer, 0, b, 0, this.len); } return b; } /** * Returns the <code>byte</code> value in this buffer at the specified * index. The index argument must be greater than or equal to * <code>0</code>, and less than the length of this buffer. * * @param i the index of the desired byte value. * @return the byte value at the specified index. * @throws IndexOutOfBoundsException if <code>index</code> is * negative or greater than or equal to {@link #length()}. */ public int byteAt(int i) { return this.buffer[i]; } /** * Returns the current capacity. The capacity is the amount of storage * available for newly appended bytes, beyond which an allocation * will occur. * * @return the current capacity */ public int capacity() { return this.buffer.length; } /** * Returns the length of the buffer (byte count). * * @return the length of the buffer */ public int length() { return this.len; } /** * Ensures that the capacity is at least equal to the specified minimum. * If the current capacity is less than the argument, then a new internal * array is allocated with greater capacity. If the <code>required</code> * argument is non-positive, this method takes no action. * * @param required the minimum required capacity. * * @since 4.1 */ public void ensureCapacity(int required) { if (required <= 0) { return; } int available = this.buffer.length - this.len; if (required > available) { expand(this.len + required); } } /** * Returns reference to the underlying byte array. * * @return the byte array. */ public byte[] buffer() { return this.buffer; } /** * Sets the length of the buffer. The new length value is expected to be * less than the current capacity and greater than or equal to * <code>0</code>. * * @param len the new length * @throws IndexOutOfBoundsException if the * <code>len</code> argument is greater than the current * capacity of the buffer or less than <code>0</code>. */ public void setLength(int len) { if (len < 0 || len > this.buffer.length) { throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length); } this.len = len; } /** * Returns <code>true</code> if this buffer is empty, that is, its * {@link #length()} is equal to <code>0</code>. * @return <code>true</code> if this buffer is empty, <code>false</code> * otherwise. */ public boolean isEmpty() { return this.len == 0; } /** * Returns <code>true</code> if this buffer is full, that is, its * {@link #length()} is equal to its {@link #capacity()}. * @return <code>true</code> if this buffer is full, <code>false</code> * otherwise. */ public boolean isFull() { return this.len == this.buffer.length; } /** * Returns the index within this buffer of the first occurrence of the * specified byte, starting the search at the specified * <code>beginIndex</code> and finishing at <code>endIndex</code>. * If no such byte occurs in this buffer within the specified bounds, * <code>-1</code> is returned. * <p> * There is no restriction on the value of <code>beginIndex</code> and * <code>endIndex</code>. If <code>beginIndex</code> is negative, * it has the same effect as if it were zero. If <code>endIndex</code> is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the <code>beginIndex</code> is greater than * the <code>endIndex</code>, <code>-1</code> is returned. * * @param b the byte to search for. * @param beginIndex the index to start the search from. * @param endIndex the index to finish the search at. * @return the index of the first occurrence of the byte in the buffer * within the given bounds, or <code>-1</code> if the byte does * not occur. * * @since 4.1 */ public int indexOf(byte b, int beginIndex, int endIndex) { if (beginIndex < 0) { beginIndex = 0; } if (endIndex > this.len) { endIndex = this.len; } if (beginIndex > endIndex) { return -1; } for (int i = beginIndex; i < endIndex; i++) { if (this.buffer[i] == b) { return i; } } return -1; } /** * Returns the index within this buffer of the first occurrence of the * specified byte, starting the search at <code>0</code> and finishing * at {@link #length()}. If no such byte occurs in this buffer within * those bounds, <code>-1</code> is returned. * * @param b the byte to search for. * @return the index of the first occurrence of the byte in the * buffer, or <code>-1</code> if the byte does not occur. * * @since 4.1 */ public int indexOf(byte b) { return indexOf(b, 0, this.len); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.util; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.io.Reader; import org.apache.ogt.http.HeaderElement; import org.apache.ogt.http.HttpEntity; import org.apache.ogt.http.NameValuePair; import org.apache.ogt.http.ParseException; import org.apache.ogt.http.protocol.HTTP; /** * Static helpers for dealing with {@link HttpEntity}s. * * @since 4.0 */ public final class EntityUtils { private EntityUtils() { } /** * Ensures that the entity content is fully consumed and the content stream, if exists, * is closed. * * @param entity * @throws IOException if an error occurs reading the input stream * * @since 4.1 */ public static void consume(final HttpEntity entity) throws IOException { if (entity == null) { return; } if (entity.isStreaming()) { InputStream instream = entity.getContent(); if (instream != null) { instream.close(); } } } /** * Read the contents of an entity and return it as a byte array. * * @param entity * @return byte array containing the entity content. May be null if * {@link HttpEntity#getContent()} is null. * @throws IOException if an error occurs reading the input stream * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE */ public static byte[] toByteArray(final HttpEntity entity) throws IOException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } ByteArrayBuffer buffer = new ByteArrayBuffer(i); byte[] tmp = new byte[4096]; int l; while((l = instream.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toByteArray(); } finally { instream.close(); } } /** * Obtains character set of the entity, if known. * * @param entity must not be null * @return the character set, or null if not found * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null */ public static String getContentCharSet(final HttpEntity entity) throws ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } String charset = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { NameValuePair param = values[0].getParameterByName("charset"); if (param != null) { charset = param.getValue(); } } } return charset; } /** * Obtains mime type of the entity, if known. * * @param entity must not be null * @return the character set, or null if not found * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null * * @since 4.1 */ public static String getContentMimeType(final HttpEntity entity) throws ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } String mimeType = null; if (entity.getContentType() != null) { HeaderElement values[] = entity.getContentType().getElements(); if (values.length > 0) { mimeType = values[0].getName(); } } return mimeType; } /** * Get the entity content as a String, using the provided default character set * if none is found in the entity. * If defaultCharset is null, the default "ISO-8859-1" is used. * * @param entity must not be null * @param defaultCharset character set to be applied if none found in the entity * @return the entity content as a String. May be null if * {@link HttpEntity#getContent()} is null. * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream */ public static String toString( final HttpEntity entity, final String defaultCharset) throws IOException, ParseException { if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } InputStream instream = entity.getContent(); if (instream == null) { return null; } try { if (entity.getContentLength() > Integer.MAX_VALUE) { throw new IllegalArgumentException("HTTP entity too large to be buffered in memory"); } int i = (int)entity.getContentLength(); if (i < 0) { i = 4096; } String charset = getContentCharSet(entity); if (charset == null) { charset = defaultCharset; } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } Reader reader = new InputStreamReader(instream, charset); CharArrayBuffer buffer = new CharArrayBuffer(i); char[] tmp = new char[1024]; int l; while((l = reader.read(tmp)) != -1) { buffer.append(tmp, 0, l); } return buffer.toString(); } finally { instream.close(); } } /** * Read the contents of an entity and return it as a String. * The content is converted using the character set from the entity (if any), * failing that, "ISO-8859-1" is used. * * @param entity * @return String containing the content. * @throws ParseException if header elements cannot be parsed * @throws IllegalArgumentException if entity is null or if content length > Integer.MAX_VALUE * @throws IOException if an error occurs reading the input stream */ public static String toString(final HttpEntity entity) throws IOException, ParseException { return toString(entity, null); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.util; /** * A set of utility methods to help produce consistent * {@link Object#equals equals} and {@link Object#hashCode hashCode} methods. * * * @since 4.0 */ public final class LangUtils { public static final int HASH_SEED = 17; public static final int HASH_OFFSET = 37; /** Disabled default constructor. */ private LangUtils() { } public static int hashCode(final int seed, final int hashcode) { return seed * HASH_OFFSET + hashcode; } public static int hashCode(final int seed, final boolean b) { return hashCode(seed, b ? 1 : 0); } public static int hashCode(final int seed, final Object obj) { return hashCode(seed, obj != null ? obj.hashCode() : 0); } /** * Check if two objects are equal. * * @param obj1 first object to compare, may be {@code null} * @param obj2 second object to compare, may be {@code null} * @return {@code true} if the objects are equal or both null */ public static boolean equals(final Object obj1, final Object obj2) { return obj1 == null ? obj2 == null : obj1.equals(obj2); } /** * Check if two object arrays are equal. * <p> * <ul> * <li>If both parameters are null, return {@code true}</li> * <li>If one parameter is null, return {@code false}</li> * <li>If the array lengths are different, return {@code false}</li> * <li>Compare array elements using .equals(); return {@code false} if any comparisons fail.</li> * <li>Return {@code true}</li> * </ul> * * @param a1 first array to compare, may be {@code null} * @param a2 second array to compare, may be {@code null} * @return {@code true} if the arrays are equal or both null */ public static boolean equals(final Object[] a1, final Object[] a2) { if (a1 == null) { if (a2 == null) { return true; } else { return false; } } else { if (a2 != null && a1.length == a2.length) { for (int i = 0; i < a1.length; i++) { if (!equals(a1[i], a2[i])) { return false; } } return true; } else { return false; } } } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.util; import java.io.Serializable; import org.apache.ogt.http.protocol.HTTP; /** * A resizable char array. * * @since 4.0 */ public final class CharArrayBuffer implements Serializable { private static final long serialVersionUID = -6208952725094867135L; private char[] buffer; private int len; /** * Creates an instance of {@link CharArrayBuffer} with the given initial * capacity. * * @param capacity the capacity */ public CharArrayBuffer(int capacity) { super(); if (capacity < 0) { throw new IllegalArgumentException("Buffer capacity may not be negative"); } this.buffer = new char[capacity]; } private void expand(int newlen) { char newbuffer[] = new char[Math.max(this.buffer.length << 1, newlen)]; System.arraycopy(this.buffer, 0, newbuffer, 0, this.len); this.buffer = newbuffer; } /** * Appends <code>len</code> chars to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> chars. * * @param b the chars to be appended. * @param off the index of the first char to append. * @param len the number of chars to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final char[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int newlen = this.len + len; if (newlen > this.buffer.length) { expand(newlen); } System.arraycopy(b, off, this.buffer, this.len, len); this.len = newlen; } /** * Appends chars of the given string to this buffer. The capacity of the * buffer is increased, if necessary, to accommodate all chars. * * @param str the string. */ public void append(String str) { if (str == null) { str = "null"; } int strlen = str.length(); int newlen = this.len + strlen; if (newlen > this.buffer.length) { expand(newlen); } str.getChars(0, strlen, this.buffer, this.len); this.len = newlen; } /** * Appends <code>len</code> chars to this buffer from the given source * buffer starting at index <code>off</code>. The capacity of the * destination buffer is increased, if necessary, to accommodate all * <code>len</code> chars. * * @param b the source buffer to be appended. * @param off the index of the first char to append. * @param len the number of chars to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final CharArrayBuffer b, int off, int len) { if (b == null) { return; } append(b.buffer, off, len); } /** * Appends all chars to this buffer from the given source buffer starting * at index <code>0</code>. The capacity of the destination buffer is * increased, if necessary, to accommodate all {@link #length()} chars. * * @param b the source buffer to be appended. */ public void append(final CharArrayBuffer b) { if (b == null) { return; } append(b.buffer,0, b.len); } /** * Appends <code>ch</code> char to this buffer. The capacity of the buffer * is increased, if necessary, to accommodate the additional char. * * @param ch the char to be appended. */ public void append(char ch) { int newlen = this.len + 1; if (newlen > this.buffer.length) { expand(newlen); } this.buffer[this.len] = ch; this.len = newlen; } /** * Appends <code>len</code> bytes to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> bytes. * <p> * The bytes are converted to chars using simple cast. * * @param b the bytes to be appended. * @param off the index of the first byte to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final byte[] b, int off, int len) { if (b == null) { return; } if ((off < 0) || (off > b.length) || (len < 0) || ((off + len) < 0) || ((off + len) > b.length)) { throw new IndexOutOfBoundsException("off: "+off+" len: "+len+" b.length: "+b.length); } if (len == 0) { return; } int oldlen = this.len; int newlen = oldlen + len; if (newlen > this.buffer.length) { expand(newlen); } for (int i1 = off, i2 = oldlen; i2 < newlen; i1++, i2++) { this.buffer[i2] = (char) (b[i1] & 0xff); } this.len = newlen; } /** * Appends <code>len</code> bytes to this buffer from the given source * array starting at index <code>off</code>. The capacity of the buffer * is increased, if necessary, to accommodate all <code>len</code> bytes. * <p> * The bytes are converted to chars using simple cast. * * @param b the bytes to be appended. * @param off the index of the first byte to append. * @param len the number of bytes to append. * @throws IndexOutOfBoundsException if <code>off</code> is out of * range, <code>len</code> is negative, or * <code>off</code> + <code>len</code> is out of range. */ public void append(final ByteArrayBuffer b, int off, int len) { if (b == null) { return; } append(b.buffer(), off, len); } /** * Appends chars of the textual representation of the given object to this * buffer. The capacity of the buffer is increased, if necessary, to * accommodate all chars. * * @param obj the object. */ public void append(final Object obj) { append(String.valueOf(obj)); } /** * Clears content of the buffer. The underlying char array is not resized. */ public void clear() { this.len = 0; } /** * Converts the content of this buffer to an array of chars. * * @return char array */ public char[] toCharArray() { char[] b = new char[this.len]; if (this.len > 0) { System.arraycopy(this.buffer, 0, b, 0, this.len); } return b; } /** * Returns the <code>char</code> value in this buffer at the specified * index. The index argument must be greater than or equal to * <code>0</code>, and less than the length of this buffer. * * @param i the index of the desired char value. * @return the char value at the specified index. * @throws IndexOutOfBoundsException if <code>index</code> is * negative or greater than or equal to {@link #length()}. */ public char charAt(int i) { return this.buffer[i]; } /** * Returns reference to the underlying char array. * * @return the char array. */ public char[] buffer() { return this.buffer; } /** * Returns the current capacity. The capacity is the amount of storage * available for newly appended chars, beyond which an allocation will * occur. * * @return the current capacity */ public int capacity() { return this.buffer.length; } /** * Returns the length of the buffer (char count). * * @return the length of the buffer */ public int length() { return this.len; } /** * Ensures that the capacity is at least equal to the specified minimum. * If the current capacity is less than the argument, then a new internal * array is allocated with greater capacity. If the <code>required</code> * argument is non-positive, this method takes no action. * * @param required the minimum required capacity. */ public void ensureCapacity(int required) { if (required <= 0) { return; } int available = this.buffer.length - this.len; if (required > available) { expand(this.len + required); } } /** * Sets the length of the buffer. The new length value is expected to be * less than the current capacity and greater than or equal to * <code>0</code>. * * @param len the new length * @throws IndexOutOfBoundsException if the * <code>len</code> argument is greater than the current * capacity of the buffer or less than <code>0</code>. */ public void setLength(int len) { if (len < 0 || len > this.buffer.length) { throw new IndexOutOfBoundsException("len: "+len+" < 0 or > buffer len: "+this.buffer.length); } this.len = len; } /** * Returns <code>true</code> if this buffer is empty, that is, its * {@link #length()} is equal to <code>0</code>. * @return <code>true</code> if this buffer is empty, <code>false</code> * otherwise. */ public boolean isEmpty() { return this.len == 0; } /** * Returns <code>true</code> if this buffer is full, that is, its * {@link #length()} is equal to its {@link #capacity()}. * @return <code>true</code> if this buffer is full, <code>false</code> * otherwise. */ public boolean isFull() { return this.len == this.buffer.length; } /** * Returns the index within this buffer of the first occurrence of the * specified character, starting the search at the specified * <code>beginIndex</code> and finishing at <code>endIndex</code>. * If no such character occurs in this buffer within the specified bounds, * <code>-1</code> is returned. * <p> * There is no restriction on the value of <code>beginIndex</code> and * <code>endIndex</code>. If <code>beginIndex</code> is negative, * it has the same effect as if it were zero. If <code>endIndex</code> is * greater than {@link #length()}, it has the same effect as if it were * {@link #length()}. If the <code>beginIndex</code> is greater than * the <code>endIndex</code>, <code>-1</code> is returned. * * @param ch the char to search for. * @param beginIndex the index to start the search from. * @param endIndex the index to finish the search at. * @return the index of the first occurrence of the character in the buffer * within the given bounds, or <code>-1</code> if the character does * not occur. */ public int indexOf(int ch, int beginIndex, int endIndex) { if (beginIndex < 0) { beginIndex = 0; } if (endIndex > this.len) { endIndex = this.len; } if (beginIndex > endIndex) { return -1; } for (int i = beginIndex; i < endIndex; i++) { if (this.buffer[i] == ch) { return i; } } return -1; } /** * Returns the index within this buffer of the first occurrence of the * specified character, starting the search at <code>0</code> and finishing * at {@link #length()}. If no such character occurs in this buffer within * those bounds, <code>-1</code> is returned. * * @param ch the char to search for. * @return the index of the first occurrence of the character in the * buffer, or <code>-1</code> if the character does not occur. */ public int indexOf(int ch) { return indexOf(ch, 0, this.len); } /** * Returns a substring of this buffer. The substring begins at the specified * <code>beginIndex</code> and extends to the character at index * <code>endIndex - 1</code>. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception StringIndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of this * buffer, or <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public String substring(int beginIndex, int endIndex) { return new String(this.buffer, beginIndex, endIndex - beginIndex); } /** * Returns a substring of this buffer with leading and trailing whitespace * omitted. The substring begins with the first non-whitespace character * from <code>beginIndex</code> and extends to the last * non-whitespace character with the index lesser than * <code>endIndex</code>. * * @param beginIndex the beginning index, inclusive. * @param endIndex the ending index, exclusive. * @return the specified substring. * @exception IndexOutOfBoundsException if the * <code>beginIndex</code> is negative, or * <code>endIndex</code> is larger than the length of this * buffer, or <code>beginIndex</code> is larger than * <code>endIndex</code>. */ public String substringTrimmed(int beginIndex, int endIndex) { if (beginIndex < 0) { throw new IndexOutOfBoundsException("Negative beginIndex: "+beginIndex); } if (endIndex > this.len) { throw new IndexOutOfBoundsException("endIndex: "+endIndex+" > length: "+this.len); } if (beginIndex > endIndex) { throw new IndexOutOfBoundsException("beginIndex: "+beginIndex+" > endIndex: "+endIndex); } while (beginIndex < endIndex && HTTP.isWhitespace(this.buffer[beginIndex])) { beginIndex++; } while (endIndex > beginIndex && HTTP.isWhitespace(this.buffer[endIndex - 1])) { endIndex--; } return new String(this.buffer, beginIndex, endIndex - beginIndex); } public String toString() { return new String(this.buffer, 0, this.len); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.util; import java.io.UnsupportedEncodingException; import org.apache.ogt.http.protocol.HTTP; /** * The home for utility methods that handle various encoding tasks. * * * @since 4.0 */ public final class EncodingUtils { /** * Converts the byte array of HTTP content characters to a string. If * the specified charset is not supported, default system encoding * is used. * * @param data the byte array to be encoded * @param offset the index of the first byte to encode * @param length the number of bytes to encode * @param charset the desired character encoding * @return The result of the conversion. */ public static String getString( final byte[] data, int offset, int length, String charset ) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } if (charset == null || charset.length() == 0) { throw new IllegalArgumentException("charset may not be null or empty"); } try { return new String(data, offset, length, charset); } catch (UnsupportedEncodingException e) { return new String(data, offset, length); } } /** * Converts the byte array of HTTP content characters to a string. If * the specified charset is not supported, default system encoding * is used. * * @param data the byte array to be encoded * @param charset the desired character encoding * @return The result of the conversion. */ public static String getString(final byte[] data, final String charset) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } return getString(data, 0, data.length, charset); } /** * Converts the specified string to a byte array. If the charset is not supported the * default system charset is used. * * @param data the string to be encoded * @param charset the desired character encoding * @return The resulting byte array. */ public static byte[] getBytes(final String data, final String charset) { if (data == null) { throw new IllegalArgumentException("data may not be null"); } if (charset == null || charset.length() == 0) { throw new IllegalArgumentException("charset may not be null or empty"); } try { return data.getBytes(charset); } catch (UnsupportedEncodingException e) { return data.getBytes(); } } /** * Converts the specified string to byte array of ASCII characters. * * @param data the string to be encoded * @return The string as a byte array. */ public static byte[] getAsciiBytes(final String data) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return data.getBytes(HTTP.US_ASCII); } catch (UnsupportedEncodingException e) { throw new Error("HttpClient requires ASCII support"); } } /** * Converts the byte array of ASCII characters to a string. This method is * to be used when decoding content of HTTP elements (such as response * headers) * * @param data the byte array to be encoded * @param offset the index of the first byte to encode * @param length the number of bytes to encode * @return The string representation of the byte array */ public static String getAsciiString(final byte[] data, int offset, int length) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } try { return new String(data, offset, length, HTTP.US_ASCII); } catch (UnsupportedEncodingException e) { throw new Error("HttpClient requires ASCII support"); } } /** * Converts the byte array of ASCII characters to a string. This method is * to be used when decoding content of HTTP elements (such as response * headers) * * @param data the byte array to be encoded * @return The string representation of the byte array */ public static String getAsciiString(final byte[] data) { if (data == null) { throw new IllegalArgumentException("Parameter may not be null"); } return getAsciiString(data, 0, data.length); } /** * This class should not be instantiated. */ private EncodingUtils() { } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.util; import java.io.IOException; import java.io.InputStream; import java.util.Map; import java.util.Properties; import java.util.ArrayList; /** * Provides access to version information for HTTP components. * Static methods are used to extract version information from property * files that are automatically packaged with HTTP component release JARs. * <br/> * All available version information is provided in strings, where * the string format is informal and subject to change without notice. * Version information is provided for debugging output and interpretation * by humans, not for automated processing in applications. * * @since 4.0 */ public class VersionInfo { /** A string constant for unavailable information. */ public final static String UNAVAILABLE = "UNAVAILABLE"; /** The filename of the version information files. */ public final static String VERSION_PROPERTY_FILE = "version.properties"; // the property names public final static String PROPERTY_MODULE = "info.module"; public final static String PROPERTY_RELEASE = "info.release"; public final static String PROPERTY_TIMESTAMP = "info.timestamp"; /** The package that contains the version information. */ private final String infoPackage; /** The module from the version info. */ private final String infoModule; /** The release from the version info. */ private final String infoRelease; /** The timestamp from the version info. */ private final String infoTimestamp; /** The classloader from which the version info was obtained. */ private final String infoClassloader; /** * Instantiates version information. * * @param pckg the package * @param module the module, or <code>null</code> * @param release the release, or <code>null</code> * @param time the build time, or <code>null</code> * @param clsldr the class loader, or <code>null</code> */ protected VersionInfo(String pckg, String module, String release, String time, String clsldr) { if (pckg == null) { throw new IllegalArgumentException ("Package identifier must not be null."); } infoPackage = pckg; infoModule = (module != null) ? module : UNAVAILABLE; infoRelease = (release != null) ? release : UNAVAILABLE; infoTimestamp = (time != null) ? time : UNAVAILABLE; infoClassloader = (clsldr != null) ? clsldr : UNAVAILABLE; } /** * Obtains the package name. * The package name identifies the module or informal unit. * * @return the package name, never <code>null</code> */ public final String getPackage() { return infoPackage; } /** * Obtains the name of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the module name, never <code>null</code> */ public final String getModule() { return infoModule; } /** * Obtains the release of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the release version, never <code>null</code> */ public final String getRelease() { return infoRelease; } /** * Obtains the timestamp of the versioned module or informal unit. * This data is read from the version information for the package. * * @return the timestamp, never <code>null</code> */ public final String getTimestamp() { return infoTimestamp; } /** * Obtains the classloader used to read the version information. * This is just the <code>toString</code> output of the classloader, * since the version information should not keep a reference to * the classloader itself. That could prevent garbage collection. * * @return the classloader description, never <code>null</code> */ public final String getClassloader() { return infoClassloader; } /** * Provides the version information in human-readable format. * * @return a string holding this version information */ public String toString() { StringBuffer sb = new StringBuffer (20 + infoPackage.length() + infoModule.length() + infoRelease.length() + infoTimestamp.length() + infoClassloader.length()); sb.append("VersionInfo(") .append(infoPackage).append(':').append(infoModule); // If version info is missing, a single "UNAVAILABLE" for the module // is sufficient. Everything else just clutters the output. if (!UNAVAILABLE.equals(infoRelease)) sb.append(':').append(infoRelease); if (!UNAVAILABLE.equals(infoTimestamp)) sb.append(':').append(infoTimestamp); sb.append(')'); if (!UNAVAILABLE.equals(infoClassloader)) sb.append('@').append(infoClassloader); return sb.toString(); } /** * Loads version information for a list of packages. * * @param pckgs the packages for which to load version info * @param clsldr the classloader to load from, or * <code>null</code> for the thread context classloader * * @return the version information for all packages found, * never <code>null</code> */ public final static VersionInfo[] loadVersionInfo(String[] pckgs, ClassLoader clsldr) { if (pckgs == null) { throw new IllegalArgumentException ("Package identifier list must not be null."); } ArrayList vil = new ArrayList(pckgs.length); for (int i=0; i<pckgs.length; i++) { VersionInfo vi = loadVersionInfo(pckgs[i], clsldr); if (vi != null) vil.add(vi); } return (VersionInfo[]) vil.toArray(new VersionInfo[vil.size()]); } /** * Loads version information for a package. * * @param pckg the package for which to load version information, * for example "org.apache.ogt.http". * The package name should NOT end with a dot. * @param clsldr the classloader to load from, or * <code>null</code> for the thread context classloader * * @return the version information for the argument package, or * <code>null</code> if not available */ public final static VersionInfo loadVersionInfo(final String pckg, ClassLoader clsldr) { if (pckg == null) { throw new IllegalArgumentException ("Package identifier must not be null."); } if (clsldr == null) clsldr = Thread.currentThread().getContextClassLoader(); Properties vip = null; // version info properties, if available try { // org.apache.ogt.http becomes // org/apache/http/version.properties InputStream is = clsldr.getResourceAsStream (pckg.replace('.', '/') + "/" + VERSION_PROPERTY_FILE); if (is != null) { try { Properties props = new Properties(); props.load(is); vip = props; } finally { is.close(); } } } catch (IOException ex) { // shamelessly munch this exception } VersionInfo result = null; if (vip != null) result = fromMap(pckg, vip, clsldr); return result; } /** * Instantiates version information from properties. * * @param pckg the package for the version information * @param info the map from string keys to string values, * for example {@link java.util.Properties} * @param clsldr the classloader, or <code>null</code> * * @return the version information */ protected final static VersionInfo fromMap(String pckg, Map info, ClassLoader clsldr) { if (pckg == null) { throw new IllegalArgumentException ("Package identifier must not be null."); } String module = null; String release = null; String timestamp = null; if (info != null) { module = (String) info.get(PROPERTY_MODULE); if ((module != null) && (module.length() < 1)) module = null; release = (String) info.get(PROPERTY_RELEASE); if ((release != null) && ((release.length() < 1) || (release.equals("${pom.version}")))) release = null; timestamp = (String) info.get(PROPERTY_TIMESTAMP); if ((timestamp != null) && ((timestamp.length() < 1) || (timestamp.equals("${mvn.timestamp}"))) ) timestamp = null; } // if info String clsldrstr = null; if (clsldr != null) clsldrstr = clsldr.toString(); return new VersionInfo(pckg, module, release, timestamp, clsldrstr); } } // class VersionInfo
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.util; import java.lang.reflect.Method; /** * The home for utility methods that handle various exception-related tasks. * * * @since 4.0 */ public final class ExceptionUtils { /** A reference to Throwable's initCause method, or null if it's not there in this JVM */ static private final Method INIT_CAUSE_METHOD = getInitCauseMethod(); /** * Returns a <code>Method<code> allowing access to * {@link Throwable#initCause(Throwable) initCause} method of {@link Throwable}, * or <code>null</code> if the method * does not exist. * * @return A <code>Method<code> for <code>Throwable.initCause</code>, or * <code>null</code> if unavailable. */ static private Method getInitCauseMethod() { try { Class[] paramsClasses = new Class[] { Throwable.class }; return Throwable.class.getMethod("initCause", paramsClasses); } catch (NoSuchMethodException e) { return null; } } /** * If we're running on JDK 1.4 or later, initialize the cause for the given throwable. * * @param throwable The throwable. * @param cause The cause of the throwable. */ public static void initCause(Throwable throwable, Throwable cause) { if (INIT_CAUSE_METHOD != null) { try { INIT_CAUSE_METHOD.invoke(throwable, new Object[] { cause }); } catch (Exception e) { // Well, with no logging, the only option is to munch the exception } } } private ExceptionUtils() { } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * The point of access to the statistics of an {@link HttpConnection}. * * @since 4.0 */ public interface HttpConnectionMetrics { /** * Returns the number of requests transferred over the connection, * 0 if not available. */ long getRequestCount(); /** * Returns the number of responses transferred over the connection, * 0 if not available. */ long getResponseCount(); /** * Returns the number of bytes transferred over the connection, * 0 if not available. */ long getSentBytesCount(); /** * Returns the number of bytes transferred over the connection, * 0 if not available. */ long getReceivedBytesCount(); /** * Return the value for the specified metric. * *@param metricName the name of the metric to query. * *@return the object representing the metric requested, * <code>null</code> if the metric cannot not found. */ Object getMetric(String metricName); /** * Resets the counts * */ void reset(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import org.apache.ogt.http.protocol.HttpContext; /** * A factory for {@link HttpResponse HttpResponse} objects. * * @since 4.0 */ public interface HttpResponseFactory { /** * Creates a new response from status line elements. * * @param ver the protocol version * @param status the status code * @param context the context from which to determine the locale * for looking up a reason phrase to the status code, or * <code>null</code> to use the default locale * * @return the new response with an initialized status line */ HttpResponse newHttpResponse(ProtocolVersion ver, int status, HttpContext context); /** * Creates a new response from a status line. * * @param statusline the status line * @param context the context from which to determine the locale * for looking up a reason phrase if the status code * is updated, or * <code>null</code> to use the default locale * * @return the new response with the argument status line */ HttpResponse newHttpResponse(StatusLine statusline, HttpContext context); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.io; import java.io.IOException; import org.apache.ogt.http.util.CharArrayBuffer; /** * Session output buffer for blocking connections. This interface is similar to * OutputStream class, but it also provides methods for writing lines of text. * <p> * Implementing classes are also expected to manage intermediate data buffering * for optimal output performance. * * @since 4.0 */ public interface SessionOutputBuffer { /** * Writes <code>len</code> bytes from the specified byte array * starting at offset <code>off</code> to this session buffer. * <p> * If <code>off</code> is negative, or <code>len</code> is negative, or * <code>off+len</code> is greater than the length of the array * <code>b</code>, then an <tt>IndexOutOfBoundsException</tt> is thrown. * * @param b the data. * @param off the start offset in the data. * @param len the number of bytes to write. * @exception IOException if an I/O error occurs. */ void write(byte[] b, int off, int len) throws IOException; /** * Writes <code>b.length</code> bytes from the specified byte array * to this session buffer. * * @param b the data. * @exception IOException if an I/O error occurs. */ void write(byte[] b) throws IOException; /** * Writes the specified byte to this session buffer. * * @param b the <code>byte</code>. * @exception IOException if an I/O error occurs. */ void write(int b) throws IOException; /** * Writes characters from the specified string followed by a line delimiter * to this session buffer. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param s the line. * @exception IOException if an I/O error occurs. */ void writeLine(String s) throws IOException; /** * Writes characters from the specified char array followed by a line * delimiter to this session buffer. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param buffer the buffer containing chars of the line. * @exception IOException if an I/O error occurs. */ void writeLine(CharArrayBuffer buffer) throws IOException; /** * Flushes this session buffer and forces any buffered output bytes * to be written out. The general contract of <code>flush</code> is * that calling it is an indication that, if any bytes previously * written have been buffered by the implementation of the output * stream, such bytes should immediately be written to their * intended destination. * * @exception IOException if an I/O error occurs. */ void flush() throws IOException; /** * Returns {@link HttpTransportMetrics} for this session buffer. * * @return transport metrics. */ HttpTransportMetrics getMetrics(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.io; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; /** * Abstract message parser intended to build HTTP messages from an arbitrary * data source. * * @since 4.0 */ public interface HttpMessageParser { /** * Generates an instance of {@link HttpMessage} from the underlying data * source. * * @return HTTP message * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation */ HttpMessage parse() throws IOException, HttpException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.io; /** * EOF sensor. * * @since 4.0 */ public interface EofSensor { boolean isEof(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.io; import java.io.IOException; import org.apache.ogt.http.HttpException; import org.apache.ogt.http.HttpMessage; /** * Abstract message writer intended to serialize HTTP messages to an arbitrary * data sink. * * @since 4.0 */ public interface HttpMessageWriter { /** * Serializes an instance of {@link HttpMessage} to the underlying data * sink. * * @param message * @throws IOException in case of an I/O error * @throws HttpException in case of HTTP protocol violation */ void write(HttpMessage message) throws IOException, HttpException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.io; /** * The point of access to the statistics of {@link SessionInputBuffer} or * {@link SessionOutputBuffer}. * * @since 4.0 */ public interface HttpTransportMetrics { /** * Returns the number of bytes transferred. */ long getBytesTransferred(); /** * Resets the counts */ void reset(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.io; import java.io.IOException; import org.apache.ogt.http.util.CharArrayBuffer; /** * Session input buffer for blocking connections. This interface is similar to * InputStream class, but it also provides methods for reading lines of text. * <p> * Implementing classes are also expected to manage intermediate data buffering * for optimal input performance. * * @since 4.0 */ public interface SessionInputBuffer { /** * Reads up to <code>len</code> bytes of data from the session buffer into * an array of bytes. An attempt is made to read as many as * <code>len</code> bytes, but a smaller number may be read, possibly * zero. The number of bytes actually read is returned as an integer. * * <p> This method blocks until input data is available, end of file is * detected, or an exception is thrown. * * <p> If <code>off</code> is negative, or <code>len</code> is negative, or * <code>off+len</code> is greater than the length of the array * <code>b</code>, then an <code>IndexOutOfBoundsException</code> is * thrown. * * @param b the buffer into which the data is read. * @param off the start offset in array <code>b</code> * at which the data is written. * @param len the maximum number of bytes to read. * @return the total number of bytes read into the buffer, or * <code>-1</code> if there is no more data because the end of * the stream has been reached. * @exception IOException if an I/O error occurs. */ int read(byte[] b, int off, int len) throws IOException; /** * Reads some number of bytes from the session buffer and stores them into * the buffer array <code>b</code>. The number of bytes actually read is * returned as an integer. This method blocks until input data is * available, end of file is detected, or an exception is thrown. * * @param b the buffer into which the data is read. * @return the total number of bytes read into the buffer, or * <code>-1</code> is there is no more data because the end of * the stream has been reached. * @exception IOException if an I/O error occurs. */ int read(byte[] b) throws IOException; /** * Reads the next byte of data from this session buffer. The value byte is * returned as an <code>int</code> in the range <code>0</code> to * <code>255</code>. If no byte is available because the end of the stream * has been reached, the value <code>-1</code> is returned. This method * blocks until input data is available, the end of the stream is detected, * or an exception is thrown. * * @return the next byte of data, or <code>-1</code> if the end of the * stream is reached. * @exception IOException if an I/O error occurs. */ int read() throws IOException; /** * Reads a complete line of characters up to a line delimiter from this * session buffer into the given line buffer. The number of chars actually * read is returned as an integer. The line delimiter itself is discarded. * If no char is available because the end of the stream has been reached, * the value <code>-1</code> is returned. This method blocks until input * data is available, end of file is detected, or an exception is thrown. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param buffer the line buffer. * @return one line of characters * @exception IOException if an I/O error occurs. */ int readLine(CharArrayBuffer buffer) throws IOException; /** * Reads a complete line of characters up to a line delimiter from this * session buffer. The line delimiter itself is discarded. If no char is * available because the end of the stream has been reached, * <code>null</code> is returned. This method blocks until input data is * available, end of file is detected, or an exception is thrown. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @return HTTP line as a string * @exception IOException if an I/O error occurs. */ String readLine() throws IOException; /** Blocks until some data becomes available in the session buffer or the * given timeout period in milliseconds elapses. If the timeout value is * <code>0</code> this method blocks indefinitely. * * @param timeout in milliseconds. * @return <code>true</code> if some data is available in the session * buffer or <code>false</code> otherwise. * @exception IOException if an I/O error occurs. */ boolean isDataAvailable(int timeout) throws IOException; /** * Returns {@link HttpTransportMetrics} for this session buffer. * * @return transport metrics. */ HttpTransportMetrics getMetrics(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http.io; /** * Basic buffer properties. * * @since 4.1 */ public interface BufferInfo { /** * Return length data stored in the buffer * * @return data length */ int length(); /** * Returns total capacity of the buffer * * @return total capacity */ int capacity(); /** * Returns available space in the buffer. * * @return available space. */ int available(); }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.IOException; import org.apache.ogt.http.protocol.HttpContext; /** * HTTP protocol interceptor is a routine that implements a specific aspect of * the HTTP protocol. Usually protocol interceptors are expected to act upon * one specific header or a group of related headers of the incoming message * or populate the outgoing message with one specific header or a group of * related headers. * <p> * Protocol Interceptors can also manipulate content entities enclosed with messages. * Usually this is accomplished by using the 'Decorator' pattern where a wrapper * entity class is used to decorate the original entity. * <p> * Protocol interceptors must be implemented as thread-safe. Similarly to * servlets, protocol interceptors should not use instance variables unless * access to those variables is synchronized. * * @since 4.0 */ public interface HttpRequestInterceptor { /** * Processes a request. * On the client side, this step is performed before the request is * sent to the server. On the server side, this step is performed * on incoming messages before the message body is evaluated. * * @param request the request to preprocess * @param context the context for the request * * @throws HttpException in case of an HTTP protocol violation * @throws IOException in case of an I/O error */ void process(HttpRequest request, HttpContext context) throws HttpException, IOException; }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; import java.io.Serializable; import org.apache.ogt.http.util.CharArrayBuffer; /** * Represents a protocol version. The "major.minor" numbering * scheme is used to indicate versions of the protocol. * <p> * This class defines a protocol version as a combination of * protocol name, major version number, and minor version number. * Note that {@link #equals} and {@link #hashCode} are defined as * final here, they cannot be overridden in derived classes. * </p> * * @since 4.0 */ public class ProtocolVersion implements Serializable, Cloneable { private static final long serialVersionUID = 8950662842175091068L; /** Name of the protocol. */ protected final String protocol; /** Major version number of the protocol */ protected final int major; /** Minor version number of the protocol */ protected final int minor; /** * Create a protocol version designator. * * @param protocol the name of the protocol, for example "HTTP" * @param major the major version number of the protocol * @param minor the minor version number of the protocol */ public ProtocolVersion(String protocol, int major, int minor) { if (protocol == null) { throw new IllegalArgumentException ("Protocol name must not be null."); } if (major < 0) { throw new IllegalArgumentException ("Protocol major version number must not be negative."); } if (minor < 0) { throw new IllegalArgumentException ("Protocol minor version number may not be negative"); } this.protocol = protocol; this.major = major; this.minor = minor; } /** * Returns the name of the protocol. * * @return the protocol name */ public final String getProtocol() { return protocol; } /** * Returns the major version number of the protocol. * * @return the major version number. */ public final int getMajor() { return major; } /** * Returns the minor version number of the HTTP protocol. * * @return the minor version number. */ public final int getMinor() { return minor; } /** * Obtains a specific version of this protocol. * This can be used by derived classes to instantiate themselves instead * of the base class, and to define constants for commonly used versions. * <br/> * The default implementation in this class returns <code>this</code> * if the version matches, and creates a new {@link ProtocolVersion} * otherwise. * * @param major the major version * @param minor the minor version * * @return a protocol version with the same protocol name * and the argument version */ public ProtocolVersion forVersion(int major, int minor) { if ((major == this.major) && (minor == this.minor)) { return this; } // argument checking is done in the constructor return new ProtocolVersion(this.protocol, major, minor); } /** * Obtains a hash code consistent with {@link #equals}. * * @return the hashcode of this protocol version */ public final int hashCode() { return this.protocol.hashCode() ^ (this.major * 100000) ^ this.minor; } /** * Checks equality of this protocol version with an object. * The object is equal if it is a protocl version with the same * protocol name, major version number, and minor version number. * The specific class of the object is <i>not</i> relevant, * instances of derived classes with identical attributes are * equal to instances of the base class and vice versa. * * @param obj the object to compare with * * @return <code>true</code> if the argument is the same protocol version, * <code>false</code> otherwise */ public final boolean equals(Object obj) { if (this == obj) { return true; } if (!(obj instanceof ProtocolVersion)) { return false; } ProtocolVersion that = (ProtocolVersion) obj; return ((this.protocol.equals(that.protocol)) && (this.major == that.major) && (this.minor == that.minor)); } /** * Checks whether this protocol can be compared to another one. * Only protocol versions with the same protocol name can be * {@link #compareToVersion compared}. * * @param that the protocol version to consider * * @return <code>true</code> if {@link #compareToVersion compareToVersion} * can be called with the argument, <code>false</code> otherwise */ public boolean isComparable(ProtocolVersion that) { return (that != null) && this.protocol.equals(that.protocol); } /** * Compares this protocol version with another one. * Only protocol versions with the same protocol name can be compared. * This method does <i>not</i> define a total ordering, as it would be * required for {@link java.lang.Comparable}. * * @param that the protocl version to compare with * * @return a negative integer, zero, or a positive integer * as this version is less than, equal to, or greater than * the argument version. * * @throws IllegalArgumentException * if the argument has a different protocol name than this object, * or if the argument is <code>null</code> */ public int compareToVersion(ProtocolVersion that) { if (that == null) { throw new IllegalArgumentException ("Protocol version must not be null."); } if (!this.protocol.equals(that.protocol)) { throw new IllegalArgumentException ("Versions for different protocols cannot be compared. " + this + " " + that); } int delta = getMajor() - that.getMajor(); if (delta == 0) { delta = getMinor() - that.getMinor(); } return delta; } /** * Tests if this protocol version is greater or equal to the given one. * * @param version the version against which to check this version * * @return <code>true</code> if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as greater or equal, * <code>false</code> otherwise */ public final boolean greaterEquals(ProtocolVersion version) { return isComparable(version) && (compareToVersion(version) >= 0); } /** * Tests if this protocol version is less or equal to the given one. * * @param version the version against which to check this version * * @return <code>true</code> if this protocol version is * {@link #isComparable comparable} to the argument * and {@link #compareToVersion compares} as less or equal, * <code>false</code> otherwise */ public final boolean lessEquals(ProtocolVersion version) { return isComparable(version) && (compareToVersion(version) <= 0); } /** * Converts this protocol version to a string. * * @return a protocol version string, like "HTTP/1.1" */ public String toString() { CharArrayBuffer buffer = new CharArrayBuffer(16); buffer.append(this.protocol); buffer.append('/'); buffer.append(Integer.toString(this.major)); buffer.append('.'); buffer.append(Integer.toString(this.minor)); return buffer.toString(); } public Object clone() throws CloneNotSupportedException { return super.clone(); } }
Java
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.ogt.http; /** * One element of an HTTP {@link Header header} value consisting of * a name / value pair and a number of optional name / value parameters. * <p> * Some HTTP headers (such as the set-cookie header) have values that * can be decomposed into multiple elements. Such headers must be in the * following form: * </p> * <pre> * header = [ element ] *( "," [ element ] ) * element = name [ "=" [ value ] ] *( ";" [ param ] ) * param = name [ "=" [ value ] ] * * name = token * value = ( token | quoted-string ) * * token = 1*&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
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.WindowConstants; import javax.swing.SwingUtilities; import javax.swing.*; import org.jvnet.substance.*; import org.jvnet.substance.button.StandardButtonShaper; import org.jvnet.substance.theme.*; import org.jvnet.substance.watermark.*; import org.jvnet.substance.theme.transform.*; import org.jvnet.substance.utils.SubstanceConstants; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmMensaje extends javax.swing.JFrame { private JPanel pnlMensaje; private JButton btnAceptar; private JLabel lblMensaje; public frmMensaje() { super(); initGUI(); this.setResizable(false); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlMensaje = new JPanel(); getContentPane().add(pnlMensaje, BorderLayout.CENTER); pnlMensaje.setBackground(new java.awt.Color(255, 255, 255)); pnlMensaje.setLayout(null); { lblMensaje = new JLabel(); pnlMensaje.add(lblMensaje); lblMensaje.setText(" "); lblMensaje.setBounds(12, 13, 669, 53); lblMensaje.setFont(new java.awt.Font("Bitstream Charter", java.awt.Font.BOLD,15)); lblMensaje.setForeground(new java.awt.Color(0,0,0)); } { Icon aceptarMensaje = new ImageIcon(getClass().getResource("src/resources/Imagenes/aceptar20x20.png")); btnAceptar = new JButton("Aceptar", aceptarMensaje); btnAceptar.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnAceptar.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.BOTTOM); pnlMensaje.add(btnAceptar); btnAceptar.setBounds(270, 60, 125, 35); btnAceptar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { frmMensaje.this.setVisible(false); //System.out.println("btnAceptar.actionPerformed, event="+evt); //TODO add your code for btnAceptar.actionPerformed } }); } } pack(); this.setSize(703, 133); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public JLabel getLblMensaje() { return lblMensaje; } public void setLblMensaje(JLabel lblMensaje) { this.lblMensaje = lblMensaje; lblMensaje.setAutoscrolls(true); } }
Java
import java.awt.BorderLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.WindowConstants; import org.jdesktop.application.Application; import javax.swing.SwingUtilities; import org.jvnet.substance.SubstanceLookAndFeel; import org.jvnet.substance.button.StandardButtonShaper; import org.jvnet.substance.utils.SubstanceConstants; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmMensajeError extends javax.swing.JFrame { private JPanel pnlMensajeError; private JLabel lblLogoError; private JButton btnAceptarError; private JLabel lblMensajeError; public frmMensajeError() { super("---- ATENCIÓN ----"); initGUI(); this.setResizable(false); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlMensajeError = new JPanel(); getContentPane().add(pnlMensajeError, BorderLayout.CENTER); pnlMensajeError.setBackground(new java.awt.Color(255, 255, 255)); pnlMensajeError.setLayout(null); { Icon logoError = new ImageIcon(getClass().getResource("src/resources/Imagenes/error50x50.png")); lblLogoError = new JLabel(logoError); pnlMensajeError.add(lblLogoError); lblLogoError.setBounds(31, 24, 77, 49); lblLogoError.setName(" "); } { lblMensajeError = new JLabel(); pnlMensajeError.add(lblMensajeError); lblMensajeError.setBounds(114, 32, 461, 32); lblMensajeError.setFont(new java.awt.Font("Bitstream Charter", java.awt.Font.BOLD,15)); lblMensajeError.setForeground(new java.awt.Color(0,0,0)); lblMensajeError.setName(" "); } { Icon aceptarError = new ImageIcon(getClass().getResource("src/resources/Imagenes/aceptar20x20.png")); btnAceptarError = new JButton("Aceptar", aceptarError); btnAceptarError.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnAceptarError.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.BOTTOM); pnlMensajeError.add(btnAceptarError); btnAceptarError.setBounds(254, 91, 126, 35); btnAceptarError.setName("Aceptar"); btnAceptarError.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { frmMensajeError.this.setVisible(false); //System.out.println("btnAceptarError.actionPerformed, event="+evt); //TODO add your code for btnAceptarError.actionPerformed } }); } } pack(); this.setSize(616, 176); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane()); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public JLabel getLblMensajeError() { return lblMensajeError; } public void setLblMensajeError(JLabel lblMensajeError) { this.lblMensajeError = lblMensajeError; } }
Java
public interface Evaluado { public abstract Alumno evaluarEstudiante(Alumno estudiante); }
Java
public interface Presentado { public abstract void presentarExamen(); }
Java
import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.Font; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.io.IOException; import java.io.PrintWriter; import java.util.Vector; import javax.swing.JPanel; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JFrame; import javax.swing.JScrollPane; import javax.swing.WindowConstants; import javax.swing.event.AncestorEvent; import javax.swing.event.AncestorListener; import javax.swing.table.DefaultTableModel; import javax.swing.table.TableModel; import org.jdesktop.application.Application; import javax.swing.SwingUtilities; import javax.swing.*; import org.jvnet.substance.*; import org.jvnet.substance.button.StandardButtonShaper; import org.jvnet.substance.theme.*; import org.jvnet.substance.watermark.*; import org.jvnet.substance.theme.transform.*; import org.jvnet.substance.utils.SubstanceConstants; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmListado extends javax.swing.JFrame { private JPanel pnlListado; private JTabbedPane tabListado; private JTable tblCedula; private JTable tblNotaFinal; private JTable tblAprobado; private JTable tblListadoEstudiante; private JLabel lblContarMatricula; private JLabel lblMatricula; private JLabel lblMostrarRendimiento; private JLabel lblRendimiento; private JLabel lblNota; private JTable tblReprobado; private JButton btnCalcularPromedio; private JLabel lblPromedioNotas; private JLabel lblProfesorCompleto; private JLabel lblProfesor; private JLabel lblNumeroSeccion; private JLabel lblSeccion; private Seccion seccion = new Seccion(); private String nombreColumnas; private Object alumnosCedula; public frmListado() { super("Listado"); initGUI(); this.setResizable(false); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlListado = new JPanel(); getContentPane().add(pnlListado, BorderLayout.CENTER); pnlListado.setBackground(new java.awt.Color(255, 255, 255)); pnlListado.setLayout(null); pnlListado.setPreferredSize(new java.awt.Dimension(910, 409)); { tabListado = new JTabbedPane(); pnlListado.add(tabListado); tabListado.setBounds(12, 52, 633, 318); { TableModel tblListadoEstudianteModel = new DefaultTableModel( new Object[frmMenuPrincipal.seccion.getVectorPrincipal().size()][3], new String[] { "CÉDULA", "NOMBRE", "APELLIDO" }); tblListadoEstudiante = new JTable(); tabListado.addTab("Alumnos por Cédula", null, tblListadoEstudiante, null); for(int i = 0; i < frmMenuPrincipal.seccion.getVectorPrincipal().size(); i++){ tblListadoEstudianteModel.setValueAt(frmMenuPrincipal.seccion.getVectorPrincipal().elementAt(i).getCI(), i, 0); tblListadoEstudianteModel.setValueAt(frmMenuPrincipal.seccion.getVectorPrincipal().elementAt(i).getNom(), i, 1); tblListadoEstudianteModel.setValueAt(frmMenuPrincipal.seccion.getVectorPrincipal().elementAt(i).getApe(), i, 2); } tblListadoEstudiante.setModel(tblListadoEstudianteModel); tblListadoEstudiante.setShowGrid(true); tblListadoEstudiante.setShowHorizontalLines(true); /*tblListadoEstudiante.setPreferredScrollableViewportSize(new Dimension(200,100)); JScrollPane jscrollpane =new JScrollPane(tblListadoEstudiante); jscrollpane.setPreferredSize(new java.awt.Dimension(163, 142));*/ tblListadoEstudiante.setBounds(694, 331, 155, 74); } { TableModel tblNotaFinalModel = new DefaultTableModel( new Object[frmMenuPrincipal.seccion.getVectorNotaFinal().size()][4], new String[] { "CÉDULA", "NOMBRE", "APELLIDO", "NOTA FINAL" }); tblNotaFinal = new JTable(); tabListado.addTab("Alumnos por NotaFinal", null, tblNotaFinal, null); for(int i = 0; i < frmMenuPrincipal.seccion.getVectorNotaFinal().size(); i++){ tblNotaFinalModel.setValueAt(frmMenuPrincipal.seccion.getVectorNotaFinal().elementAt(i).getCI(), i, 0); tblNotaFinalModel.setValueAt(frmMenuPrincipal.seccion.getVectorNotaFinal().elementAt(i).getNom(), i, 1); tblNotaFinalModel.setValueAt(frmMenuPrincipal.seccion.getVectorNotaFinal().elementAt(i).getApe(), i, 2); tblNotaFinalModel.setValueAt(frmMenuPrincipal.seccion.getVectorNotaFinal().elementAt(i).getNotaFinal(), i, 3); } tblNotaFinal.setModel(tblNotaFinalModel); tblNotaFinal.setShowGrid(true); tblNotaFinal.setShowHorizontalLines(true); tblNotaFinal.setBounds(316, 193, 628, 261); } { TableModel tblAprobadoModel = new DefaultTableModel( new Object[frmMenuPrincipal.seccion.getVectorAprobados().size()][4], new String[] { "CÉDULA", "NOMBRE", "APELLIDO", "NOTA FINAL" }); tblAprobado = new JTable(); tabListado.addTab("Alumnos Aprobado", null, tblAprobado, null); for(int i = 0; i < frmMenuPrincipal.seccion.getVectorAprobados().size(); i++){ tblAprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorAprobados().elementAt(i).getCI(), i, 0); tblAprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorAprobados().elementAt(i).getNom(), i, 1); tblAprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorAprobados().elementAt(i).getApe(), i, 2); tblAprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorAprobados().elementAt(i).getNotaFinal(), i, 3); } tblAprobado.setModel(tblAprobadoModel); tblAprobado.setShowGrid(true); tblAprobado.setShowHorizontalLines(true); tblAprobado.setBounds(51, 193, 628, 291); } { TableModel tblReprobadoModel = new DefaultTableModel( new Object[frmMenuPrincipal.seccion.getVectorReprobados().size()][4], new String[] { "CÉDULA", "NOMBRE", "APELLIDO", "NOTA FINAL" }); tblReprobado = new JTable(); tabListado.addTab("Alumnos Reprobados", null, tblReprobado, null); for(int i = 0; i < frmMenuPrincipal.seccion.getVectorReprobados().size(); i++){ tblReprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorReprobados().elementAt(i).getCI(), i, 0); tblReprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorReprobados().elementAt(i).getNom(), i, 1); tblReprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorReprobados().elementAt(i).getApe(), i, 2); tblReprobadoModel.setValueAt(frmMenuPrincipal.seccion.getVectorReprobados().elementAt(i).getNotaFinal(), i, 3); } tblReprobado.setModel(tblReprobadoModel); tblReprobado.setShowGrid(true); tblReprobado.setShowHorizontalLines(true); tblReprobado.setBounds(12, 124, 627, 291); } } { lblSeccion = new JLabel(); pnlListado.add(lblSeccion); lblSeccion.setText("Sección: "); lblSeccion.setForeground(new java.awt.Color(0, 0, 0)); lblSeccion.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 15)); lblSeccion.setBounds(18, 26, 72, 15); } { lblNumeroSeccion = new JLabel(); pnlListado.add(lblNumeroSeccion); lblNumeroSeccion.setBounds(81, 22, 61, 20); } { lblProfesor = new JLabel(); pnlListado.add(lblProfesor); lblProfesor.setText("Profesor: "); lblProfesor.setForeground(new java.awt.Color(0, 0, 0)); lblProfesor.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 15)); lblProfesor.setBounds(168, 26, 82, 15); } { lblProfesorCompleto = new JLabel(); pnlListado.add(lblProfesorCompleto); lblProfesorCompleto.setText(" "); lblProfesorCompleto.setBounds(252, 22, 387, 20); } { Icon calcularpromedio = new ImageIcon(getClass().getResource("src/resources/Imagenes/calcularpromedio30x30.png")); btnCalcularPromedio = new JButton("Calcular Promedio", calcularpromedio); btnCalcularPromedio.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnCalcularPromedio.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.LEFT); pnlListado.add(btnCalcularPromedio); btnCalcularPromedio.setBounds(657, 177, 217, 47); btnCalcularPromedio.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { frmMenuPrincipal.seccion.calcularPromedio(); frmListado.this.lblNota.setText(""+frmMenuPrincipal.seccion.getPromedio()+" Puntos"); frmListado.this.lblMostrarRendimiento.setText(""+frmMenuPrincipal.seccion.getRendimiento()+" %"); frmMensaje frmEvaluacionAplicada = new frmMensaje(); frmEvaluacionAplicada.getLblMensaje().setHorizontalAlignment(javax.swing.SwingConstants.CENTER); frmEvaluacionAplicada.getLblMensaje().setFont(new Font("Courier 10 Pitch", java.awt.Font.BOLD, 18)); frmEvaluacionAplicada.getLblMensaje().setText("Operación Exitosa"); frmEvaluacionAplicada.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmEvaluacionAplicada.setLocationRelativeTo(null); frmEvaluacionAplicada.setVisible(true); //System.out.println("btnCalcularPromedio.actionPerformed, event="+evt); //TODO add your code for btnCalcularPromedio.actionPerformed } }); } { lblPromedioNotas = new JLabel(); pnlListado.add(lblPromedioNotas); lblPromedioNotas.setText("Promedio de Notas: "); lblPromedioNotas.setForeground(new java.awt.Color(0, 0, 0)); lblPromedioNotas.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 15)); lblPromedioNotas.setBounds(24, 401, 174, 31); } { lblNota = new JLabel(); pnlListado.add(lblNota); lblNota.setBounds(176, 405, 85, 23); } { lblRendimiento = new JLabel(); pnlListado.add(lblRendimiento); lblRendimiento.setText("Rendimiento: "); lblRendimiento.setForeground(new java.awt.Color(0, 0, 0)); lblRendimiento.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 15)); lblRendimiento.setBounds(363, 407, 171, 25); } { lblMostrarRendimiento = new JLabel(); pnlListado.add(lblMostrarRendimiento); lblMostrarRendimiento.setBounds(515, 407, 99, 20); } { lblMatricula = new JLabel(); pnlListado.add(lblMatricula); lblMatricula.setText("Matricula: "); lblMatricula.setForeground(new java.awt.Color(0, 0, 0)); lblMatricula.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 15)); lblMatricula.setBounds(645, 26, 91, 15); } { lblContarMatricula = new JLabel(); pnlListado.add(lblContarMatricula); lblContarMatricula.setBounds(737, 23, 112, 17); } } pack(); this.setSize(896, 489); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane()); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public JLabel getLblProfesorCompleto() { return lblProfesorCompleto; } public void setLblProfesorCompleto(JLabel lblProfesorCompleto) { this.lblProfesorCompleto = lblProfesorCompleto; } public JLabel getLblNumeroSeccion() { return lblNumeroSeccion; } public void setLblNumeroSeccion(JLabel lblNumeroSeccion) { this.lblNumeroSeccion = lblNumeroSeccion; } public Seccion getSeccion() { return seccion; } public void setSeccion(Seccion seccion) { this.seccion = seccion; } public JTable getTblCedula() { return tblCedula; } public void setTblCedula(JTable tblCedula) { this.tblCedula = tblCedula; } public void setTblCedula(DefaultTableModel tableOrdenCedula) { // TODO Auto-generated method stub } public JLabel getLblContarMatricula() { return lblContarMatricula; } public void setLblContarMatricula(JLabel lblContarMatricula) { this.lblContarMatricula = lblContarMatricula; } }
Java
import java.awt.BorderLayout; import java.awt.Button; import java.awt.Font; import java.awt.GraphicsConfiguration; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import java.awt.Image; import javax.swing.BorderFactory; import java.awt.Graphics; import javax.swing.WindowConstants; import javax.swing.border.LineBorder; import org.jdesktop.application.Application; import javax.swing.*; import org.jvnet.substance.*; import org.jvnet.substance.button.StandardButtonShaper; import org.jvnet.substance.theme.*; import org.jvnet.substance.watermark.*; import org.jvnet.substance.theme.transform.*; import org.jvnet.substance.utils.SubstanceConstants; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ @SuppressWarnings("serial") public class frmMenuPrincipal extends javax.swing.JFrame { private JPanel pnlMenuPrincipal; private JButton btnOperacionesEstudiantes; private JLabel lblNombreProfesor; private JButton btnLimpiarSeccion; private JButton btnAceptarSeccion; private JTextField txtTituloProfesor; private JTextField txtApellidoProfesor; private JTextField txtNombreProfesor; private JTextField txtCedulaProfesor; private JLabel lblTituloProfesor; private JLabel lblApellidoProfesor; private JLabel lblCedulaProfesor; private JLabel lblDatosProfesor; private JLabel lblNumeroSeccion; private JTextField txtNumeroSeccion; private JPanel pnlConfigurarSeccion; private JLabel lblImagenPrincipal; public static Profesor profe = new Profesor(); public static Seccion seccion = new Seccion(); /** * Auto-generated main method to display this JFrame */ public static void main(String[] args) { //Le decimos al SO que java se encargara del manejo de la decoracion //del contorno de la ventana JFrame.setDefaultLookAndFeelDecorated(true); //Aplicamos un skin a nuestra ventana SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); //marca de agua, un prediseño de substance SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); SwingUtilities.invokeLater(new Runnable() { public void run() { frmMenuPrincipal inst = new frmMenuPrincipal(); inst.setLocationRelativeTo(null); inst.setVisible(true); } }); } public frmMenuPrincipal() { super("::::::BIENVENIDOS A LA APLICACIÓN::::::"); initGUI(); this.setResizable(false); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); //frmMenuPrincipal.this.setIconImage(Toolkit.getDefaultToolkit().getImage("/home/leo/workspace/proyecto1/primeraentrega/src/src/resources/Imagenes/javacoffe30x30.png")); getContentPane().setLayout(new BorderLayout()); { pnlMenuPrincipal = new JPanel(); getContentPane().add(pnlMenuPrincipal, BorderLayout.CENTER); pnlMenuPrincipal.setBackground(new java.awt.Color(255, 255, 255)); pnlMenuPrincipal.setLayout(null); pnlMenuPrincipal.setPreferredSize(new java.awt.Dimension(843, 429)); { Icon operacionesAlumno = new ImageIcon(getClass().getResource("src/resources/Imagenes/operacionesAlumno70x70.png")); btnOperacionesEstudiantes = new JButton("Operaciones con Alumno", operacionesAlumno); btnOperacionesEstudiantes.setBorderPainted(true); btnOperacionesEstudiantes.putClientProperty( SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnOperacionesEstudiantes.putClientProperty( SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.LEFT); pnlMenuPrincipal.add(btnOperacionesEstudiantes); btnOperacionesEstudiantes.setVisible(false); btnOperacionesEstudiantes.setBounds(469, 318, 342, 60); btnOperacionesEstudiantes.setName("btnOperacionesEstudiantes"); btnOperacionesEstudiantes.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { frmOperacionesEstudiante frmestudiantes = new frmOperacionesEstudiante(); frmMenuPrincipal.this.setVisible(false); frmestudiantes.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmestudiantes.setLocationRelativeTo(null); frmestudiantes.setVisible(true); //System.out.println("btnOperacionesEstudiantes.actionPerformed, event="+evt); //TODO add your code for btnOperacionesEstudiantes.actionPerformed } }); } } { Icon imagenPrincipal = new ImageIcon(getClass().getResource("src/resources/Imagenes/TuxalumnoGrande.png")); lblImagenPrincipal = new JLabel(imagenPrincipal); pnlMenuPrincipal.add(lblImagenPrincipal); lblImagenPrincipal.setVisible(true); lblImagenPrincipal.setBounds(7, 13, 256, 323); } { pnlConfigurarSeccion = new JPanel(); pnlMenuPrincipal.add(pnlConfigurarSeccion); pnlConfigurarSeccion.setBorder(BorderFactory.createTitledBorder("Configurar Seccion")); pnlConfigurarSeccion.setLayout(null); pnlConfigurarSeccion.setBackground(new java.awt.Color(255, 255, 255)); pnlConfigurarSeccion.setBounds(263, 13, 548, 293); { txtNumeroSeccion = new JTextField(); pnlConfigurarSeccion.add(txtNumeroSeccion); txtNumeroSeccion.setBounds(113, 35, 71, 31); txtNumeroSeccion.setName("txtNumeroSeccion"); } { lblNumeroSeccion = new JLabel("Numero: "); pnlConfigurarSeccion.add(lblNumeroSeccion); lblNumeroSeccion.setForeground(new java.awt.Color(0, 0, 0)); lblNumeroSeccion.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 20)); lblNumeroSeccion.setBounds(17, 32, 101, 36); lblNumeroSeccion.setName("lblNumero"); } { lblDatosProfesor = new JLabel(); pnlConfigurarSeccion.add(lblDatosProfesor); lblDatosProfesor.setForeground(new java.awt.Color(0, 0, 0)); lblDatosProfesor.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 20)); lblDatosProfesor.setBounds(118, 76, 209, 33); lblDatosProfesor.setName("lblDatosProfesor"); } { lblNombreProfesor = new JLabel(); pnlConfigurarSeccion.add(lblNombreProfesor); lblNombreProfesor.setForeground(new java.awt.Color(0, 0, 0)); lblNombreProfesor.setFont(new Font("Bitstream Charter", java.awt.Font.ITALIC, 18)); lblNombreProfesor.setBounds(15, 162, 100, 22); lblNombreProfesor.setName("lblNombreProfesor"); } { lblCedulaProfesor = new JLabel(); pnlConfigurarSeccion.add(lblCedulaProfesor); lblCedulaProfesor.setForeground(new java.awt.Color(0, 0, 0)); lblCedulaProfesor.setFont(new Font("Bitstream Charter", java.awt.Font.ITALIC, 18)); lblCedulaProfesor.setBounds(13, 121, 100, 28); lblCedulaProfesor.setName("lblCedulaProfesor"); } { lblApellidoProfesor = new JLabel(); pnlConfigurarSeccion.add(lblApellidoProfesor); lblApellidoProfesor.setForeground(new java.awt.Color(0, 0, 0)); lblApellidoProfesor.setFont(new Font("Bitstream Charter", java.awt.Font.ITALIC, 18)); lblApellidoProfesor.setBounds(17, 204, 98, 20); lblApellidoProfesor.setName("lblApellidoProfesor"); } { lblTituloProfesor = new JLabel(); pnlConfigurarSeccion.add(lblTituloProfesor); lblTituloProfesor.setForeground(new java.awt.Color(0, 0, 0)); lblTituloProfesor.setFont(new Font("Bitstream Charter", java.awt.Font.ITALIC, 18)); lblTituloProfesor.setBounds(17, 240, 100, 24); lblTituloProfesor.setName("lblTituliProfesor"); } { txtCedulaProfesor = new JTextField(); pnlConfigurarSeccion.add(txtCedulaProfesor); txtCedulaProfesor.setBounds(113, 121, 168, 29); txtCedulaProfesor.setName("txtCedulaProfesor"); } { txtNombreProfesor = new JTextField(); pnlConfigurarSeccion.add(txtNombreProfesor); txtNombreProfesor.setBounds(115, 161, 226, 32); txtNombreProfesor.setName("txtNombreProfesor"); } { txtApellidoProfesor = new JTextField(); pnlConfigurarSeccion.add(txtApellidoProfesor); txtApellidoProfesor.setBounds(115, 199, 226, 32); txtApellidoProfesor.setName("txtApellidoProfesor"); } { txtTituloProfesor = new JTextField(); pnlConfigurarSeccion.add(txtTituloProfesor); txtTituloProfesor.setBounds(117, 237, 224, 32); txtTituloProfesor.setName("txtTituloProfesor"); } { Icon aceptar = new ImageIcon(getClass().getResource("src/resources/Imagenes/aceptar20x20.png")); btnAceptarSeccion = new JButton("Aceptar", aceptar); pnlConfigurarSeccion.add(btnAceptarSeccion); btnAceptarSeccion.setBorderPainted(true); btnAceptarSeccion.putClientProperty( SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnAceptarSeccion.putClientProperty( SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.BOTTOM); btnAceptarSeccion.setBounds(388, 144, 121, 40); btnAceptarSeccion.setName("btnAceptarSeccion"); btnAceptarSeccion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if((txtNumeroSeccion.getText() != "") || (txtCedulaProfesor.getText() != "") || (txtNombreProfesor.getText() != "") || (txtApellidoProfesor.getText() != "") || (txtTituloProfesor.getText() != "")){ if((seccion.validarEntradaSeccion(txtNumeroSeccion.getText())) && (seccion.validarEntradaLetras(txtNombreProfesor.getText())) && (seccion.validarEntradaLetras(txtApellidoProfesor.getText())) && (seccion.validarEntradaLetras(txtTituloProfesor.getText()) && (seccion.validarNumeros(txtCedulaProfesor.getText())))){ frmMenuPrincipal.this.seccion.setNumero(frmMenuPrincipal.this.txtNumeroSeccion.getText()); frmMenuPrincipal.this.profe.setCI(frmMenuPrincipal.this.txtCedulaProfesor.getText()); frmMenuPrincipal.this.profe.setNom(frmMenuPrincipal.this.txtNombreProfesor.getText()); frmMenuPrincipal.this.profe.setApe(frmMenuPrincipal.this.txtApellidoProfesor.getText()); frmMenuPrincipal.this.profe.setTitulo(frmMenuPrincipal.this.txtTituloProfesor.getText()); frmMenuPrincipal.this.pnlConfigurarSeccion.setVisible(false); frmMensaje frmSeccionLista = new frmMensaje(); frmSeccionLista.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmSeccionLista.setLocationRelativeTo(null); frmSeccionLista.setVisible(true); frmSeccionLista.getLblMensaje().setHorizontalAlignment(javax.swing.SwingConstants.CENTER); frmSeccionLista.getLblMensaje().setFont(new Font("Courier 10 Pitch", java.awt.Font.BOLD, 20)); frmSeccionLista.getLblMensaje().setText("Sección configurada exitosamente"); frmMenuPrincipal.this.btnOperacionesEstudiantes.setVisible(true); } else{ frmMensajeError frmError = new frmMensajeError(); frmError.getLblMensajeError().setText("Existen datos no permitidos. Por favor verifique"); frmError.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmError.setLocationRelativeTo(null); frmError.setVisible(true); } } else{ frmMensajeError frmError = new frmMensajeError(); frmError.getLblMensajeError().setText("Existen campos sin datos"); frmError.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmError.setLocationRelativeTo(null); frmError.setVisible(true); } //System.out.println("btnAceptarSeccion.actionPerformed, event="+evt); //TODO add your code for btnAceptarSeccion.actionPerformed } }); } { Icon limpiarSeccion = new ImageIcon(getClass().getResource("src/resources/Imagenes/limpiar30x30.png")); btnLimpiarSeccion = new JButton("Limpiar", limpiarSeccion); btnLimpiarSeccion.setBorderPainted(true); pnlConfigurarSeccion.add(btnLimpiarSeccion); btnLimpiarSeccion.putClientProperty( SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnLimpiarSeccion.putClientProperty( SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.BOTTOM); btnLimpiarSeccion.setBounds(388, 224, 121, 40); btnLimpiarSeccion.setName("btnLimpiarSeccion"); btnLimpiarSeccion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { txtNumeroSeccion.setText(""); txtNombreProfesor.setText(""); txtApellidoProfesor.setText(""); txtTituloProfesor.setText(""); //System.out.println("btnLimpiarSeccion.actionPerformed, event="+evt); //TODO add your code for btnLimpiarSeccion.actionPerformed } }); } } pack(); this.setSize(833, 419); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane()); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } }
Java
import java.awt.BorderLayout; import java.awt.Font; import java.awt.Label; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.util.Vector; import javax.swing.BorderFactory; import javax.swing.Icon; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTextField; import javax.swing.WindowConstants; import org.jdesktop.application.Application; import javax.swing.SwingUtilities; import javax.swing.*; import javax.swing.table.DefaultTableModel; import org.jvnet.substance.*; import org.jvnet.substance.button.StandardButtonShaper; import org.jvnet.substance.theme.*; import org.jvnet.substance.watermark.*; import org.jvnet.substance.theme.transform.*; import org.jvnet.substance.utils.SubstanceConstants; /** * This code was edited or generated using CloudGarden's Jigloo * SWT/Swing GUI Builder, which is free for non-commercial * use. If Jigloo is being used commercially (ie, by a corporation, * company or business for any purpose whatever) then you * should purchase a license for each developer using Jigloo. * Please visit www.cloudgarden.com for details. * Use of Jigloo implies acceptance of these licensing terms. * A COMMERCIAL LICENSE HAS NOT BEEN PURCHASED FOR * THIS MACHINE, SO JIGLOO OR THIS CODE CANNOT BE USED * LEGALLY FOR ANY CORPORATE OR COMMERCIAL PURPOSE. */ public class frmOperacionesEstudiante extends javax.swing.JFrame { private JPanel pnlOperacionesEstudiante; private JPanel pnlInscribirEstudiantes; private JButton btnInscribir; private JButton btnMostrarListado; private JButton btnCancelarEstudiante; private JButton btnAceptarEstudiante; private JButton btnAplicarEvaluacion; private JButton btnRetirar; private JButton btnBuscarAlumno; private JLabel lblBusquedaApellido; private JLabel lblBusquedaNombre; private JLabel lblBusquedaCedula; private JLabel lblApellidoEstudiante; private JLabel lblNombreEstudiante; private JLabel lblCedulaEstudiante; private JList lstMostrarInscritos; private JPanel pnlResultadoBusqueda; private JTextField txtEscribirCedula; private JTextField txtCedula; private JTextField txtEscribirApellido; private JTextField txtEscribirNombre; public frmOperacionesEstudiante() { super("Operaciones con Alumno"); initGUI(); this.setResizable(false); } private void initGUI() { try { setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE); { pnlOperacionesEstudiante = new JPanel(); getContentPane().add(pnlOperacionesEstudiante, BorderLayout.CENTER); pnlOperacionesEstudiante.setBackground(new java.awt.Color(255, 255, 255)); pnlOperacionesEstudiante.setLayout(null); pnlOperacionesEstudiante.setPreferredSize(new java.awt.Dimension(1000, 431)); { txtCedula = new JTextField(); pnlOperacionesEstudiante.add(txtCedula); txtCedula.setText(""); txtCedula.setBounds(41, 24, 227, 34); txtCedula.setToolTipText("Ingrese la cedula a buscar"); } { Icon buscarOperacion = new ImageIcon(getClass().getResource("src/resources/Imagenes/buscar20x20.png")); btnBuscarAlumno = new JButton("Buscar", buscarOperacion); btnBuscarAlumno.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); pnlOperacionesEstudiante.add(btnBuscarAlumno); btnBuscarAlumno.setBounds(280, 24, 109, 34); btnBuscarAlumno.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { frmMenuPrincipal.seccion.setEncontrado(true); frmMenuPrincipal.seccion.busquedaCi(txtCedula.getText()); int posicion = frmMenuPrincipal.seccion.getPosicion(); if(frmMenuPrincipal.seccion.isEncontrado() != true){ frmMensaje frmEstudianteNoEncontrado = new frmMensaje(); frmEstudianteNoEncontrado.getLblMensaje().setHorizontalAlignment(javax.swing.SwingConstants.CENTER); frmEstudianteNoEncontrado.getLblMensaje().setFont(new Font("Courier 10 Pitch", java.awt.Font.BOLD, 24)); frmEstudianteNoEncontrado.getLblMensaje().setText("El Estudiante No esta Inscrito"); frmEstudianteNoEncontrado.setVisible(true); } else{ lblBusquedaCedula.setText("Cédula: "+frmMenuPrincipal.seccion.getVectorPrincipal().elementAt(posicion).getCI()); lblBusquedaNombre.setText("Nombre: "+frmMenuPrincipal.seccion.getVectorPrincipal().elementAt(posicion).getNom()); lblBusquedaApellido.setText("Apellido: "+frmMenuPrincipal.seccion.getVectorPrincipal().elementAt(posicion).getApe()); } //System.out.println("btnBuscarAlumno.actionPerformed, event="+evt); //TODO add your code for btnBuscarAlumno.actionPerformed } }); } { Icon inscribirOperacion = new ImageIcon(getClass().getResource("src/resources/Imagenes/inscribir30x30.png")); btnInscribir = new JButton("Inscribir", inscribirOperacion); btnInscribir.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnInscribir.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.LEFT); pnlOperacionesEstudiante.add(btnInscribir); btnInscribir.setBounds(407, 81, 205, 38); btnInscribir.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { pnlInscribirEstudiantes.setVisible(true); txtEscribirCedula.setText(frmOperacionesEstudiante.this.txtCedula.getText()); txtCedula.setText(""); //System.out.println("btnInscribir.actionPerformed, event="+evt); //TODO add your code for btnInscribir.actionPerformed } }); } { Icon retirarOperacion = new ImageIcon(getClass().getResource("src/resources/Imagenes/retirar30x30.png")); btnRetirar = new JButton("Retirar",retirarOperacion); btnRetirar.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnRetirar.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.LEFT); pnlOperacionesEstudiante.add(btnRetirar); btnRetirar.setBounds(407, 130, 205, 38); btnRetirar.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if(frmMenuPrincipal.seccion.validarInscritos()){ frmMenuPrincipal.seccion.retirarEstudiante(frmOperacionesEstudiante.this.txtCedula.getText()); frmMensaje frmEstudianteRetirado = new frmMensaje(); frmEstudianteRetirado.getLblMensaje().setHorizontalAlignment(javax.swing.SwingConstants.CENTER); frmEstudianteRetirado.getLblMensaje().setFont(new Font("Courier 10 Pitch", java.awt.Font.BOLD, 24)); frmEstudianteRetirado.getLblMensaje().setText("El Estudiante fue Retirado"); frmEstudianteRetirado.setVisible(true); } else{ frmMensajeError frmError = new frmMensajeError(); frmError.getLblMensajeError().setText("Debe Inscribir al menos un(1) Estudiante"); frmError.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmError.setLocationRelativeTo(null); frmError.setVisible(true); } //System.out.println("btnRetirar.actionPerformed, event="+evt); //TODO add your code for btnRetirar.actionPerformed } }); } { pnlInscribirEstudiantes = new JPanel(); //pnlInscribirEstudiantes.setEnabled(false); pnlOperacionesEstudiante.add(pnlInscribirEstudiantes); pnlInscribirEstudiantes.setBorder(BorderFactory.createTitledBorder("Inscribir Estudiante")); pnlInscribirEstudiantes.setLayout(null); pnlInscribirEstudiantes.setBackground(new java.awt.Color(255, 255, 255)); pnlInscribirEstudiantes.setBounds(623, 24, 378, 287); { lblCedulaEstudiante = new JLabel(); pnlInscribirEstudiantes.add(lblCedulaEstudiante); lblCedulaEstudiante.setForeground(new java.awt.Color(0, 0, 0)); lblCedulaEstudiante.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 20)); lblCedulaEstudiante.setBounds(11, 53, 83, 26); lblCedulaEstudiante.setName("lblCedulaEstudiante"); } { lblNombreEstudiante = new JLabel(); pnlInscribirEstudiantes.add(lblNombreEstudiante); lblNombreEstudiante.setForeground(new java.awt.Color(0, 0, 0)); lblNombreEstudiante.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 20)); lblNombreEstudiante.setBounds(11, 99, 88, 24); lblNombreEstudiante.setName("lblNombreEstudiante"); } { lblApellidoEstudiante = new JLabel(); pnlInscribirEstudiantes.add(lblApellidoEstudiante); lblApellidoEstudiante.setForeground(new java.awt.Color(0, 0, 0)); lblApellidoEstudiante.setFont(new Font("Bitstream Charter", java.awt.Font.BOLD, 20)); lblApellidoEstudiante.setBounds(11, 148, 101, 27); lblApellidoEstudiante.setName("lblApellidoEstudiante"); } { txtEscribirCedula = new JTextField(); pnlInscribirEstudiantes.add(txtEscribirCedula); txtEscribirCedula.setBounds(117, 53, 136, 29); txtEscribirCedula.setName("txtEscribirCedula"); } { txtEscribirNombre = new JTextField(); pnlInscribirEstudiantes.add(txtEscribirNombre); txtEscribirNombre.setBounds(117, 97, 203, 31); txtEscribirNombre.setName("txtEscribirNombre"); } { txtEscribirApellido = new JTextField(); pnlInscribirEstudiantes.add(txtEscribirApellido); txtEscribirApellido.setBounds(118, 147, 203, 30); txtEscribirApellido.setName("txtEscribirApellido"); } { Icon aceptarEstudiante = new ImageIcon(getClass().getResource("src/resources/Imagenes/aceptar20x20.png")); btnAceptarEstudiante = new JButton("Aceptar", aceptarEstudiante); pnlInscribirEstudiantes.add(btnAceptarEstudiante); btnAceptarEstudiante.putClientProperty( SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnAceptarEstudiante.putClientProperty( SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.BOTTOM); btnAceptarEstudiante.setBounds(52, 231, 139, 35); btnAceptarEstudiante.setName("btnAceptarEstudiante"); btnAceptarEstudiante.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if((txtEscribirCedula.getText() != "") || (txtEscribirNombre.getText() != "") || (txtEscribirApellido.getText() != "")){ if((frmMenuPrincipal.seccion.validarEntradaLetras(txtEscribirNombre.getText())) && (frmMenuPrincipal.seccion.validarEntradaLetras(txtEscribirApellido.getText())) && (frmMenuPrincipal.seccion.validarNumeros(txtEscribirCedula.getText()))){ Alumno estudiante = new Alumno(frmOperacionesEstudiante.this.txtEscribirCedula.getText(), frmOperacionesEstudiante.this.txtEscribirNombre.getText(), frmOperacionesEstudiante.this.txtEscribirApellido.getText()); frmMenuPrincipal.seccion.inscribirEstudiante(estudiante); txtEscribirCedula.setText(""); txtEscribirNombre.setText(""); txtEscribirApellido.setText(""); frmMensaje frmEstudianteInscrito = new frmMensaje(); frmEstudianteInscrito.getLblMensaje().setHorizontalAlignment(javax.swing.SwingConstants.CENTER); frmEstudianteInscrito.getLblMensaje().setFont(new Font("Courier 10 Pitch", java.awt.Font.BOLD, 24)); frmEstudianteInscrito.getLblMensaje().setText("El Estudiante fue Inscrito Exitosamente"); frmEstudianteInscrito.setVisible(true); frmEstudianteInscrito.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmEstudianteInscrito.setLocationRelativeTo(null); } else{ frmMensajeError frmError = new frmMensajeError(); frmError.getLblMensajeError().setText("Existen datos no permitidos. Por favor verifique"); frmError.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmError.setLocationRelativeTo(null); frmError.setVisible(true); } } else{ frmMensajeError frmError = new frmMensajeError(); frmError.getLblMensajeError().setText("Existen campos sin datos"); frmError.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmError.setLocationRelativeTo(null); frmError.setVisible(true); } //System.out.println("btnAceptarEstudiante.actionPerformed, event="+evt); //TODO add your code for btnAceptarEstudiante.actionPerformed } }); } { Icon cancelarEstudiante = new ImageIcon(getClass().getResource("src/resources/Imagenes/cancelar30x30.png")); btnCancelarEstudiante = new JButton("Cancelar", cancelarEstudiante); pnlInscribirEstudiantes.add(btnCancelarEstudiante); btnCancelarEstudiante.putClientProperty( SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnCancelarEstudiante.putClientProperty( SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.BOTTOM); btnCancelarEstudiante.setBounds(222, 231, 133, 35); btnCancelarEstudiante.setName("btnLimpiarEstudiante"); btnCancelarEstudiante.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { txtEscribirCedula.setText(""); txtEscribirNombre.setText(""); txtEscribirApellido.setText(""); //frmOperacionesEstudiante.this.pnlInscribirEstudiantes.setEnabled(false); //System.out.println("btnLimpiarEstudiante.actionPerformed, event="+evt); //TODO add your code for btnLimpiarEstudiante.actionPerformed } }); } } { Icon MostrarListado = new ImageIcon(getClass().getResource("src/resources/Imagenes/listados30x30.png")); btnMostrarListado = new JButton("Listados", MostrarListado); pnlOperacionesEstudiante.add(btnMostrarListado); btnMostrarListado.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnMostrarListado.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.LEFT); btnMostrarListado.setBounds(407, 236, 205, 38); btnMostrarListado.setVisible(false); btnMostrarListado.setName("btnMostrarListado"); btnMostrarListado.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { frmMenuPrincipal.seccion.ordenadosCedula(frmMenuPrincipal.seccion, frmMenuPrincipal.profe); frmListado frmMostrarListados = new frmListado(); frmMostrarListados.getLblNumeroSeccion().setText(frmMenuPrincipal.seccion.getNumero()); frmMostrarListados.getLblProfesorCompleto().setText(frmMenuPrincipal.profe.getTitulo()+" "+frmMenuPrincipal.profe.getNom()+" "+frmMenuPrincipal.profe.getApe()); frmMostrarListados.getLblContarMatricula().setText(""+frmMenuPrincipal.seccion.getVectorPrincipal().size()+" Alumnos"); frmMostrarListados.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmMostrarListados.setLocationRelativeTo(null); frmMostrarListados.setVisible(true); //System.out.println("btnMostrarListado.actionPerformed, event="+evt); //TODO add your code for btnMostrarListado.actionPerformed } }); } { pnlResultadoBusqueda = new JPanel(); pnlOperacionesEstudiante.add(pnlResultadoBusqueda); pnlResultadoBusqueda.setBorder(BorderFactory.createTitledBorder("Resultado de la Busqueda")); pnlOperacionesEstudiante.setBackground(new java.awt.Color(255, 255, 255)); pnlResultadoBusqueda.setLayout(null); pnlResultadoBusqueda.setBounds(24, 69, 371, 208); { lblBusquedaCedula = new JLabel(); pnlResultadoBusqueda.add(lblBusquedaCedula); lblBusquedaCedula.setBounds(17, 46, 337, 26); } { lblBusquedaNombre = new JLabel(); pnlResultadoBusqueda.add(lblBusquedaNombre); lblBusquedaNombre.setBounds(17, 97, 337, 27); lblBusquedaNombre.setName("lblBusquedaNombre"); } { lblBusquedaApellido = new JLabel(); pnlResultadoBusqueda.add(lblBusquedaApellido); lblBusquedaApellido.setBounds(17, 151, 337, 28); } } { Icon aplicarevaluacion = new ImageIcon(getClass().getResource("src/resources/Imagenes/aplicarevaluacion30x30.png")); btnAplicarEvaluacion = new JButton("Aplicar Evaluaciones", aplicarevaluacion); btnAplicarEvaluacion.putClientProperty(SubstanceLookAndFeel.BUTTON_SHAPER_PROPERTY, new StandardButtonShaper()); btnAplicarEvaluacion.putClientProperty(SubstanceLookAndFeel.BUTTON_SIDE_PROPERTY, SubstanceConstants.Side.LEFT); pnlOperacionesEstudiante.add(btnAplicarEvaluacion); btnAplicarEvaluacion.setBounds(407, 185, 205, 38); btnAplicarEvaluacion.setName("btnAplicarEvaluacion"); btnAplicarEvaluacion.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { if(frmMenuPrincipal.seccion.validarInscritos()){ frmMenuPrincipal.seccion.AplicarEvaluacion(); frmMenuPrincipal.seccion.ordenadosNotaFinal(frmMenuPrincipal.seccion, frmMenuPrincipal.profe); frmMenuPrincipal.seccion.listadoAprobado(frmMenuPrincipal.seccion, frmMenuPrincipal.profe); frmMenuPrincipal.seccion.listadoReprobado(frmMenuPrincipal.seccion, frmMenuPrincipal.profe); frmMensaje frmEvaluacionAplicada = new frmMensaje(); frmEvaluacionAplicada.getLblMensaje().setHorizontalAlignment(javax.swing.SwingConstants.CENTER); frmEvaluacionAplicada.getLblMensaje().setFont(new Font("Courier 10 Pitch", java.awt.Font.BOLD, 18)); frmEvaluacionAplicada.getLblMensaje().setText("Las Evaluaciones fueron Aplicadas con Exito"); frmEvaluacionAplicada.setVisible(true); btnMostrarListado.setVisible(true); } else{ frmMensajeError frmError = new frmMensajeError(); frmError.getLblMensajeError().setText("Debe Inscribir al menos un(1) Estudiante"); frmError.setDefaultLookAndFeelDecorated(true); SubstanceLookAndFeel.setSkin("org.jvnet.substance.skin.RavenGraphiteGlassSkin"); SubstanceLookAndFeel.setCurrentTheme("org.jvnet.substance.theme.SubstanceAquaTheme"); SubstanceLookAndFeel.setCurrentWatermark("org.jvnet.substance.watermark.SubstanceBinaryWatermark"); frmError.setLocationRelativeTo(null); frmError.setVisible(true); } //System.out.println("btnAplicarEvaluacion.actionPerformed, event="+evt); //TODO add your code for btnAplicarEvaluacion.actionPerformed } }); } } pack(); this.setSize(1028, 384); Application.getInstance().getContext().getResourceMap(getClass()).injectComponents(getContentPane()); } catch (Exception e) { //add your error handling code here e.printStackTrace(); } } public JLabel getLblBusquedaApellido() { return lblBusquedaApellido; } public void setLblBusquedaApellido(JLabel lblBusquedaApellido) { this.lblBusquedaApellido = lblBusquedaApellido; } public JLabel getLblBusquedaNombre() { return lblBusquedaNombre; } public void setLblBusquedaNombre(JLabel lblBusquedaNombre) { this.lblBusquedaNombre = lblBusquedaNombre; } public JLabel getLblBusquedaCedula() { return lblBusquedaCedula; } public void setLblBusquedaCedula(JLabel lblBusquedaCedula) { this.lblBusquedaCedula = lblBusquedaCedula; } }
Java
import java.util.Vector; import java.util.regex.Matcher; import java.util.regex.Pattern; import java.io.IOException; import java.io.PrintWriter; public class Seccion { private String numero; private Profesor prof = new Profesor(); private Vector<Alumno> vectorPrincipal = new Vector<Alumno>(); private Vector<Alumno> vectorReprobados = new Vector<Alumno>(); private Vector<Alumno> vectorAprobados = new Vector<Alumno>(); private Vector<Alumno> vectorNotaFinal = new Vector<Alumno>(); private boolean encontrado; private boolean evaluacionAplicada; private int posicion; private double promedio; private double rendimiento; public int getPosicion() { return posicion; } public void setPosicion(int posicion) { this.posicion = posicion; } public boolean isEvaluacionAplicada() { return evaluacionAplicada; } public boolean validarInscritos(){ if(this.vectorPrincipal.size() == 0){ encontrado = false; } else { encontrado = true; } return encontrado; } public boolean compararProfesorAlumno(String cedulaAlumno, String cedulaProfesor){ int cedulaAlumnoProbar = Integer.parseInt(cedulaAlumno); int cedulaProfesorComparar = Integer.parseInt(cedulaProfesor); if(cedulaAlumnoProbar == cedulaProfesorComparar){ return true; } else{ return false; } } public boolean validarEntradaLetras(String datoEntrada){ Pattern patron = Pattern.compile("[^A-Za-z^ ]"); Matcher encaja = patron.matcher(datoEntrada); if(!encaja.find()) return true; else return false; } public boolean validarEntradaSeccion(String datoEntrada){ Pattern patron = Pattern.compile("[^A-Z^0-9^-]"); Matcher encaja = patron.matcher(datoEntrada); if(!encaja.find()) return true; else return false; } public boolean validarNumeros(String datoEntrada){ try{ Integer.parseInt(datoEntrada); return true; } catch(NumberFormatException nfe){ return false; } } public boolean isEncontrado() { return encontrado; } public void setEncontrado(boolean encontrado) { this.encontrado = encontrado; } public Seccion(String numero) { super(); this.numero = numero; } public Seccion() { // TODO Auto-generated constructor stub } public void inscribirEstudiante(Alumno estudiante){ this.vectorPrincipal.addElement(estudiante); System.out.println("Hay "+vectorPrincipal.size()+" estudiantes inscritos"); } public void retirarEstudiante(String cedulaEtudiante){ int i = 0; this.encontrado = false; while((this.encontrado != true) && (i < vectorPrincipal.size())){ if(cedulaEtudiante.equals(vectorPrincipal.elementAt(i).getCI())){ this.encontrado = true; vectorPrincipal.removeElementAt(i); System.out.println("Quedan "+vectorPrincipal.size()+" estudiantes registrados"); } else { this.encontrado = false; } i++; } } public boolean busquedaCi(String cedulaBusqueda){ int i = 0; this.encontrado = false; while((this.encontrado != true) && (i < vectorPrincipal.size())){ if (vectorPrincipal.elementAt(i).getCI().equals(cedulaBusqueda)){ System.out.println("Estudiante encontrado"); System.out.println("Cédula: "+vectorPrincipal.elementAt(i).getCI()); System.out.println("Nombre: "+vectorPrincipal.elementAt(i).getNom()); System.out.println("Apellido: "+vectorPrincipal.elementAt(i).getApe()); this.posicion = i; this.encontrado = true; } else { this.encontrado = false; } i++; } return encontrado; } public void AplicarEvaluacion(){ int i = 0; while( i < this.vectorPrincipal.size()){ this.vectorPrincipal.elementAt(i).presentarExamen(); prof.evaluarEstudiante(this.vectorPrincipal.elementAt(i)); i++; }//end while this.evaluacionAplicada = true; } public void calcularPromedio(){ double acumulador = 0; int contador = 0; int i=0; while(i < this.vectorPrincipal.size()){ acumulador = acumulador + this.vectorPrincipal.elementAt(i).getNotaFinal(); contador++; i++; } this.promedio = acumulador / contador; this.rendimiento = promedio*100 /20; System.out.println("El promedio de notas de la sección es: "+Math.rint(promedio*100/100.0)+" puntos"); System.out.println(" "); System.out.println("El rendimiento de la sección es de: "+Math.rint(rendimiento*100/100.0)+"%"); } public void listadoReprobado(Seccion sec, Profesor profe){ int i = 0; int e = 0; double porcentajeReprobado; int contadorReprobado= 0; while(i < this.vectorPrincipal.size()){ if(this.vectorPrincipal.elementAt(i).getStatus() == "Reprobado"){ this.vectorReprobados.addElement(this.vectorPrincipal.elementAt(i)); contadorReprobado++; } i++; } porcentajeReprobado = contadorReprobado * 100 / this.vectorPrincipal.size(); try { PrintWriter escritura = new PrintWriter ("reprobado"); escritura.println("-----------------------------------------------------------"); System.out.println("-----------------------------------------------------------"); escritura.println("----------- Listado de Estudiantes Reprobados -------------"); System.out.println("----------- Listado de Estudiantes Reprobados -------------"); escritura.println("-----------------------------------------------------------"); System.out.println("-----------------------------------------------------------"); escritura.println(" "); System.out.println(" "); escritura.println("Numero de la Seccion: "+sec.getNumero()); escritura.println("Profesor: ("+profe.getTitulo()+") "+profe.getNom()+" "+profe.getApe()+" CI: "+profe.getCI()); escritura.println("--------------------------------------------------------------------------------------------------------"); escritura.println("La sección tiene: "+this.vectorReprobados.size()+" estudiante(s) reprobado(s)"); System.out.println("La sección tiene: "+this.vectorReprobados.size()+" estudiante(s) reprobado(s)"); escritura.println("El "+Math.rint(porcentajeReprobado*100/100.0)+" % de la sección está en condición de REPROBADO"); System.out.println("El "+Math.rint(porcentajeReprobado*100/100.0)+" % de la sección está en condición de REPROBADO"); escritura.println(" "); System.out.println(" "); while(e < this.vectorReprobados.size()){ escritura.println("Cédula: "+this.vectorReprobados.elementAt(e).getCI()); System.out.println("Cédula: "+this.vectorReprobados.elementAt(e).getCI()); escritura.println("Nombre: "+this.vectorReprobados.elementAt(e).getNom()); System.out.println("Nombre: "+this.vectorReprobados.elementAt(e).getNom()); escritura.println("Apellido: "+this.vectorReprobados.elementAt(e).getApe()); System.out.println("Apellido: "+this.vectorReprobados.elementAt(e).getApe()); escritura.println("Nota Final: "+this.vectorReprobados.elementAt(e).getNotaFinal()); System.out.println("Nota Final: "+this.vectorReprobados.elementAt(e).getNotaFinal()); escritura.println("------------------------------------------------------------"); System.out.println("-----------------------------------------------------------"); e++; } escritura.close(); //this.vectorReprobados.removeAllElements(); } catch (IOException ex) { System.out.println("ATENCION: Se produjo un error en el archivo"); } } public void listadoAprobado(Seccion sec, Profesor profe){ int i = 0; int e = 0; double porcentajeAprobado; int contadorAprobado= 0; while(i < this.vectorPrincipal.size()){ if(this.vectorPrincipal.elementAt(i).getStatus() == "Aprobado"){ this.vectorAprobados.addElement(this.vectorPrincipal.elementAt(i)); contadorAprobado++; } i++; } porcentajeAprobado = contadorAprobado * 100 / this.vectorPrincipal.size(); try { PrintWriter escritura = new PrintWriter ("aprobado"); escritura.println("----------------------------------------------------------"); System.out.println("----------------------------------------------------------"); escritura.println("----------- Listado de Estudiantes Aprobados -------------"); System.out.println("----------- Listado de Estudiantes Aprobados -------------"); escritura.println("----------------------------------------------------------"); System.out.println("----------------------------------------------------------"); escritura.println(" "); System.out.println(" "); escritura.println("Numero de la Seccion: "+sec.getNumero()); escritura.println("Profesor: ("+profe.getTitulo()+") "+profe.getNom()+" "+profe.getApe()+" CI: "+profe.getCI()); escritura.println("--------------------------------------------------------------------------------------------------------"); escritura.println("La sección tiene: "+this.vectorAprobados.size()+" estudiante(s) aprobado(s)"); System.out.println("La sección tiene: "+this.vectorAprobados.size()+" estudiante(s) aprobado(s)"); escritura.println("El "+Math.rint(porcentajeAprobado*100/100.0)+" % de la sección está en condición de APROBADO"); System.out.println("El "+Math.rint(porcentajeAprobado*100/100.0)+" % de la sección está en condición de APROBADO"); escritura.println(" "); System.out.println(" "); while(e < this.vectorAprobados.size()){ escritura.println("Cédula: "+this.vectorAprobados.elementAt(e).getCI()); System.out.println("Cédula: "+this.vectorAprobados.elementAt(e).getCI()); escritura.println("Nombre: "+this.vectorAprobados.elementAt(e).getNom()); System.out.println("Nombre: "+this.vectorAprobados.elementAt(e).getNom()); escritura.println("Apellido: "+this.vectorAprobados.elementAt(e).getApe()); System.out.println("Apellido: "+this.vectorAprobados.elementAt(e).getApe()); escritura.println("Nota Final: "+this.vectorAprobados.elementAt(e).getNotaFinal()); System.out.println("Nota Final: "+this.vectorAprobados.elementAt(e).getNotaFinal()); escritura.println("------------------------------------------------------------"); System.out.println("-----------------------------------------------------------"); e++; } escritura.close(); //this.vectorAprobados.removeAllElements(); } catch (IOException ex) { System.out.println("ATENCION: Se produjo un error en el archivo"); } } public Vector<Alumno> ordenadosCedula(Seccion sec, Profesor profe){ int e = 0; int cedulaEntero; int cedulaEntero2; Alumno auxiliar; Alumno primero; Alumno segundo; for(int j = 0; j < this.vectorPrincipal.size() - 1; j++){ for(int i = 0; i < this.vectorPrincipal.size() - 1; i++){ cedulaEntero = Integer.parseInt(this.vectorPrincipal.elementAt(i).getCI()); cedulaEntero2 = Integer.parseInt(this.vectorPrincipal.elementAt(i+1).getCI()); if(cedulaEntero < cedulaEntero2){ primero = this.vectorPrincipal.elementAt(i); segundo = this.vectorPrincipal.elementAt(i+1); auxiliar = segundo; this.vectorPrincipal.setElementAt(primero, i+1); this.vectorPrincipal.setElementAt(auxiliar, i); } } } try { PrintWriter escritura = new PrintWriter ("ordenadocedula"); escritura.println("------------------------------------------------------------------------"); System.out.println("------------------------------------------------------------------------"); escritura.println("----------- Listado de Estudiantes por Cédula de Identidad -------------"); System.out.println("----------- Listado de Estudiantes por Cédula de Identidad -------------"); escritura.println("------------------------------------------------------------------------"); System.out.println("------------------------------------------------------------------------"); escritura.println(" "); System.out.println(" "); escritura.println("Numero de la Seccion: "+sec.getNumero()); escritura.println("Profesor: ("+profe.getTitulo()+") "+profe.getNom()+" "+profe.getApe()+" CI: "+profe.getCI()); escritura.println("--------------------------------------------------------------------------------------------------------"); escritura.println("La sección tiene: "+this.vectorPrincipal.size()+" estudiante(s) inscrito(s)"); System.out.println("La sección tiene: "+this.vectorPrincipal.size()+" estudiante(s) inscrito(s)"); escritura.println(" "); System.out.println(" "); while(e < this.vectorPrincipal.size()){ escritura.println("Cédula: "+this.vectorPrincipal.elementAt(e).getCI()); System.out.println("Cédula: "+this.vectorPrincipal.elementAt(e).getCI()); escritura.println("Nombre: "+this.vectorPrincipal.elementAt(e).getNom()); System.out.println("Nombre: "+this.vectorPrincipal.elementAt(e).getNom()); escritura.println("Apellido: "+this.vectorPrincipal.elementAt(e).getApe()); System.out.println("Apellido: "+this.vectorPrincipal.elementAt(e).getApe()); escritura.println("------------------------------------------------------------"); System.out.println("-----------------------------------------------------------"); e++; } escritura.close(); } catch(IOException ex){ System.out.println("ATENCIÓN: Se produjo un error"); } return vectorPrincipal; } public void ordenadosNotaFinal(Seccion sec, Profesor profe){ int e = 0; Alumno notaAuxiliar; Alumno primero; Alumno segundo; this.vectorNotaFinal = this.vectorPrincipal; for(int j = 0; j < this.vectorNotaFinal.size() - 1; j++){ for(int i = 0; i < this.vectorNotaFinal.size() - 1; i++){ if(this.vectorNotaFinal.elementAt(i).getNotaFinal() > this.vectorNotaFinal.elementAt(i+1).getNotaFinal()){ primero = this.vectorNotaFinal.elementAt(i); segundo = this.vectorNotaFinal.elementAt(i+1); notaAuxiliar = segundo; this.vectorNotaFinal.setElementAt(primero, i+1); this.vectorNotaFinal.setElementAt(notaAuxiliar, i); } } } try { PrintWriter escritura = new PrintWriter ("ordenadonotafinal"); escritura.println("------------------------------------------------------------------"); System.out.println("------------------------------------------------------------------"); escritura.println("----------- Listado de Estudiantes por su Nota Final -------------"); System.out.println("----------- Listado de Estudiantes por su Nota Final -------------"); escritura.println("------------------------------------------------------------------"); System.out.println("------------------------------------------------------------------"); escritura.println(" "); System.out.println(" "); escritura.println("Numero de la Seccion: "+sec.getNumero()); escritura.println("Profesor: ("+profe.getTitulo()+") "+profe.getNom()+" "+profe.getApe()+" CI: "+profe.getCI()); escritura.println("--------------------------------------------------------------------------------------------------------"); escritura.println("La sección tiene: "+this.vectorNotaFinal.size()+" estudiante(s) inscrito(s)"); System.out.println("La sección tiene: "+this.vectorNotaFinal.size()+" estudiante(s) inscrito(s)"); escritura.println(" "); System.out.println(" "); while(e < this.vectorNotaFinal.size()){ escritura.println("Cédula: "+this.vectorNotaFinal.elementAt(e).getCI()); System.out.println("Cédula: "+this.vectorNotaFinal.elementAt(e).getCI()); escritura.println("Nombre: "+this.vectorNotaFinal.elementAt(e).getNom()); System.out.println("Nombre: "+this.vectorNotaFinal.elementAt(e).getNom()); escritura.println("Apellido: "+this.vectorNotaFinal.elementAt(e).getApe()); System.out.println("Apellido: "+this.vectorNotaFinal.elementAt(e).getApe()); escritura.println("Nota Final: "+this.vectorNotaFinal.elementAt(e).getNotaFinal()); System.out.println("Nota Final: "+this.vectorNotaFinal.elementAt(e).getNotaFinal()); escritura.println("------------------------------------------------------------"); System.out.println("-----------------------------------------------------------"); e++; } escritura.close(); } catch(IOException ex){ System.out.println("ATENCIÓN: Se produjo un error"); } } public void setNumero(String num) { this.numero = num; } public String getNumero() { return numero; } public Vector<Alumno> getVectorPrincipal() { return vectorPrincipal; } public void setVectorPrincipal(Vector<Alumno> vectorPrincipal) { this.vectorPrincipal = vectorPrincipal; } public double getPromedio() { return promedio; } public double getRendimiento() { return rendimiento; } public Vector<Alumno> getVectorReprobados() { return vectorReprobados; } public void setVectorReprobados(Vector<Alumno> vectorReprobados) { this.vectorReprobados = vectorReprobados; } public Vector<Alumno> getVectorAprobados() { return vectorAprobados; } public void setVectorAprobados(Vector<Alumno> vectorAprobados) { this.vectorAprobados = vectorAprobados; } public Vector<Alumno> getVectorNotaFinal() { return vectorNotaFinal; } public void setVectorNotaFinal(Vector<Alumno> vectorNotaFinal) { this.vectorNotaFinal = vectorNotaFinal; } }
Java
package org.anddev.andengine.examples; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnAreaTouchListener; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.scene.Scene.ITouchArea; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.examples.adt.messages.client.ClientMessageFlags; import org.anddev.andengine.examples.adt.messages.server.ConnectionCloseServerMessage; import org.anddev.andengine.examples.adt.messages.server.ServerMessageFlags; import org.anddev.andengine.examples.util.BluetoothListDevicesActivity; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.IMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.IServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; import org.anddev.andengine.extension.multiplayer.protocol.client.IServerMessageHandler; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.BluetoothSocketConnectionServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.BluetoothSocketConnectionServerConnector.IBluetoothSocketConnectionServerConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.client.connector.ServerConnector; import org.anddev.andengine.extension.multiplayer.protocol.exception.BluetoothException; import org.anddev.andengine.extension.multiplayer.protocol.server.BluetoothSocketServer; import org.anddev.andengine.extension.multiplayer.protocol.server.BluetoothSocketServer.IBluetoothSocketServerListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.BluetoothSocketConnectionClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.BluetoothSocketConnectionClientConnector.IBluetoothSocketConnectionClientConnectorListener; import org.anddev.andengine.extension.multiplayer.protocol.server.connector.ClientConnector; import org.anddev.andengine.extension.multiplayer.protocol.shared.BluetoothSocketConnection; import org.anddev.andengine.extension.multiplayer.protocol.util.MessagePool; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.util.Debug; import android.app.AlertDialog; import android.app.Dialog; import android.bluetooth.BluetoothAdapter; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.util.SparseArray; import android.view.KeyEvent; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:45:03 - 06.03.2011 */ public class MultiplayerBluetoothExample extends BaseExample implements ClientMessageFlags, ServerMessageFlags { // =========================================================== // Constants // =========================================================== /** Create your own unique UUID at: http://www.uuidgenerator.com/ */ private static final String EXAMPLE_UUID = "6D2DF50E-06EF-C21C-7DB0-345099A5F64E"; private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final short FLAG_MESSAGE_SERVER_ADD_FACE = 1; private static final short FLAG_MESSAGE_SERVER_MOVE_FACE = FLAG_MESSAGE_SERVER_ADD_FACE + 1; private static final int DIALOG_CHOOSE_SERVER_OR_CLIENT_ID = 0; private static final int DIALOG_SHOW_SERVER_IP_ID = DIALOG_CHOOSE_SERVER_OR_CLIENT_ID + 1; private static final int REQUESTCODE_BLUETOOTH_ENABLE = 0; private static final int REQUESTCODE_BLUETOOTH_CONNECT = REQUESTCODE_BLUETOOTH_ENABLE + 1; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private int mFaceIDCounter; private final SparseArray<Sprite> mFaces = new SparseArray<Sprite>(); private String mServerMACAddress; private BluetoothSocketServer<BluetoothSocketConnectionClientConnector> mBluetoothSocketServer; private ServerConnector<BluetoothSocketConnection> mServerConnector; private final MessagePool<IMessage> mMessagePool = new MessagePool<IMessage>(); private BluetoothAdapter mBluetoothAdapter; // =========================================================== // Constructors // =========================================================== public MultiplayerBluetoothExample() { this.initMessagePool(); } private void initMessagePool() { this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class); this.mMessagePool.registerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class); } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected void onCreate(final Bundle pSavedInstanceState) { super.onCreate(pSavedInstanceState); this.mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); this.mServerMACAddress = BluetoothAdapter.getDefaultAdapter().getAddress(); if (this.mBluetoothAdapter == null) { Toast.makeText(this, "Bluetooth is not available!", Toast.LENGTH_LONG).show(); this.finish(); return; } else { if (this.mBluetoothAdapter.isEnabled()) { this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); } else { final Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); this.startActivityForResult(enableIntent, REQUESTCODE_BLUETOOTH_ENABLE); } } } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_SHOW_SERVER_IP_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Server-Details") .setCancelable(false) .setMessage("The Name of your Server is:\n" + BluetoothAdapter.getDefaultAdapter().getName() + "\n" + "The MACAddress of your Server is:\n" + this.mServerMACAddress) .setPositiveButton(android.R.string.ok, null) .create(); case DIALOG_CHOOSE_SERVER_OR_CLIENT_ID: return new AlertDialog.Builder(this) .setIcon(android.R.drawable.ic_dialog_info) .setTitle("Be Server or Client ...") .setCancelable(false) .setPositiveButton("Client", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { final Intent intent = new Intent(MultiplayerBluetoothExample.this, BluetoothListDevicesActivity.class); MultiplayerBluetoothExample.this.startActivityForResult(intent, REQUESTCODE_BLUETOOTH_CONNECT); } }) .setNeutralButton("Server", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerBluetoothExample.this.toast("You can add and move sprites, which are only shown on the clients."); MultiplayerBluetoothExample.this.initServer(); MultiplayerBluetoothExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .setNegativeButton("Both", new OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { MultiplayerBluetoothExample.this.toast("You can add sprites and move them, by dragging them."); MultiplayerBluetoothExample.this.initServerAndClient(); MultiplayerBluetoothExample.this.showDialog(DIALOG_SHOW_SERVER_IP_ID); } }) .create(); default: return super.onCreateDialog(pID); } } @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override protected void onDestroy() { if(this.mBluetoothSocketServer != null) { try { this.mBluetoothSocketServer.sendBroadcastServerMessage(new ConnectionCloseServerMessage()); } catch (final IOException e) { Debug.e(e); } this.mBluetoothSocketServer.terminate(); } if(this.mServerConnector != null) { this.mServerConnector.terminate(); } super.onDestroy(); } @Override public boolean onKeyUp(final int pKeyCode, final KeyEvent pEvent) { switch(pKeyCode) { case KeyEvent.KEYCODE_BACK: this.finish(); return true; } return super.onKeyUp(pKeyCode, pEvent); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); /* We allow only the server to actively send around messages. */ if(MultiplayerBluetoothExample.this.mBluetoothSocketServer != null) { scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { if(pSceneTouchEvent.isActionDown()) { try { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage) MultiplayerBluetoothExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_ADD_FACE); addFaceServerMessage.set(MultiplayerBluetoothExample.this.mFaceIDCounter++, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerBluetoothExample.this.mBluetoothSocketServer.sendBroadcastServerMessage(addFaceServerMessage); MultiplayerBluetoothExample.this.mMessagePool.recycleMessage(addFaceServerMessage); } catch (final IOException e) { Debug.e(e); } return true; } else { return false; } } }); scene.setOnAreaTouchListener(new IOnAreaTouchListener() { @Override public boolean onAreaTouched(final TouchEvent pSceneTouchEvent, final ITouchArea pTouchArea, final float pTouchAreaLocalX, final float pTouchAreaLocalY) { try { final Sprite face = (Sprite)pTouchArea; final Integer faceID = (Integer)face.getUserData(); final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage) MultiplayerBluetoothExample.this.mMessagePool.obtainMessage(FLAG_MESSAGE_SERVER_MOVE_FACE); moveFaceServerMessage.set(faceID, pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); MultiplayerBluetoothExample.this.mBluetoothSocketServer.sendBroadcastServerMessage(moveFaceServerMessage); MultiplayerBluetoothExample.this.mMessagePool.recycleMessage(moveFaceServerMessage); } catch (final IOException e) { Debug.e(e); return false; } return true; } }); scene.setTouchAreaBindingEnabled(true); } return scene; } @Override public void onLoadComplete() { } @Override protected void onActivityResult(final int pRequestCode, final int pResultCode, final Intent pData) { switch(pRequestCode) { case REQUESTCODE_BLUETOOTH_ENABLE: this.showDialog(DIALOG_CHOOSE_SERVER_OR_CLIENT_ID); break; case REQUESTCODE_BLUETOOTH_CONNECT: this.mServerMACAddress = pData.getExtras().getString(BluetoothListDevicesActivity.EXTRA_DEVICE_ADDRESS); this.initClient(); break; default: super.onActivityResult(pRequestCode, pResultCode, pData); } } // =========================================================== // Methods // =========================================================== public void addFace(final int pID, final float pX, final float pY) { final Scene scene = this.mEngine.getScene(); /* Create the face and add it to the scene. */ final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); face.setUserData(pID); this.mFaces.put(pID, face); scene.registerTouchArea(face); scene.attachChild(face); } public void moveFace(final int pID, final float pX, final float pY) { /* Find and move the face. */ final Sprite face = this.mFaces.get(pID); face.setPosition(pX - face.getWidth() * 0.5f, pY - face.getHeight() * 0.5f); } private void initServerAndClient() { this.initServer(); /* Wait some time after the server has been started, so it actually can start up. */ try { Thread.sleep(500); } catch (final Throwable t) { Debug.e(t); } this.initClient(); } private void initServer() { this.mServerMACAddress = BluetoothAdapter.getDefaultAdapter().getAddress(); try { this.mBluetoothSocketServer = new BluetoothSocketServer<BluetoothSocketConnectionClientConnector>(EXAMPLE_UUID, new ExampleClientConnectorListener(), new ExampleServerStateListener()) { @Override protected BluetoothSocketConnectionClientConnector newClientConnector(final BluetoothSocketConnection pBluetoothSocketConnection) throws IOException { try { return new BluetoothSocketConnectionClientConnector(pBluetoothSocketConnection); } catch (final BluetoothException e) { Debug.e(e); /* Actually cannot happen. */ return null; } } }; } catch (final BluetoothException e) { Debug.e(e); } this.mBluetoothSocketServer.start(); } private void initClient() { try { this.mServerConnector = new BluetoothSocketConnectionServerConnector(new BluetoothSocketConnection(this.mBluetoothAdapter, this.mServerMACAddress, EXAMPLE_UUID), new ExampleServerConnectorListener()); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_CONNECTION_CLOSE, ConnectionCloseServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { MultiplayerBluetoothExample.this.finish(); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_ADD_FACE, AddFaceServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final AddFaceServerMessage addFaceServerMessage = (AddFaceServerMessage)pServerMessage; MultiplayerBluetoothExample.this.addFace(addFaceServerMessage.mID, addFaceServerMessage.mX, addFaceServerMessage.mY); } }); this.mServerConnector.registerServerMessage(FLAG_MESSAGE_SERVER_MOVE_FACE, MoveFaceServerMessage.class, new IServerMessageHandler<BluetoothSocketConnection>() { @Override public void onHandleMessage(final ServerConnector<BluetoothSocketConnection> pServerConnector, final IServerMessage pServerMessage) throws IOException { final MoveFaceServerMessage moveFaceServerMessage = (MoveFaceServerMessage)pServerMessage; MultiplayerBluetoothExample.this.moveFace(moveFaceServerMessage.mID, moveFaceServerMessage.mX, moveFaceServerMessage.mY); } }); this.mServerConnector.getConnection().start(); } catch (final Throwable t) { Debug.e(t); } } private void log(final String pMessage) { Debug.d(pMessage); } private void toast(final String pMessage) { this.log(pMessage); this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(MultiplayerBluetoothExample.this, pMessage, Toast.LENGTH_SHORT).show(); } }); } // =========================================================== // Inner and Anonymous Classes // =========================================================== public static class AddFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public AddFaceServerMessage() { } public AddFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_ADD_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } public static class MoveFaceServerMessage extends ServerMessage { private int mID; private float mX; private float mY; public MoveFaceServerMessage() { } public MoveFaceServerMessage(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } public void set(final int pID, final float pX, final float pY) { this.mID = pID; this.mX = pX; this.mY = pY; } @Override public short getFlag() { return FLAG_MESSAGE_SERVER_MOVE_FACE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } } private class ExampleServerConnectorListener implements IBluetoothSocketConnectionServerConnectorListener { @Override public void onStarted(final ServerConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("CLIENT: Connected to server."); } @Override public void onTerminated(final ServerConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("CLIENT: Disconnected from Server..."); MultiplayerBluetoothExample.this.finish(); } } private class ExampleServerStateListener implements IBluetoothSocketServerListener<BluetoothSocketConnectionClientConnector> { @Override public void onStarted(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer) { MultiplayerBluetoothExample.this.toast("SERVER: Started."); } @Override public void onTerminated(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer) { MultiplayerBluetoothExample.this.toast("SERVER: Terminated."); } @Override public void onException(final BluetoothSocketServer<BluetoothSocketConnectionClientConnector> pBluetoothSocketServer, final Throwable pThrowable) { Debug.e(pThrowable); MultiplayerBluetoothExample.this.toast("SERVER: Exception: " + pThrowable); } } private class ExampleClientConnectorListener implements IBluetoothSocketConnectionClientConnectorListener { @Override public void onStarted(final ClientConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("SERVER: Client connected: " + pConnector.getConnection().getBluetoothSocket().getRemoteDevice().getAddress()); } @Override public void onTerminated(final ClientConnector<BluetoothSocketConnection> pConnector) { MultiplayerBluetoothExample.this.toast("SERVER: Client disconnected: " + pConnector.getConnection().getBluetoothSocket().getRemoteDevice().getAddress()); } } }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.IEntity; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.DelayModifier; import org.anddev.andengine.entity.modifier.IEntityModifier.IEntityModifierListener; import org.anddev.andengine.entity.modifier.LoopEntityModifier; import org.anddev.andengine.entity.modifier.LoopEntityModifier.ILoopEntityModifierListener; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationByModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.primitive.Rectangle; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; import org.anddev.andengine.util.modifier.IModifier; import org.anddev.andengine.util.modifier.LoopModifier; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class EntityModifierExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Rectangle rect = new Rectangle(centerX + 100, centerY, 32, 32); rect.setColor(1, 0, 0); final AnimatedSprite face = new AnimatedSprite(centerX - 100, centerY, this.mFaceTextureRegion); face.animate(100); face.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); final LoopEntityModifier entityModifier = new LoopEntityModifier( new IEntityModifierListener() { @Override public void onModifierStarted(final IModifier<IEntity> pModifier, final IEntity pItem) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onModifierFinished(final IModifier<IEntity> pEntityModifier, final IEntity pEntity) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Sequence finished.", Toast.LENGTH_SHORT).show(); } }); } }, 2, new ILoopEntityModifierListener() { @Override public void onLoopStarted(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' started.", Toast.LENGTH_SHORT).show(); } }); } @Override public void onLoopFinished(final LoopModifier<IEntity> pLoopModifier, final int pLoop, final int pLoopCount) { EntityModifierExample.this.runOnUiThread(new Runnable() { @Override public void run() { Toast.makeText(EntityModifierExample.this, "Loop: '" + (pLoop + 1) + "' of '" + pLoopCount + "' finished.", Toast.LENGTH_SHORT).show(); } }); } }, new SequenceEntityModifier( new RotationModifier(1, 0, 90), new AlphaModifier(2, 1, 0), new AlphaModifier(1, 0, 1), new ScaleModifier(2, 1, 0.5f), new DelayModifier(0.5f), new ParallelEntityModifier( new ScaleModifier(3, 0.5f, 5), new RotationByModifier(3, 90) ), new ParallelEntityModifier( new ScaleModifier(3, 5, 1), new RotationModifier(3, 180, 0) ) ) ); face.registerEntityModifier(entityModifier); rect.registerEntityModifier(entityModifier.clone()); scene.attachChild(face); scene.attachChild(rect); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.card; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:59:33 - 18.06.2010 */ public enum Color { // =========================================================== // Elements // =========================================================== CLUB, // Kreuz DIAMOND, HEART, SPADE; // PIK // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.card; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:59:46 - 18.06.2010 */ public enum Value { // =========================================================== // Elements // =========================================================== ACE, ONE, TWO, THREE, FOUR, FIVE, SIX, SEVEN, EIGHT, NINE, TEN, JACK, QUEEN, KING; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.card; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 18:59:13 - 18.06.2010 */ public enum Card { // =========================================================== // Elements // =========================================================== CLUB_ACE(Color.CLUB, Value.ACE), CLUB_ONE(Color.CLUB, Value.ONE), CLUB_TWO(Color.CLUB, Value.TWO), CLUB_THREE(Color.CLUB, Value.THREE), CLUB_FOUR(Color.CLUB, Value.FOUR), CLUB_FIVE(Color.CLUB, Value.FIVE), CLUB_SIX(Color.CLUB, Value.SIX), CLUB_SEVEN(Color.CLUB, Value.SEVEN), CLUB_EIGHT(Color.CLUB, Value.EIGHT), CLUB_NINE(Color.CLUB, Value.NINE), CLUB_TEN(Color.CLUB, Value.TEN), CLUB_JACK(Color.CLUB, Value.JACK), CLUB_QUEEN(Color.CLUB, Value.QUEEN), CLUB_KING(Color.CLUB, Value.KING), DIAMOND_ACE(Color.DIAMOND, Value.ACE), DIAMOND_ONE(Color.DIAMOND, Value.ONE), DIAMOND_TWO(Color.DIAMOND, Value.TWO), DIAMOND_THREE(Color.DIAMOND, Value.THREE), DIAMOND_FOUR(Color.DIAMOND, Value.FOUR), DIAMOND_FIVE(Color.DIAMOND, Value.FIVE), DIAMOND_SIX(Color.DIAMOND, Value.SIX), DIAMOND_SEVEN(Color.DIAMOND, Value.SEVEN), DIAMOND_EIGHT(Color.DIAMOND, Value.EIGHT), DIAMOND_NINE(Color.DIAMOND, Value.NINE), DIAMOND_TEN(Color.DIAMOND, Value.TEN), DIAMOND_JACK(Color.DIAMOND, Value.JACK), DIAMOND_QUEEN(Color.DIAMOND, Value.QUEEN), DIAMOND_KING(Color.DIAMOND, Value.KING), HEART_ACE(Color.HEART, Value.ACE), HEART_ONE(Color.HEART, Value.ONE), HEART_TWO(Color.HEART, Value.TWO), HEART_THREE(Color.HEART, Value.THREE), HEART_FOUR(Color.HEART, Value.FOUR), HEART_FIVE(Color.HEART, Value.FIVE), HEART_SIX(Color.HEART, Value.SIX), HEART_SEVEN(Color.HEART, Value.SEVEN), HEART_EIGHT(Color.HEART, Value.EIGHT), HEART_NINE(Color.HEART, Value.NINE), HEART_TEN(Color.HEART, Value.TEN), HEART_JACK(Color.HEART, Value.JACK), HEART_QUEEN(Color.HEART, Value.QUEEN), HEART_KING(Color.HEART, Value.KING), SPADE_ACE(Color.SPADE, Value.ACE), SPADE_ONE(Color.SPADE, Value.ONE), SPADE_TWO(Color.SPADE, Value.TWO), SPADE_THREE(Color.SPADE, Value.THREE), SPADE_FOUR(Color.SPADE, Value.FOUR), SPADE_FIVE(Color.SPADE, Value.FIVE), SPADE_SIX(Color.SPADE, Value.SIX), SPADE_SEVEN(Color.SPADE, Value.SEVEN), SPADE_EIGHT(Color.SPADE, Value.EIGHT), SPADE_NINE(Color.SPADE, Value.NINE), SPADE_TEN(Color.SPADE, Value.TEN), SPADE_JACK(Color.SPADE, Value.JACK), SPADE_QUEEN(Color.SPADE, Value.QUEEN), SPADE_KING(Color.SPADE, Value.KING); // =========================================================== // Constants // =========================================================== public static final int CARD_WIDTH = 71; public static final int CARD_HEIGHT = 96; // =========================================================== // Fields // =========================================================== public final Color mColor; public final Value mValue; // =========================================================== // Constructors // =========================================================== private Card(final Color pColor, final Value pValue) { this.mColor = pColor; this.mValue = pValue; } // =========================================================== // Getter & Setter // =========================================================== public int getTexturePositionX() { return this.mValue.ordinal() * CARD_WIDTH; } public int getTexturePositionY() { return this.mColor.ordinal() * CARD_HEIGHT; } // =========================================================== // Methods from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.cityradar; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 20:32:16 - 28.10.2010 */ public class City { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private final String mName; private final double mLatitude; private final double mLongitude; private double mDistanceToUser; private double mBearingToUser; // =========================================================== // Constructors // =========================================================== public City(final String pName, final double pLatitude, final double pLongitude) { this.mName = pName; this.mLatitude = pLatitude; this.mLongitude = pLongitude; } // =========================================================== // Getter & Setter // =========================================================== public final String getName() { return this.mName; } public final double getLatitude() { return this.mLatitude; } public final double getLongitude() { return this.mLongitude; } public double getDistanceToUser() { return this.mDistanceToUser; } public void setDistanceToUser(final double pDistanceToUser) { this.mDistanceToUser = pDistanceToUser; } public double getBearingToUser() { return this.mBearingToUser; } public void setBearingToUser(final double pBearingToUser) { this.mBearingToUser = pBearingToUser; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:36 - 21.05.2011 */ public class ConnectionCloseClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionCloseClientMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:31 - 21.05.2011 */ public class ConnectionEstablishClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private short mProtocolVersion; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionEstablishClientMessage() { } public ConnectionEstablishClientMessage(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Getter & Setter // =========================================================== public short getProtocolVersion() { return this.mProtocolVersion; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return ClientMessageFlags.FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mProtocolVersion = pDataInputStream.readShort(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeShort(this.mProtocolVersion); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:00:00 - 21.05.2011 */ public interface ClientMessageFlags { // =========================================================== // Final Fields // =========================================================== /* Connection Flags. */ public static final short FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE = Short.MIN_VALUE; public static final short FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH = FLAG_MESSAGE_CLIENT_CONNECTION_CLOSE + 1; public static final short FLAG_MESSAGE_CLIENT_CONNECTION_PING = FLAG_MESSAGE_CLIENT_CONNECTION_ESTABLISH + 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:37 - 21.05.2011 */ public class ConnectionPingClientMessage extends ClientMessage implements ClientMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private long mTimestamp; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionPingClientMessage() { } // =========================================================== // Getter & Setter // =========================================================== public long getTimestamp() { return this.mTimestamp; } public void setTimestamp(final long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_CONNECTION_PING; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mTimestamp = pDataInputStream.readLong(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeLong(this.mTimestamp); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:18:34 - 21.05.2011 */ public class MessageConstants { // =========================================================== // Constants // =========================================================== public static final short PROTOCOL_VERSION = 1; // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 11:59:39 - 21.05.2011 */ public interface ServerMessageFlags { // =========================================================== // Final Fields // =========================================================== /* Connection Flags. */ public static final short FLAG_MESSAGE_SERVER_CONNECTION_CLOSE = Short.MIN_VALUE; public static final short FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED = FLAG_MESSAGE_SERVER_CONNECTION_CLOSE + 1; public static final short FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH = FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED + 1; public static final short FLAG_MESSAGE_SERVER_CONNECTION_PONG = FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH + 1; // =========================================================== // Methods // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:20 - 21.05.2011 */ public class ConnectionPongServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private long mTimestamp; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionPongServerMessage() { } public ConnectionPongServerMessage(final long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Getter & Setter // =========================================================== public long getTimestamp() { return this.mTimestamp; } public void setTimestamp(long pTimestamp) { this.mTimestamp = pTimestamp; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_PONG; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mTimestamp = pDataInputStream.readLong(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeLong(this.mTimestamp); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:25 - 21.05.2011 */ public class ConnectionEstablishedServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionEstablishedServerMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_ESTABLISHED; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 16:11:40 - 11.03.2011 */ public class ConnectionCloseServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== public ConnectionCloseServerMessage() { } // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_CLOSE; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { /* Nothing to read. */ } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { /* Nothing to write. */ } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 12:23:15 - 21.05.2011 */ public class ConnectionRejectedProtocolMissmatchServerMessage extends ServerMessage implements ServerMessageFlags { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== private short mProtocolVersion; // =========================================================== // Constructors // =========================================================== @Deprecated public ConnectionRejectedProtocolMissmatchServerMessage() { } public ConnectionRejectedProtocolMissmatchServerMessage(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Getter & Setter // =========================================================== public short getProtocolVersion() { return this.mProtocolVersion; } public void setProtocolVersion(final short pProtocolVersion) { this.mProtocolVersion = pProtocolVersion; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_CONNECTION_REJECTED_PROTOCOL_MISSMATCH; } @Override protected void onReadTransmissionData(final DataInputStream pDataInputStream) throws IOException { this.mProtocolVersion = pDataInputStream.readShort(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeShort(this.mProtocolVersion); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.adt; public enum ZoomState { // =========================================================== // Elements // =========================================================== IN, OUT, NONE; // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl.IOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.DigitalOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class DigitalOnScreenControlExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; private static final int DIALOG_ALLOWDIAGONAL_ID = 0; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; private DigitalOnScreenControl mDigitalOnScreenControl; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); this.mDigitalOnScreenControl = new DigitalOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, new IOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } }); this.mDigitalOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mDigitalOnScreenControl.getControlBase().setAlpha(0.5f); this.mDigitalOnScreenControl.getControlBase().setScaleCenter(0, 128); this.mDigitalOnScreenControl.getControlBase().setScale(1.25f); this.mDigitalOnScreenControl.getControlKnob().setScale(1.25f); this.mDigitalOnScreenControl.refreshControlKnobPosition(); scene.setChildScene(this.mDigitalOnScreenControl); return scene; } @Override public void onLoadComplete() { this.showDialog(DIALOG_ALLOWDIAGONAL_ID); } @Override protected Dialog onCreateDialog(final int pID) { switch(pID) { case DIALOG_ALLOWDIAGONAL_ID: return new AlertDialog.Builder(this) .setTitle("Setup...") .setMessage("Do you wish to allow diagonal directions on the OnScreenControl?") .setPositiveButton("Yes", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { DigitalOnScreenControlExample.this.mDigitalOnScreenControl.setAllowDiagonal(true); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { @Override public void onClick(final DialogInterface pDialog, final int pWhich) { DigitalOnScreenControlExample.this.mDigitalOnScreenControl.setAllowDiagonal(false); } }) .create(); } return super.onCreateDialog(pID); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.particle.ParticleSystem; import org.anddev.andengine.entity.particle.emitter.CircleOutlineParticleEmitter; import org.anddev.andengine.entity.particle.initializer.AlphaInitializer; import org.anddev.andengine.entity.particle.initializer.ColorInitializer; import org.anddev.andengine.entity.particle.initializer.RotationInitializer; import org.anddev.andengine.entity.particle.initializer.VelocityInitializer; import org.anddev.andengine.entity.particle.modifier.AlphaModifier; import org.anddev.andengine.entity.particle.modifier.ColorModifier; import org.anddev.andengine.entity.particle.modifier.ExpireModifier; import org.anddev.andengine.entity.particle.modifier.ScaleModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.Scene.IOnSceneTouchListener; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.input.touch.TouchEvent; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.ui.activity.LayoutGameActivity; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class XMLLayoutExample extends LayoutGameActivity { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mParticleTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override protected int getLayoutID() { return R.layout.xmllayoutexample; } @Override protected int getRenderSurfaceViewID() { return R.id.xmllayoutexample_rendersurfaceview; } @Override public Engine onLoadEngine() { Toast.makeText(this, "Touch the screen to move the particlesystem.", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mParticleTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/particle_point.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final CircleOutlineParticleEmitter particleEmitter = new CircleOutlineParticleEmitter(CAMERA_WIDTH * 0.5f, CAMERA_HEIGHT * 0.5f + 20, 80); final ParticleSystem particleSystem = new ParticleSystem(particleEmitter, 60, 60, 360, this.mParticleTextureRegion); scene.setOnSceneTouchListener(new IOnSceneTouchListener() { @Override public boolean onSceneTouchEvent(final Scene pScene, final TouchEvent pSceneTouchEvent) { particleEmitter.setCenter(pSceneTouchEvent.getX(), pSceneTouchEvent.getY()); return true; } }); particleSystem.addParticleInitializer(new ColorInitializer(1, 0, 0)); particleSystem.addParticleInitializer(new AlphaInitializer(0)); particleSystem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE); particleSystem.addParticleInitializer(new VelocityInitializer(-2, 2, -20, -10)); particleSystem.addParticleInitializer(new RotationInitializer(0.0f, 360.0f)); particleSystem.addParticleModifier(new ScaleModifier(1.0f, 2.0f, 0, 5)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0, 0.5f, 0, 0, 0, 3)); particleSystem.addParticleModifier(new ColorModifier(1, 1, 0.5f, 1, 0, 1, 4, 6)); particleSystem.addParticleModifier(new AlphaModifier(0, 1, 0, 1)); particleSystem.addParticleModifier(new AlphaModifier(1, 0, 5, 6)); particleSystem.addParticleModifier(new ExpireModifier(6, 6)); scene.attachChild(particleSystem); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.AlphaModifier; import org.anddev.andengine.entity.modifier.ParallelEntityModifier; import org.anddev.andengine.entity.modifier.RotationModifier; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.text.Text; import org.anddev.andengine.entity.text.TickerText; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.font.Font; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.util.HorizontalAlign; import android.graphics.Color; import android.graphics.Typeface; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class TickerTextExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mFontTexture; private Font mFont; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mFontTexture = new BitmapTextureAtlas(256, 256, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFont = new Font(this.mFontTexture, Typeface.create(Typeface.DEFAULT, Typeface.BOLD), 32, true, Color.BLACK); this.mEngine.getTextureManager().loadTexture(this.mFontTexture); this.mEngine.getFontManager().loadFont(this.mFont); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Text text = new TickerText(30, 60, this.mFont, "There are also ticker texts!\n\nYou'll see the answer to life & universe in...\n\n5 4 3 2 1...\n\n42\n\nIndeed very funny!", HorizontalAlign.CENTER, 10); text.registerEntityModifier( new SequenceEntityModifier( new ParallelEntityModifier( new AlphaModifier(10, 0.0f, 1.0f), new ScaleModifier(10, 0.5f, 1.0f) ), new RotationModifier(5, 0, 360) ) ); text.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); scene.attachChild(text); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class MovingBallExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; private static final float DEMO_VELOCITY = 100.0f; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_circle_tiled.png", 0, 0, 2, 1); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Ball ball = new Ball(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(ball); ball.registerUpdateHandler(physicsHandler); physicsHandler.setVelocity(DEMO_VELOCITY, DEMO_VELOCITY); scene.attachChild(ball); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== private static class Ball extends AnimatedSprite { private final PhysicsHandler mPhysicsHandler; public Ball(final float pX, final float pY, final TiledTextureRegion pTextureRegion) { super(pX, pY, pTextureRegion); this.mPhysicsHandler = new PhysicsHandler(this); this.registerUpdateHandler(this.mPhysicsHandler); } @Override protected void onManagedUpdate(final float pSecondsElapsed) { if(this.mX < 0) { this.mPhysicsHandler.setVelocityX(DEMO_VELOCITY); } else if(this.mX + this.getWidth() > CAMERA_WIDTH) { this.mPhysicsHandler.setVelocityX(-DEMO_VELOCITY); } if(this.mY < 0) { this.mPhysicsHandler.setVelocityY(DEMO_VELOCITY); } else if(this.mY + this.getHeight() > CAMERA_HEIGHT) { this.mPhysicsHandler.setVelocityY(-DEMO_VELOCITY); } super.onManagedUpdate(pSecondsElapsed); } } }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl; import org.anddev.andengine.engine.camera.hud.controls.AnalogOnScreenControl.IAnalogOnScreenControlListener; import org.anddev.andengine.engine.camera.hud.controls.BaseOnScreenControl; import org.anddev.andengine.engine.handler.physics.PhysicsHandler; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.ScaleModifier; import org.anddev.andengine.entity.modifier.SequenceEntityModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 00:06:23 - 11.07.2010 */ public class AnalogOnScreenControlExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 480; private static final int CAMERA_HEIGHT = 320; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; private BitmapTextureAtlas mOnScreenControlTexture; private TextureRegion mOnScreenControlBaseTextureRegion; private TextureRegion mOnScreenControlKnobTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "Also try tapping this AnalogOnScreenControl!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { BitmapTextureAtlasTextureRegionFactory.setAssetBasePath("gfx/"); this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "face_box.png", 0, 0); this.mOnScreenControlTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mOnScreenControlBaseTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_base.png", 0, 0); this.mOnScreenControlKnobTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mOnScreenControlTexture, this, "onscreen_control_knob.png", 128, 0); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mOnScreenControlTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); scene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); final PhysicsHandler physicsHandler = new PhysicsHandler(face); face.registerUpdateHandler(physicsHandler); scene.attachChild(face); final AnalogOnScreenControl analogOnScreenControl = new AnalogOnScreenControl(0, CAMERA_HEIGHT - this.mOnScreenControlBaseTextureRegion.getHeight(), this.mCamera, this.mOnScreenControlBaseTextureRegion, this.mOnScreenControlKnobTextureRegion, 0.1f, 200, new IAnalogOnScreenControlListener() { @Override public void onControlChange(final BaseOnScreenControl pBaseOnScreenControl, final float pValueX, final float pValueY) { physicsHandler.setVelocity(pValueX * 100, pValueY * 100); } @Override public void onControlClick(final AnalogOnScreenControl pAnalogOnScreenControl) { face.registerEntityModifier(new SequenceEntityModifier(new ScaleModifier(0.25f, 1, 1.5f), new ScaleModifier(0.25f, 1.5f, 1))); } }); analogOnScreenControl.getControlBase().setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); analogOnScreenControl.getControlBase().setAlpha(0.5f); analogOnScreenControl.getControlBase().setScaleCenter(0, 128); analogOnScreenControl.getControlBase().setScale(1.25f); analogOnScreenControl.getControlKnob().setScale(1.25f); analogOnScreenControl.refreshControlKnobPosition(); scene.setChildScene(analogOnScreenControl); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.AutoParallaxBackground; import org.anddev.andengine.entity.scene.background.ParallaxBackground.ParallaxEntity; import org.anddev.andengine.entity.sprite.AnimatedSprite; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import org.anddev.andengine.opengl.texture.region.TiledTextureRegion; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 19:58:39 - 19.07.2010 */ public class AutoParallaxBackgroundExample extends BaseExample { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TiledTextureRegion mPlayerTextureRegion; private TiledTextureRegion mEnemyTextureRegion; private BitmapTextureAtlas mAutoParallaxBackgroundTexture; private TextureRegion mParallaxLayerBack; private TextureRegion mParallaxLayerMid; private TextureRegion mParallaxLayerFront; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mPlayerTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/player.png", 0, 0, 3, 4); this.mEnemyTextureRegion = BitmapTextureAtlasTextureRegionFactory.createTiledFromAsset(this.mBitmapTextureAtlas, this, "gfx/enemy.png", 73, 0, 3, 4); this.mAutoParallaxBackgroundTexture = new BitmapTextureAtlas(1024, 1024, TextureOptions.DEFAULT); this.mParallaxLayerFront = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "gfx/parallax_background_layer_front.png", 0, 0); this.mParallaxLayerBack = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "gfx/parallax_background_layer_back.png", 0, 188); this.mParallaxLayerMid = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mAutoParallaxBackgroundTexture, this, "gfx/parallax_background_layer_mid.png", 0, 669); this.mEngine.getTextureManager().loadTextures(this.mBitmapTextureAtlas, this.mAutoParallaxBackgroundTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); final AutoParallaxBackground autoParallaxBackground = new AutoParallaxBackground(0, 0, 0, 5); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(0.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerBack.getHeight(), this.mParallaxLayerBack))); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-5.0f, new Sprite(0, 80, this.mParallaxLayerMid))); autoParallaxBackground.attachParallaxEntity(new ParallaxEntity(-10.0f, new Sprite(0, CAMERA_HEIGHT - this.mParallaxLayerFront.getHeight(), this.mParallaxLayerFront))); scene.setBackground(autoParallaxBackground); /* Calculate the coordinates for the face, so its centered on the camera. */ final int playerX = (CAMERA_WIDTH - this.mPlayerTextureRegion.getTileWidth()) / 2; final int playerY = CAMERA_HEIGHT - this.mPlayerTextureRegion.getTileHeight() - 5; /* Create two sprits and add it to the scene. */ final AnimatedSprite player = new AnimatedSprite(playerX, playerY, this.mPlayerTextureRegion); player.setScaleCenterY(this.mPlayerTextureRegion.getTileHeight()); player.setScale(2); player.animate(new long[]{200, 200, 200}, 3, 5, true); final AnimatedSprite enemy = new AnimatedSprite(playerX - 80, playerY, this.mEnemyTextureRegion); enemy.setScaleCenterY(this.mEnemyTextureRegion.getTileHeight()); enemy.setScale(2); enemy.animate(new long[]{200, 200, 200}, 3, 5, true); scene.attachChild(player); scene.attachChild(enemy); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import javax.microedition.khronos.opengles.GL10; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.scene.menu.MenuScene; import org.anddev.andengine.entity.scene.menu.MenuScene.IOnMenuItemClickListener; import org.anddev.andengine.entity.scene.menu.item.IMenuItem; import org.anddev.andengine.entity.scene.menu.item.SpriteMenuItem; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.view.KeyEvent; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 01:30:15 - 02.04.2010 */ public class MenuExample extends BaseExample implements IOnMenuItemClickListener { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; protected static final int MENU_RESET = 0; protected static final int MENU_QUIT = MENU_RESET + 1; // =========================================================== // Fields // =========================================================== protected Camera mCamera; protected Scene mMainScene; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; protected MenuScene mMenuScene; private BitmapTextureAtlas mMenuTexture; protected TextureRegion mMenuResetTextureRegion; protected TextureRegion mMenuQuitTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(64, 64, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box_menu.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); this.mMenuTexture = new BitmapTextureAtlas(256, 128, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mMenuResetTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "gfx/menu_reset.png", 0, 0); this.mMenuQuitTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mMenuTexture, this, "gfx/menu_quit.png", 0, 50); this.mEngine.getTextureManager().loadTexture(this.mMenuTexture); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); this.createMenuScene(); /* Just a simple scene with an animated face flying around. */ this.mMainScene = new Scene(); this.mMainScene.setBackground(new ColorBackground(0.09804f, 0.6274f, 0.8784f)); final Sprite face = new Sprite(0, 0, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); this.mMainScene.attachChild(face); return this.mMainScene; } @Override public void onLoadComplete() { } @Override public boolean onKeyDown(final int pKeyCode, final KeyEvent pEvent) { if(pKeyCode == KeyEvent.KEYCODE_MENU && pEvent.getAction() == KeyEvent.ACTION_DOWN) { if(this.mMainScene.hasChildScene()) { /* Remove the menu and reset it. */ this.mMenuScene.back(); } else { /* Attach the menu. */ this.mMainScene.setChildScene(this.mMenuScene, false, true, true); } return true; } else { return super.onKeyDown(pKeyCode, pEvent); } } @Override public boolean onMenuItemClicked(final MenuScene pMenuScene, final IMenuItem pMenuItem, final float pMenuItemLocalX, final float pMenuItemLocalY) { switch(pMenuItem.getID()) { case MENU_RESET: /* Restart the animation. */ this.mMainScene.reset(); /* Remove the menu and reset it. */ this.mMainScene.clearChildScene(); this.mMenuScene.reset(); return true; case MENU_QUIT: /* End Activity. */ this.finish(); return true; default: return false; } } // =========================================================== // Methods // =========================================================== protected void createMenuScene() { this.mMenuScene = new MenuScene(this.mCamera); final SpriteMenuItem resetMenuItem = new SpriteMenuItem(MENU_RESET, this.mMenuResetTextureRegion); resetMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(resetMenuItem); final SpriteMenuItem quitMenuItem = new SpriteMenuItem(MENU_QUIT, this.mMenuQuitTextureRegion); quitMenuItem.setBlendFunction(GL10.GL_SRC_ALPHA, GL10.GL_ONE_MINUS_SRC_ALPHA); this.mMenuScene.addMenuItem(quitMenuItem); this.mMenuScene.buildAnimations(); this.mMenuScene.setBackgroundEnabled(false); this.mMenuScene.setOnMenuItemClickListener(this); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples; import org.anddev.andengine.engine.Engine; import org.anddev.andengine.engine.camera.Camera; import org.anddev.andengine.engine.options.EngineOptions; import org.anddev.andengine.engine.options.EngineOptions.ScreenOrientation; import org.anddev.andengine.engine.options.resolutionpolicy.RatioResolutionPolicy; import org.anddev.andengine.entity.modifier.MoveModifier; import org.anddev.andengine.entity.scene.Scene; import org.anddev.andengine.entity.scene.background.ColorBackground; import org.anddev.andengine.entity.sprite.Sprite; import org.anddev.andengine.entity.util.FPSLogger; import org.anddev.andengine.extension.augmentedreality.BaseAugmentedRealityGameActivity; import org.anddev.andengine.opengl.texture.TextureOptions; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlas; import org.anddev.andengine.opengl.texture.atlas.bitmap.BitmapTextureAtlasTextureRegionFactory; import org.anddev.andengine.opengl.texture.region.TextureRegion; import android.widget.Toast; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga * * @author Nicolas Gramlich * @since 11:54:51 - 03.04.2010 */ public class AugmentedRealityExample extends BaseAugmentedRealityGameActivity { // =========================================================== // Constants // =========================================================== private static final int CAMERA_WIDTH = 720; private static final int CAMERA_HEIGHT = 480; // =========================================================== // Fields // =========================================================== private Camera mCamera; private BitmapTextureAtlas mBitmapTextureAtlas; private TextureRegion mFaceTextureRegion; // =========================================================== // Constructors // =========================================================== // =========================================================== // Getter & Setter // =========================================================== // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public Engine onLoadEngine() { Toast.makeText(this, "If you don't see a sprite moving over the screen, try starting this while already being in Landscape orientation!!", Toast.LENGTH_LONG).show(); this.mCamera = new Camera(0, 0, CAMERA_WIDTH, CAMERA_HEIGHT); return new Engine(new EngineOptions(true, ScreenOrientation.LANDSCAPE, new RatioResolutionPolicy(CAMERA_WIDTH, CAMERA_HEIGHT), this.mCamera)); } @Override public void onLoadResources() { this.mBitmapTextureAtlas = new BitmapTextureAtlas(32, 32, TextureOptions.BILINEAR_PREMULTIPLYALPHA); this.mFaceTextureRegion = BitmapTextureAtlasTextureRegionFactory.createFromAsset(this.mBitmapTextureAtlas, this, "gfx/face_box.png", 0, 0); this.mEngine.getTextureManager().loadTexture(this.mBitmapTextureAtlas); } @Override public Scene onLoadScene() { this.mEngine.registerUpdateHandler(new FPSLogger()); final Scene scene = new Scene(); // scene.setBackgroundEnabled(false); scene.setBackground(new ColorBackground(0.0f, 0.0f, 0.0f, 0.0f)); final int centerX = (CAMERA_WIDTH - this.mFaceTextureRegion.getWidth()) / 2; final int centerY = (CAMERA_HEIGHT - this.mFaceTextureRegion.getHeight()) / 2; final Sprite face = new Sprite(centerX, centerY, this.mFaceTextureRegion); face.registerEntityModifier(new MoveModifier(30, 0, CAMERA_WIDTH - face.getWidth(), 0, CAMERA_HEIGHT - face.getHeight())); scene.attachChild(face); return scene; } @Override public void onLoadComplete() { } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.client; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.client.ClientMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:52:27 - 28.02.2011 */ public class MovePaddleClientMessage extends ClientMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public float mY; // =========================================================== // Constructors // =========================================================== public MovePaddleClientMessage() { } public MovePaddleClientMessage(final int pID, final float pY) { this.mPaddleID = pID; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void setPaddleID(final int pPaddleID, final float pY) { this.mPaddleID = pPaddleID; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_CLIENT_MOVE_PADDLE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class UpdateBallServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public float mX; public float mY; // =========================================================== // Constructors // =========================================================== public UpdateBallServerMessage() { } public UpdateBallServerMessage(final float pX, final float pY) { this.mX = pX; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void set(final float pX,final float pY) { this.mX = pX; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_BALL; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class UpdatePaddleServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public float mX; public float mY; // =========================================================== // Constructors // =========================================================== public UpdatePaddleServerMessage() { } public UpdatePaddleServerMessage(final int pPaddleID, final float pX, final float pY) { this.mPaddleID = pPaddleID; this.mX = pX; this.mY = pY; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID, final float pX,final float pY) { this.mPaddleID = pPaddleID; this.mX = pX; this.mY = pY; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_PADDLE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mX = pDataInputStream.readFloat(); this.mY = pDataInputStream.readFloat(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeFloat(this.mX); pDataOutputStream.writeFloat(this.mY); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 19:48:32 - 28.02.2011 */ public class SetPaddleIDServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; // =========================================================== // Constructors // =========================================================== public SetPaddleIDServerMessage() { } public SetPaddleIDServerMessage(final int pPaddleID) { this.mPaddleID = pPaddleID; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID) { this.mPaddleID = pPaddleID; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_SET_PADDLEID; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java
package org.anddev.andengine.examples.game.pong.adt.messages.server; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import org.anddev.andengine.examples.game.pong.util.constants.PongConstants; import org.anddev.andengine.extension.multiplayer.protocol.adt.message.server.ServerMessage; /** * (c) 2010 Nicolas Gramlich * (c) 2011 Zynga Inc. * * @author Nicolas Gramlich * @since 02:02:12 - 01.03.2011 */ public class UpdateScoreServerMessage extends ServerMessage implements PongConstants { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== public int mPaddleID; public int mScore; // =========================================================== // Constructors // =========================================================== public UpdateScoreServerMessage() { } public UpdateScoreServerMessage(final int pPaddleID, final int pScore) { this.mPaddleID = pPaddleID; this.mScore = pScore; } // =========================================================== // Getter & Setter // =========================================================== public void set(final int pPaddleID, final int pScore) { this.mPaddleID = pPaddleID; this.mScore = pScore; } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== @Override public short getFlag() { return FLAG_MESSAGE_SERVER_UPDATE_SCORE; } @Override protected void onReadTransmissionData(DataInputStream pDataInputStream) throws IOException { this.mPaddleID = pDataInputStream.readInt(); this.mScore = pDataInputStream.readInt(); } @Override protected void onWriteTransmissionData(final DataOutputStream pDataOutputStream) throws IOException { pDataOutputStream.writeInt(this.mPaddleID); pDataOutputStream.writeInt(this.mScore); } // =========================================================== // Methods // =========================================================== // =========================================================== // Inner and Anonymous Classes // =========================================================== }
Java