code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.util; import java.io.IOException; import org.apache.http.nio.ContentEncoder; /** * Buffer for storing content to be streamed out to a {@link ContentEncoder}. * * @since 4.0 */ public interface ContentOutputBuffer { /** * Writes content from this buffer to the given {@link ContentEncoder}. * * @param encoder content encoder. * @return number of bytes written. * @throws IOException in case of an I/O error. */ int produceContent(ContentEncoder encoder) throws IOException; /** * Resets the buffer by clearing its state and stored content. */ void reset(); /** * @deprecated No longer used. */ @Deprecated void flush() throws IOException; /** * Writes <code>len</code> bytes from the specified byte array * starting at offset <code>off</code> to this 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>, this method can throw a runtime exception. The exact type * of runtime exception thrown by this method depends on implementation. * * @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 the specified byte to this buffer. * * @param b the <code>byte</code>. * @exception IOException if an I/O error occurs. */ void write(int b) throws IOException; /** * Indicates the content has been fully written. * @exception IOException if an I/O error occurs. */ void writeCompleted() throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentOutputBuffer.java
Java
gpl3
3,059
/* * ==================================================================== * 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.http.nio.util; import java.nio.ByteBuffer; /** * Allocates {@link ByteBuffer} instances using * {@link ByteBuffer#allocateDirect(int)}. * * @since 4.0 */ public class DirectByteBufferAllocator implements ByteBufferAllocator { public ByteBuffer allocate(int size) { return ByteBuffer.allocateDirect(size); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/DirectByteBufferAllocator.java
Java
gpl3
1,538
/* * ==================================================================== * 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.http.nio.util; import java.io.IOException; import java.io.InterruptedIOException; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; /** * Implementation of the {@link ContentOutputBuffer} interface that can be * shared by multiple threads, usually the I/O dispatch of an I/O reactor and * a worker thread. * <p> * The I/O dispatch thread is expected to transfer data from the buffer to * {@link ContentEncoder} by calling {@link #produceContent(ContentEncoder)}. * <p> * The worker thread is expected to write data to the buffer by calling * {@link #write(int)}, {@link #write(byte[], int, int)} or {@link #writeCompleted()} * <p> * In case of an abnormal situation or when no longer needed the buffer must be * shut down using {@link #shutdown()} method. * * @since 4.0 */ public class SharedOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer { private final IOControl ioctrl; private final ReentrantLock lock; private final Condition condition; private volatile boolean shutdown = false; private volatile boolean endOfStream = false; public SharedOutputBuffer(int buffersize, final IOControl ioctrl, final ByteBufferAllocator allocator) { super(buffersize, allocator); if (ioctrl == null) { throw new IllegalArgumentException("I/O content control may not be null"); } this.ioctrl = ioctrl; this.lock = new ReentrantLock(); this.condition = this.lock.newCondition(); } public void reset() { if (this.shutdown) { return; } this.lock.lock(); try { clear(); this.endOfStream = false; } finally { this.lock.unlock(); } } @Override public boolean hasData() { this.lock.lock(); try { return super.hasData(); } finally { this.lock.unlock(); } } @Override public int available() { this.lock.lock(); try { return super.available(); } finally { this.lock.unlock(); } } @Override public int capacity() { this.lock.lock(); try { return super.capacity(); } finally { this.lock.unlock(); } } @Override public int length() { this.lock.lock(); try { return super.length(); } finally { this.lock.unlock(); } } public int produceContent(final ContentEncoder encoder) throws IOException { if (this.shutdown) { return -1; } this.lock.lock(); try { setOutputMode(); int bytesWritten = 0; if (super.hasData()) { bytesWritten = encoder.write(this.buffer); if (encoder.isCompleted()) { this.endOfStream = true; } } if (!super.hasData()) { // No more buffered content // If at the end of the stream, terminate if (this.endOfStream && !encoder.isCompleted()) { encoder.complete(); } if (!this.endOfStream) { // suspend output events this.ioctrl.suspendOutput(); } } this.condition.signalAll(); return bytesWritten; } finally { this.lock.unlock(); } } public void close() { shutdown(); } public void shutdown() { if (this.shutdown) { return; } this.shutdown = true; this.lock.lock(); try { this.condition.signalAll(); } finally { this.lock.unlock(); } } public void write(final byte[] b, int off, int len) throws IOException { if (b == null) { return; } this.lock.lock(); try { if (this.shutdown || this.endOfStream) { throw new IllegalStateException("Buffer already closed for writing"); } setInputMode(); int remaining = len; while (remaining > 0) { if (!this.buffer.hasRemaining()) { flushContent(); setInputMode(); } int chunk = Math.min(remaining, this.buffer.remaining()); this.buffer.put(b, off, chunk); remaining -= chunk; off += chunk; } } finally { this.lock.unlock(); } } public void write(final byte[] b) throws IOException { if (b == null) { return; } write(b, 0, b.length); } public void write(int b) throws IOException { this.lock.lock(); try { if (this.shutdown || this.endOfStream) { throw new IllegalStateException("Buffer already closed for writing"); } setInputMode(); if (!this.buffer.hasRemaining()) { flushContent(); setInputMode(); } this.buffer.put((byte)b); } finally { this.lock.unlock(); } } public void flush() throws IOException { } private void flushContent() throws IOException { this.lock.lock(); try { try { while (super.hasData()) { if (this.shutdown) { throw new InterruptedIOException("Output operation aborted"); } this.ioctrl.requestOutput(); this.condition.await(); } } catch (InterruptedException ex) { throw new IOException("Interrupted while flushing the content buffer"); } } finally { this.lock.unlock(); } } public void writeCompleted() throws IOException { this.lock.lock(); try { if (this.endOfStream) { return; } this.endOfStream = true; this.ioctrl.requestOutput(); } finally { this.lock.unlock(); } } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/SharedOutputBuffer.java
Java
gpl3
7,676
/* * ==================================================================== * 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.http.nio.util; import java.nio.ByteBuffer; import org.apache.http.io.BufferInfo; /** * A buffer that expand its capacity on demand using {@link ByteBufferAllocator} * interface. Internally, this class is backed by an instance of * {@link ByteBuffer}. * <p> * This class is not thread safe. * * @since 4.0 */ @SuppressWarnings("deprecation") public class ExpandableBuffer implements BufferInfo, org.apache.http.nio.util.BufferInfo { public final static int INPUT_MODE = 0; public final static int OUTPUT_MODE = 1; private int mode; protected ByteBuffer buffer = null; private final ByteBufferAllocator allocator; /** * Allocates buffer of the given size using the given allocator. * * @param buffersize the buffer size. * @param allocator allocator to be used to allocate {@link ByteBuffer}s. */ public ExpandableBuffer(int buffersize, final ByteBufferAllocator allocator) { super(); if (allocator == null) { throw new IllegalArgumentException("ByteBuffer allocator may not be null"); } this.allocator = allocator; this.buffer = allocator.allocate(buffersize); this.mode = INPUT_MODE; } /** * Returns the current mode: * <p> * {@link #INPUT_MODE}: the buffer is in the input mode. * <p> * {@link #OUTPUT_MODE}: the buffer is in the output mode. * * @return current input/output mode. */ protected int getMode() { return this.mode; } /** * Sets output mode. The buffer can now be read from. */ protected void setOutputMode() { if (this.mode != OUTPUT_MODE) { this.buffer.flip(); this.mode = OUTPUT_MODE; } } /** * Sets input mode. The buffer can now be written into. */ protected void setInputMode() { if (this.mode != INPUT_MODE) { if (this.buffer.hasRemaining()) { this.buffer.compact(); } else { this.buffer.clear(); } this.mode = INPUT_MODE; } } private void expandCapacity(int capacity) { ByteBuffer oldbuffer = this.buffer; this.buffer = allocator.allocate(capacity); oldbuffer.flip(); this.buffer.put(oldbuffer); } /** * Expands buffer's capacity. */ protected void expand() { int newcapacity = (this.buffer.capacity() + 1) << 1; if (newcapacity < 0) { newcapacity = Integer.MAX_VALUE; } expandCapacity(newcapacity); } /** * Ensures the buffer can accommodate the required capacity. * * @param requiredCapacity */ protected void ensureCapacity(int requiredCapacity) { if (requiredCapacity > this.buffer.capacity()) { expandCapacity(requiredCapacity); } } /** * Returns the total capacity of this buffer. * * @return total capacity. */ public int capacity() { return this.buffer.capacity(); } /** * Determines if the buffer contains data. * * @return <code>true</code> if there is data in the buffer, * <code>false</code> otherwise. */ public boolean hasData() { setOutputMode(); return this.buffer.hasRemaining(); } /** * Returns the length of this buffer. * * @return buffer length. */ public int length() { setOutputMode(); return this.buffer.remaining(); } /** * Returns available capacity of this buffer. * * @return buffer length. */ public int available() { setInputMode(); return this.buffer.remaining(); } /** * Clears buffer. */ protected void clear() { this.buffer.clear(); this.mode = INPUT_MODE; } @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("[mode="); int mode = getMode(); if (mode == INPUT_MODE) { sb.append("in"); } else { sb.append("out"); } sb.append(" pos="); sb.append(this.buffer.position()); sb.append(" lim="); sb.append(this.buffer.limit()); sb.append(" cap="); sb.append(this.buffer.capacity()); sb.append("]"); return sb.toString(); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/ExpandableBuffer.java
Java
gpl3
5,640
/* * ==================================================================== * 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.http.nio.util; import java.nio.ByteBuffer; /** * Allocates {@link ByteBuffer} instances using * {@link ByteBuffer#allocate(int)}. * * @since 4.0 */ public class HeapByteBufferAllocator implements ByteBufferAllocator { public ByteBuffer allocate(int size) { return ByteBuffer.allocate(size); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/HeapByteBufferAllocator.java
Java
gpl3
1,524
/* * ==================================================================== * 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.http.nio.util; import java.io.IOException; import org.apache.http.nio.ContentDecoder; /** * Buffer for storing content streamed out from a {@link ContentDecoder}. * * @since 4.0 */ public interface ContentInputBuffer { /** * Reads content from the given {@link ContentDecoder} and stores it in * this buffer. * * @param decoder the content decoder. * @return number of bytes read. * @throws IOException in case of an I/O error. */ int consumeContent(ContentDecoder decoder) throws IOException; /** * Resets the buffer by clearing its state and stored content. */ void reset(); /** * Reads up to <code>len</code> bytes of data from this buffer into * an array of bytes. The exact number of bytes read depends how many bytes * are stored in the 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>, this method can throw a runtime exception. The exact type * of runtime exception thrown by this method depends on implementation. * This method returns <code>-1</code> if the end of content stream has been * reached. * * @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 one byte from this buffer. If the buffer is empty this method can * throw a runtime exception. The exact type of runtime exception thrown * by this method depends on implementation. This method returns * <code>-1</code> if the end of content stream has been reached. * * @return one byte */ int read() throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/ContentInputBuffer.java
Java
gpl3
3,413
/* * ==================================================================== * 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.http.nio.util; import java.io.IOException; import org.apache.http.nio.ContentEncoder; /** * Basic implementation of the {@link ContentOutputBuffer} interface. * <p> * This class is not thread safe. * * @since 4.0 */ public class SimpleOutputBuffer extends ExpandableBuffer implements ContentOutputBuffer { private boolean endOfStream; public SimpleOutputBuffer(int buffersize, final ByteBufferAllocator allocator) { super(buffersize, allocator); this.endOfStream = false; } public int produceContent(final ContentEncoder encoder) throws IOException { setOutputMode(); int bytesWritten = encoder.write(this.buffer); if (!hasData() && this.endOfStream) { encoder.complete(); } return bytesWritten; } public void write(final byte[] b, int off, int len) throws IOException { if (b == null) { return; } if (this.endOfStream) { return; } setInputMode(); ensureCapacity(this.buffer.position() + len); this.buffer.put(b, off, len); } public void write(final byte[] b) throws IOException { if (b == null) { return; } if (this.endOfStream) { return; } write(b, 0, b.length); } public void write(int b) throws IOException { if (this.endOfStream) { return; } setInputMode(); ensureCapacity(this.capacity() + 1); this.buffer.put((byte)b); } public void reset() { super.clear(); this.endOfStream = false; } public void flush() { } public void writeCompleted() { this.endOfStream = true; } public void shutdown() { this.endOfStream = true; } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/SimpleOutputBuffer.java
Java
gpl3
3,024
/* * ==================================================================== * 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.http.nio.util; /** * Basic buffer properties. * * @since 4.0 * * @deprecated Use {@link org.apache.http.io.BufferInfo} */ @Deprecated public interface BufferInfo { int length(); int capacity(); int available(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/util/BufferInfo.java
Java
gpl3
1,440
/* * ==================================================================== * 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.http.nio; import java.io.IOException; import org.apache.http.HttpException; import org.apache.http.HttpMessage; /** * Abstract HTTP message writer for non-blocking connections. * * @since 4.0 */ public interface NHttpMessageWriter<T extends HttpMessage> { /** * Resets the writer. The writer will be ready to start serializing another * HTTP message. */ void reset(); /** * Serializes out the HTTP message head. * * @param message HTTP message. * @throws IOException in case of an I/O error. * @throws HttpException in case the HTTP message is malformed or * violates the HTTP protocol. */ void write(T message) throws IOException, HttpException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpMessageWriter.java
Java
gpl3
1,930
/* * ==================================================================== * 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.http.nio; import java.io.IOException; import java.nio.channels.FileChannel; /** * A content decoder capable of transferring data directly to a {@link FileChannel} * * @since 4.0 */ public interface FileContentDecoder extends ContentDecoder { /** * Transfers a portion of entity content from the underlying network channel * into the given file channel.<br> * * <b>Warning</b>: Many implementations cannot write beyond the length of the file. * If the position exceeds the channel's size, some implementations * may throw an IOException. * * @param dst the target FileChannel to transfer data into. * @param position * The position within the file at which the transfer is to begin; * must be non-negative. * <b>Must be less than or equal to the size of the file</b> * @param count * The maximum number of bytes to be transferred; must be * non-negative * @throws IOException, if some I/O error occurs. * @return The number of bytes, possibly zero, * that were actually transferred */ long transfer(FileChannel dst, long position, long count) throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/FileContentDecoder.java
Java
gpl3
2,456
/* * ==================================================================== * 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.http.nio; import java.io.IOException; import java.nio.ByteBuffer; /** * Abstract HTTP content decoder. HTTP content decoders can be used * to read entity content from the underlying channel in small * chunks and apply the required coding transformation. * * @since 4.0 */ public interface ContentDecoder { /** * Reads a portion of content from the underlying channel * * @param dst The buffer into which entity content is to be transferred * @return The number of bytes read, possibly zero, or -1 if the * channel has reached end-of-stream * @throws IOException if I/O error occurs while reading content */ int read(ByteBuffer dst) throws IOException; /** * Returns <code>true</code> if the entity has been received in its * entirety. * * @return <code>true</code> if all the content has been consumed, * <code>false</code> otherwise. */ boolean isCompleted(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/ContentDecoder.java
Java
gpl3
2,159
/* * ==================================================================== * 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.http.nio; import java.io.IOException; import java.nio.channels.FileChannel; import org.apache.http.nio.ContentEncoder; /** * A content encoder capable of transferring data directly from a {@link FileChannel} * * @since 4.0 */ public interface FileContentEncoder extends ContentEncoder { /** * Transfers a portion of entity content from the given file channel * to the underlying network channel. * * @param src the source FileChannel to transfer data from. * @param position * The position within the file at which the transfer is to begin; * must be non-negative * @param count * The maximum number of bytes to be transferred; must be * non-negative *@throws IOException, if some I/O error occurs. * @return The number of bytes, possibly zero, * that were actually transferred */ long transfer(FileChannel src, long position, long count) throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/FileContentEncoder.java
Java
gpl3
2,196
/* * ==================================================================== * 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.http.nio; import org.apache.http.HttpConnection; import org.apache.http.HttpRequest; import org.apache.http.HttpResponse; import org.apache.http.protocol.HttpContext; /** * Abstract non-blocking HTTP connection interface. Each connection contains an * HTTP execution context, which can be used to maintain a processing state, * as well as the actual {@link HttpRequest} and {@link HttpResponse} that are * being transmitted over this connection. Both the request and * the response objects can be <code>null</code> if there is no incoming or * outgoing message currently being transferred. * <p> * Please note non-blocking HTTP connections are stateful and not thread safe. * Input / output operations on non-blocking HTTP connections should be * restricted to the dispatch events triggered by the I/O event dispatch thread. * However, the {@link IOControl} interface is fully threading safe and can be * manipulated from any thread. * * @since 4.0 */ public interface NHttpConnection extends HttpConnection, IOControl { public static final int ACTIVE = 0; public static final int CLOSING = 1; public static final int CLOSED = 2; /** * Returns status of the connection: * <p> * {@link #ACTIVE}: connection is active. * <p> * {@link #CLOSING}: connection is being closed. * <p> * {@link #CLOSED}: connection has been closed. * * @return connection status. */ int getStatus(); /** * Returns the current HTTP request if one is being received / transmitted. * Otherwise returns <code>null</code>. * * @return HTTP request, if available, <code>null</code> otherwise. */ HttpRequest getHttpRequest(); /** * Returns the current HTTP response if one is being received / transmitted. * Otherwise returns <tt>null</tt>. * * @return HTTP response, if available, <code>null</code> otherwise. */ HttpResponse getHttpResponse(); /** * Returns an HTTP execution context associated with this connection. * @return HTTP context */ HttpContext getContext(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpConnection.java
Java
gpl3
3,342
/* * ==================================================================== * 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.http.nio; import org.apache.http.nio.reactor.IOEventDispatch; /** * Extended version of the {@link NHttpClientConnection} used by * {@link IOEventDispatch} implementations to inform client-side connection * objects of I/O events. * * @since 4.0 */ public interface NHttpClientIOTarget extends NHttpClientConnection { /** * Triggered when the connection is ready to consume input. * * @param handler the client protocol handler. */ void consumeInput(NHttpClientHandler handler); /** * Triggered when the connection is ready to produce output. * * @param handler the client protocol handler. */ void produceOutput(NHttpClientHandler handler); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientIOTarget.java
Java
gpl3
1,914
/* * ==================================================================== * 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.http.nio; import java.io.IOException; import org.apache.http.HttpException; /** * Abstract client-side HTTP protocol handler. * * @since 4.0 */ public interface NHttpClientHandler { /** * Triggered when a new outgoing connection is created. * * @param conn new outgoing HTTP connection. * @param attachment an object that was attached to the session request */ void connected(NHttpClientConnection conn, Object attachment); /** * Triggered when the connection is ready to accept a new HTTP request. * The protocol handler does not have to submit a request if it is not * ready. * * @see NHttpClientConnection * * @param conn HTTP connection that is ready to accept a new HTTP request. */ void requestReady(NHttpClientConnection conn); /** * Triggered when an HTTP response is received. The connection * passed as a parameter to this method is guaranteed to return * a valid HTTP response object. * <p/> * If the response received encloses a response entity this method will * be followed by a series of * {@link #inputReady(NHttpClientConnection, ContentDecoder)} calls * to transfer the response content. * * @see NHttpClientConnection * * @param conn HTTP connection that contains an HTTP response */ void responseReceived(NHttpClientConnection conn); /** * Triggered when the underlying channel is ready for reading a * new portion of the response entity through the corresponding * content decoder. * <p/> * If the content consumer is unable to process the incoming content, * input event notifications can be temporarily suspended using * {@link IOControl} interface. * * @see NHttpClientConnection * @see ContentDecoder * @see IOControl * * @param conn HTTP connection that can produce a new portion of the * incoming response content. * @param decoder The content decoder to use to read content. */ void inputReady(NHttpClientConnection conn, ContentDecoder decoder); /** * Triggered when the underlying channel is ready for writing a next portion * of the request entity through the corresponding content encoder. * <p> * If the content producer is unable to generate the outgoing content, * output event notifications can be temporarily suspended using * {@link IOControl} interface. * * @see NHttpClientConnection * @see ContentEncoder * @see IOControl * * @param conn HTTP connection that can accommodate a new portion * of the outgoing request content. * @param encoder The content encoder to use to write content. */ void outputReady(NHttpClientConnection conn, ContentEncoder encoder); /** * Triggered when an I/O error occurs while reading from or writing * to the underlying channel. * * @param conn HTTP connection that caused an I/O error * @param ex I/O exception */ void exception(NHttpClientConnection conn, IOException ex); /** * Triggered when an HTTP protocol violation occurs while receiving * an HTTP response. * * @param conn HTTP connection that caused an HTTP protocol violation * @param ex HTTP protocol violation exception */ void exception(NHttpClientConnection conn, HttpException ex); /** * Triggered when no input is detected on this connection over the * maximum period of inactivity. * * @param conn HTTP connection that caused timeout condition. */ void timeout(NHttpClientConnection conn); /** * Triggered when the connection is closed. * * @param conn closed HTTP connection. */ void closed(NHttpClientConnection conn); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpClientHandler.java
Java
gpl3
5,045
<html> <head> <!-- /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ --> </head> <body> Representations for non-blocking HTTP message entities. An {@link org.apache.http.HttpEntity entity} is the optional content of a {@link org.apache.http.HttpMessage message}. This package provides a basic selection of entity implementations that can obtain content from {@link org.apache.http.nio.entity.NByteArrayEntity byte array}, {@link org.apache.http.nio.entity.NStringEntity string}, {@link org.apache.http.nio.entity.NFileEntity file}, or through an {@link org.apache.http.nio.entity.NHttpEntityWrapper compatibility adaptor} for blocking HTTP entities. If a message is received from an open non-blocking connection, usually it is represented by {@link org.apache.http.nio.entity.ConsumingNHttpEntity consuming} entity. </body> </html>
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/package.html
HTML
gpl3
1,967
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import java.io.InputStream; import org.apache.http.io.BufferInfo; import org.apache.http.nio.util.ContentInputBuffer; /** * {@link InputStream} adaptor for {@link ContentInputBuffer}. * * @since 4.0 */ public class ContentInputStream extends InputStream { private final ContentInputBuffer buffer; public ContentInputStream(final ContentInputBuffer buffer) { super(); if (buffer == null) { throw new IllegalArgumentException("Input buffer may not be null"); } this.buffer = buffer; } @Override public int available() throws IOException { if (this.buffer instanceof BufferInfo) { return ((BufferInfo) this.buffer).length(); } else { return super.available(); } } @Override public int read(final byte[] b, int off, int len) throws IOException { return this.buffer.read(b, off, len); } @Override public int read(final byte[] b) throws IOException { if (b == null) { return 0; } return this.buffer.read(b, 0, b.length); } @Override public int read() throws IOException { return this.buffer.read(); } @Override public void close() throws IOException { // read and discard the remainder of the message byte tmp[] = new byte[1024]; while (this.buffer.read(tmp, 0, tmp.length) >= 0) { } super.close(); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentInputStream.java
Java
gpl3
2,717
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.entity; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpEntity; import org.apache.http.entity.StringEntity; /** * An entity whose content is retrieved from a string. In addition to the * standard {@link HttpEntity} interface this class also implements NIO specific * {@link HttpNIOEntity}. * * @deprecated Use {@link NStringEntity} * * @since 4.0 */ @Deprecated public class StringNIOEntity extends StringEntity implements HttpNIOEntity { public StringNIOEntity( final String s, String charset) throws UnsupportedEncodingException { super(s, charset); } public ReadableByteChannel getChannel() throws IOException { return Channels.newChannel(getContent()); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/StringNIOEntity.java
Java
gpl3
2,077
/* * ==================================================================== * 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.http.nio.entity; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.channels.FileChannel; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.ContentEncoderChannel; import org.apache.http.nio.FileContentEncoder; import org.apache.http.nio.IOControl; /** * A self contained, repeatable non-blocking entity that retrieves its content * from a file. This class is mostly used to stream large files of different * types, so one needs to supply the content type of the file to make sure * the content can be correctly recognized and processed by the recipient. * * @since 4.0 */ public class NFileEntity extends AbstractHttpEntity implements ProducingNHttpEntity { private final File file; private FileChannel fileChannel; private long idx = -1; private boolean useFileChannels; /** * Creates new instance of NFileEntity from the given source {@link File} * with the given content type. If <code>useFileChannels</code> is set to * <code>true</code>, the entity will try to use {@link FileContentEncoder} * interface to stream file content directly from the file channel. * * @param file the source file. * @param contentType the content type of the file. * @param useFileChannels flag whether the direct transfer from the file * channel should be attempted. */ public NFileEntity(final File file, final String contentType, boolean useFileChannels) { if (file == null) { throw new IllegalArgumentException("File may not be null"); } this.file = file; this.useFileChannels = useFileChannels; setContentType(contentType); } public NFileEntity(final File file, final String contentType) { this(file, contentType, true); } public void finish() { try { if(fileChannel != null) fileChannel.close(); } catch(IOException ignored) {} fileChannel = null; } public long getContentLength() { return file.length(); } public boolean isRepeatable() { return true; } public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException { if(fileChannel == null) { FileInputStream in = new FileInputStream(file); fileChannel = in.getChannel(); idx = 0; } long transferred; if(useFileChannels && encoder instanceof FileContentEncoder) { transferred = ((FileContentEncoder)encoder) .transfer(fileChannel, idx, Long.MAX_VALUE); } else { transferred = fileChannel. transferTo(idx, Long.MAX_VALUE, new ContentEncoderChannel(encoder)); } if(transferred > 0) idx += transferred; if(idx >= fileChannel.size()) encoder.complete(); } public boolean isStreaming() { return false; } public InputStream getContent() throws IOException { return new FileInputStream(this.file); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = new FileInputStream(this.file); try { byte[] tmp = new byte[4096]; int l; while ((l = instream.read(tmp)) != -1) { outstream.write(tmp, 0, l); } outstream.flush(); } finally { instream.close(); } } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NFileEntity.java
Java
gpl3
4,978
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.entity; import java.io.IOException; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpEntity; import org.apache.http.entity.ByteArrayEntity; /** * An entity whose content is retrieved from a byte array. In addition to the * standard {@link HttpEntity} interface this class also implements NIO specific * {@link HttpNIOEntity}. * * @deprecated Use {@link NByteArrayEntity} * * @since 4.0 */ @Deprecated public class ByteArrayNIOEntity extends ByteArrayEntity implements HttpNIOEntity { public ByteArrayNIOEntity(final byte[] b) { super(b); } public ReadableByteChannel getChannel() throws IOException { return Channels.newChannel(getContent()); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ByteArrayNIOEntity.java
Java
gpl3
1,965
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.util.ByteBufferAllocator; import org.apache.http.nio.util.SimpleInputBuffer; /** * A {@link ConsumingNHttpEntity} that consumes content into a buffer. The * content can be retrieved as an InputStream via * {@link HttpEntity#getContent()}, or written to an output stream via * {@link HttpEntity#writeTo(OutputStream)}. * * @since 4.0 */ public class BufferingNHttpEntity extends HttpEntityWrapper implements ConsumingNHttpEntity { private final static int BUFFER_SIZE = 2048; private final SimpleInputBuffer buffer; private boolean finished; private boolean consumed; public BufferingNHttpEntity( final HttpEntity httpEntity, final ByteBufferAllocator allocator) { super(httpEntity); this.buffer = new SimpleInputBuffer(BUFFER_SIZE, allocator); } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { this.buffer.consumeContent(decoder); if (decoder.isCompleted()) { this.finished = true; } } public void finish() { this.finished = true; } @Override public void consumeContent() throws IOException { } /** * Obtains entity's content as {@link InputStream}. * * @throws IllegalStateException if content of the entity has not been * fully received or has already been consumed. */ @Override public InputStream getContent() throws IOException { if (!this.finished) { throw new IllegalStateException("Entity content has not been fully received"); } if (this.consumed) { throw new IllegalStateException("Entity content has been consumed"); } this.consumed = true; return new ContentInputStream(this.buffer); } @Override public boolean isRepeatable() { return false; } @Override public boolean isStreaming() { return true; } @Override public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } InputStream instream = getContent(); byte[] buffer = new byte[BUFFER_SIZE]; int l; // consume until EOF while ((l = instream.read(buffer)) != -1) { outstream.write(buffer, 0, l); } } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/BufferingNHttpEntity.java
Java
gpl3
3,973
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; /** * A non-blocking {@link HttpEntity} that allows content to be streamed from a * {@link ContentDecoder}. * * @since 4.0 */ public interface ConsumingNHttpEntity extends HttpEntity { /** * Notification that content is available to be read from the decoder. * {@link IOControl} instance passed as a parameter to the method can be * used to suspend input events if the entity is temporarily unable to * allocate more storage to accommodate all incoming content. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. */ void consumeContent(ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Notification that any resources allocated for reading can be released. */ void finish() throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ConsumingNHttpEntity.java
Java
gpl3
2,199
/* * ==================================================================== * 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.http.nio.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.protocol.AsyncNHttpServiceHandler; import org.apache.http.protocol.HTTP; /** * A simple, self contained, repeatable non-blocking entity that retrieves * its content from a {@link String} object. * * @see AsyncNHttpServiceHandler * @since 4.0 * */ public class NStringEntity extends AbstractHttpEntity implements ProducingNHttpEntity { protected final byte[] content; protected final ByteBuffer buffer; public NStringEntity(final String s, String charset) throws UnsupportedEncodingException { if (s == null) { throw new IllegalArgumentException("Source string may not be null"); } if (charset == null) { charset = HTTP.DEFAULT_CONTENT_CHARSET; } this.content = s.getBytes(charset); this.buffer = ByteBuffer.wrap(this.content); setContentType(HTTP.PLAIN_TEXT_TYPE + HTTP.CHARSET_PARAM + charset); } public NStringEntity(final String s) throws UnsupportedEncodingException { this(s, null); } public boolean isRepeatable() { return true; } public long getContentLength() { return this.buffer.limit(); } public void finish() { buffer.rewind(); } public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException { encoder.write(buffer); if(!buffer.hasRemaining()) encoder.complete(); } public boolean isStreaming() { return false; } public InputStream getContent() { return new ByteArrayInputStream(content); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } outstream.write(content); outstream.flush(); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NStringEntity.java
Java
gpl3
3,444
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; /** * A listener for available data on a non-blocking {@link ConsumingNHttpEntity}. * * @since 4.0 */ public interface ContentListener { /** * Notification that content is available to be read from the decoder. * * @param decoder content decoder. * @param ioctrl I/O control of the underlying connection. */ void contentAvailable(ContentDecoder decoder, IOControl ioctrl) throws IOException; /** * Notification that any resources allocated for reading can be released. */ void finished(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentListener.java
Java
gpl3
1,890
/* * ==================================================================== * 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.http.nio.entity; import org.apache.http.Header; import org.apache.http.HttpEntity; import org.apache.http.entity.BasicHttpEntity; import org.apache.http.nio.util.ContentInputBuffer; /** * HTTP entity wrapper whose content is provided by a * {@link ContentInputBuffer}. * * @since 4.0 */ public class ContentBufferEntity extends BasicHttpEntity { private HttpEntity wrappedEntity; /** * Creates new instance of ContentBufferEntity. * * @param entity the original entity. * @param buffer the content buffer. */ public ContentBufferEntity(final HttpEntity entity, final ContentInputBuffer buffer) { super(); if (entity == null) { throw new IllegalArgumentException("HTTP entity may not be null"); } this.wrappedEntity = entity; setContent(new ContentInputStream(buffer)); } @Override public boolean isChunked() { return this.wrappedEntity.isChunked(); } @Override public long getContentLength() { return this.wrappedEntity.getContentLength(); } @Override public Header getContentType() { return this.wrappedEntity.getContentType(); } @Override public Header getContentEncoding() { return this.wrappedEntity.getContentEncoding(); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentBufferEntity.java
Java
gpl3
2,521
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import java.nio.ByteBuffer; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.util.ByteBufferAllocator; /** * A simple {@link ContentListener} that reads and ignores all content. * * @since 4.0 */ public class SkipContentListener implements ContentListener { private final ByteBuffer buffer; public SkipContentListener(final ByteBufferAllocator allocator) { super(); if (allocator == null) { throw new IllegalArgumentException("ByteBuffer allocator may not be null"); } this.buffer = allocator.allocate(2048); } public void contentAvailable( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { int totalRead = 0; int lastRead; do { buffer.clear(); lastRead = decoder.read(buffer); if (lastRead > 0) totalRead += lastRead; } while (lastRead > 0); } public void finished() { } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/SkipContentListener.java
Java
gpl3
2,299
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import java.io.OutputStream; import org.apache.http.nio.util.ContentOutputBuffer; /** * {@link OutputStream} adaptor for {@link ContentOutputBuffer}. * * @since 4.0 */ public class ContentOutputStream extends OutputStream { private final ContentOutputBuffer buffer; public ContentOutputStream(final ContentOutputBuffer buffer) { super(); if (buffer == null) { throw new IllegalArgumentException("Output buffer may not be null"); } this.buffer = buffer; } @Override public void close() throws IOException { this.buffer.writeCompleted(); } @Override public void flush() throws IOException { } @Override public void write(byte[] b, int off, int len) throws IOException { this.buffer.write(b, off, len); } @Override public void write(byte[] b) throws IOException { if (b == null) { return; } this.buffer.write(b, 0, b.length); } @Override public void write(int b) throws IOException { this.buffer.write(b); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ContentOutputStream.java
Java
gpl3
2,347
/* * ==================================================================== * 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.http.nio.entity; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpEntity; import org.apache.http.entity.FileEntity; /** * An entity whose content is retrieved from from a file. In addition to the standard * {@link HttpEntity} interface this class also implements NIO specific * {@link HttpNIOEntity}. * * @deprecated Use {@link NFileEntity} * * @since 4.0 */ @Deprecated public class FileNIOEntity extends FileEntity implements HttpNIOEntity { public FileNIOEntity(final File file, final String contentType) { super(file, contentType); } public ReadableByteChannel getChannel() throws IOException { RandomAccessFile rafile = new RandomAccessFile(this.file, "r"); return rafile.getChannel(); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/FileNIOEntity.java
Java
gpl3
2,059
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import org.apache.http.HttpEntity; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; /** * An {@link HttpEntity} that can stream content out into a * {@link ContentEncoder}. * * @since 4.0 */ public interface ProducingNHttpEntity extends HttpEntity { /** * Notification that content should be written to the encoder. * {@link IOControl} instance passed as a parameter to the method can be * used to suspend output events if the entity is temporarily unable to * produce more content. * <p> * When all content is finished, this <b>MUST</b> call {@link ContentEncoder#complete()}. * Failure to do so could result in the entity never being written. * * @param encoder content encoder. * @param ioctrl I/O control of the underlying connection. */ void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException; /** * Notification that any resources allocated for writing can be released. */ void finish() throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ProducingNHttpEntity.java
Java
gpl3
2,313
/* * ==================================================================== * 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.http.nio.entity; import java.io.ByteArrayInputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import org.apache.http.entity.AbstractHttpEntity; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; import org.apache.http.nio.protocol.AsyncNHttpServiceHandler; /** * A simple self contained, repeatable non-blocking entity that retrieves * its content from a byte array. * * @see AsyncNHttpServiceHandler * @since 4.0 */ public class NByteArrayEntity extends AbstractHttpEntity implements ProducingNHttpEntity { protected final byte[] content; protected final ByteBuffer buffer; public NByteArrayEntity(final byte[] b) { this.content = b; this.buffer = ByteBuffer.wrap(b); } public void finish() { buffer.rewind(); } public void produceContent(ContentEncoder encoder, IOControl ioctrl) throws IOException { encoder.write(buffer); if(!buffer.hasRemaining()) encoder.complete(); } public long getContentLength() { return buffer.limit(); } public boolean isRepeatable() { return true; } public boolean isStreaming() { return false; } public InputStream getContent() { return new ByteArrayInputStream(content); } public void writeTo(final OutputStream outstream) throws IOException { if (outstream == null) { throw new IllegalArgumentException("Output stream may not be null"); } outstream.write(content); outstream.flush(); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NByteArrayEntity.java
Java
gpl3
2,863
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.Channels; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.nio.ContentEncoder; import org.apache.http.nio.IOControl; /** * {@link ProducingNHttpEntity} compatibility adaptor for blocking HTTP * entities. * * @since 4.0 */ public class NHttpEntityWrapper extends HttpEntityWrapper implements ProducingNHttpEntity { private final ReadableByteChannel channel; private final ByteBuffer buffer; public NHttpEntityWrapper(final HttpEntity httpEntity) throws IOException { super(httpEntity); this.channel = Channels.newChannel(httpEntity.getContent()); this.buffer = ByteBuffer.allocate(4096); } /** * This method throws {@link UnsupportedOperationException}. */ @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } @Override public boolean isStreaming() { return true; } /** * This method throws {@link UnsupportedOperationException}. */ @Override public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } /** * This method is equivalent to the {@link #finish()} method. * <br/> * TODO: The name of this method is misnomer. It will be renamed to * #finish() in the next major release. */ @Override public void consumeContent() throws IOException { finish(); } public void produceContent( final ContentEncoder encoder, final IOControl ioctrl) throws IOException { int i = this.channel.read(this.buffer); this.buffer.flip(); encoder.write(this.buffer); boolean buffering = this.buffer.hasRemaining(); this.buffer.compact(); if (i == -1 && !buffering) { encoder.complete(); this.channel.close(); } } public void finish() { try { this.channel.close(); } catch (IOException ignore) { } } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/NHttpEntityWrapper.java
Java
gpl3
3,629
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import org.apache.http.HttpEntity; import org.apache.http.entity.HttpEntityWrapper; import org.apache.http.nio.ContentDecoder; import org.apache.http.nio.IOControl; /** * A {@link ConsumingNHttpEntity} that forwards available content to a * {@link ContentListener}. * * @since 4.0 */ public class ConsumingNHttpEntityTemplate extends HttpEntityWrapper implements ConsumingNHttpEntity { private final ContentListener contentListener; public ConsumingNHttpEntityTemplate( final HttpEntity httpEntity, final ContentListener contentListener) { super(httpEntity); this.contentListener = contentListener; } public ContentListener getContentListener() { return contentListener; } @Override public InputStream getContent() throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } @Override public boolean isStreaming() { return true; } @Override public void writeTo(OutputStream out) throws IOException, UnsupportedOperationException { throw new UnsupportedOperationException("Does not support blocking methods"); } /** * This method is equivalent to the {@link #finish()} method. * <br/> * TODO: The name of this method is misnomer. It will be renamed to * #finish() in the next major release. */ @Override public void consumeContent() throws IOException { finish(); } public void consumeContent( final ContentDecoder decoder, final IOControl ioctrl) throws IOException { this.contentListener.contentAvailable(decoder, ioctrl); } public void finish() { this.contentListener.finished(); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/ConsumingNHttpEntityTemplate.java
Java
gpl3
3,119
/* * ==================================================================== * 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.http.nio.entity; import java.io.IOException; import java.nio.channels.ReadableByteChannel; import org.apache.http.HttpEntity; /** * @deprecated Use {@link ProducingNHttpEntity} * * @since 4.0 */ @Deprecated public interface HttpNIOEntity extends HttpEntity { ReadableByteChannel getChannel() throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/entity/HttpNIOEntity.java
Java
gpl3
1,532
/* * ==================================================================== * 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.http.nio; import java.io.IOException; import org.apache.http.HttpException; /** * Abstract server-side HTTP protocol handler. * * @since 4.0 */ public interface NHttpServiceHandler { /** * Triggered when a new incoming connection is created. * * @param conn new incoming connection HTTP connection. */ void connected(NHttpServerConnection conn); /** * Triggered when a new HTTP request is received. The connection * passed as a parameter to this method is guaranteed to return * a valid HTTP request object. * <p/> * If the request received encloses a request entity this method will * be followed a series of * {@link #inputReady(NHttpServerConnection, ContentDecoder)} calls * to transfer the request content. * * @see NHttpServerConnection * * @param conn HTTP connection that contains a new HTTP request */ void requestReceived(NHttpServerConnection conn); /** * Triggered when the underlying channel is ready for reading a * new portion of the request entity through the corresponding * content decoder. * <p/> * If the content consumer is unable to process the incoming content, * input event notifications can be temporarily suspended using * {@link IOControl} interface. * * @see NHttpServerConnection * @see ContentDecoder * @see IOControl * * @param conn HTTP connection that can produce a new portion of the * incoming request content. * @param decoder The content decoder to use to read content. */ void inputReady(NHttpServerConnection conn, ContentDecoder decoder); /** * Triggered when the connection is ready to accept a new HTTP response. * The protocol handler does not have to submit a response if it is not * ready. * * @see NHttpServerConnection * * @param conn HTTP connection that contains an HTTP response */ void responseReady(NHttpServerConnection conn); /** * Triggered when the underlying channel is ready for writing a * next portion of the response entity through the corresponding * content encoder. * <p/> * If the content producer is unable to generate the outgoing content, * output event notifications can be temporarily suspended using * {@link IOControl} interface. * * @see NHttpServerConnection * @see ContentEncoder * @see IOControl * * @param conn HTTP connection that can accommodate a new portion * of the outgoing response content. * @param encoder The content encoder to use to write content. */ void outputReady(NHttpServerConnection conn, ContentEncoder encoder); /** * Triggered when an I/O error occurs while reading from or writing * to the underlying channel. * * @param conn HTTP connection that caused an I/O error * @param ex I/O exception */ void exception(NHttpServerConnection conn, IOException ex); /** * Triggered when an HTTP protocol violation occurs while receiving * an HTTP request. * * @param conn HTTP connection that caused an HTTP protocol violation * @param ex HTTP protocol violation exception */ void exception(NHttpServerConnection conn, HttpException ex); /** * Triggered when no input is detected on this connection over the * maximum period of inactivity. * * @param conn HTTP connection that caused timeout condition. */ void timeout(NHttpServerConnection conn); /** * Triggered when the connection is closed. * * @param conn closed HTTP connection. */ void closed(NHttpServerConnection conn); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServiceHandler.java
Java
gpl3
4,955
/* * ==================================================================== * 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.http.nio; import org.apache.http.nio.reactor.IOEventDispatch; /** * Extended version of the {@link NHttpServerConnection} used by * {@link IOEventDispatch} implementations to inform server-side connection * objects of I/O events. * * @since 4.0 */ public interface NHttpServerIOTarget extends NHttpServerConnection { /** * Triggered when the connection is ready to consume input. * * @param handler the server protocol handler. */ void consumeInput(NHttpServiceHandler handler); /** * Triggered when the connection is ready to produce output. * * @param handler the server protocol handler. */ void produceOutput(NHttpServiceHandler handler); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/NHttpServerIOTarget.java
Java
gpl3
1,916
/* * ==================================================================== * 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.http.nio.reactor; import java.nio.channels.SelectionKey; /** * Type of I/O event notifications I/O sessions can declare interest in. * * @since 4.0 */ public interface EventMask { /** * Interest in data input. */ public static final int READ = SelectionKey.OP_READ; /** * Interest in data output. */ public static final int WRITE = SelectionKey.OP_WRITE; /** * Interest in data input/output. */ public static final int READ_WRITE = READ | WRITE; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/EventMask.java
Java
gpl3
1,716
<html> <head> <!-- /* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ --> </head> <body> API for event driven NIO based on <a href="http://gee.cs.oswego.edu/dl/">Doug Lea</a>'s <a href="http://gee.cs.oswego.edu/dl/cpjslides/nio.pdf">reactor pattern</a>. This API is not specific to HTTP communication. However, it is minimal in the sense that it defines only what is required within the scope of HTTP components. </body> </html>
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/package.html
HTML
gpl3
1,562
/* * ==================================================================== * 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.http.nio.reactor; import java.net.SocketAddress; import java.nio.channels.ByteChannel; /** * IOSession interface represents a sequence of logically related data exchanges * between two end points. * <p> * The channel associated with implementations of this interface can be used to * read data from and write data to the session. * <p> * I/O sessions are not bound to an execution thread, therefore one cannot use * the context of the thread to store a session's state. All details about * a particular session must be stored within the session itself, usually * using execution context associated with it. * <p> * Implementations of this interface are expected to be threading safe. * * @since 4.0 */ public interface IOSession { /** * Name of the context attribute key, which can be used to obtain the * session attachment object. */ public static final String ATTACHMENT_KEY = "http.session.attachment"; public static final int ACTIVE = 0; public static final int CLOSING = 1; public static final int CLOSED = Integer.MAX_VALUE; /** * Returns the underlying I/O channel associated with this session. * * @return the I/O channel. */ ByteChannel channel(); /** * Returns address of the remote peer. * * @return socket address. */ SocketAddress getRemoteAddress(); /** * Returns local address. * * @return socket address. */ SocketAddress getLocalAddress(); /** * Returns mask of I/O evens this session declared interest in. * * @return I/O event mask. */ int getEventMask(); /** * Declares interest in I/O event notifications by setting the event mask * associated with the session * * @param ops new I/O event mask. */ void setEventMask(int ops); /** * Declares interest in a particular I/O event type by updating the event * mask associated with the session. * * @param op I/O event type. */ void setEvent(int op); /** * Clears interest in a particular I/O event type by updating the event * mask associated with the session. * * @param op I/O event type. */ void clearEvent(int op); /** * Terminates the session gracefully and closes the underlying I/O channel. * This method ensures that session termination handshake, such as the one * used by the SSL/TLS protocol, is correctly carried out. */ void close(); /** * Terminates the session by shutting down the underlying I/O channel. */ void shutdown(); /** * Returns status of the session: * <p> * {@link #ACTIVE}: session is active. * <p> * {@link #CLOSING}: session is being closed. * <p> * {@link #CLOSED}: session has been terminated. * * @return session status. */ int getStatus(); /** * Determines if the session has been terminated. * * @return <code>true</code> if the session has been terminated, * <code>false</code> otherwise. */ boolean isClosed(); /** * Returns value of the socket timeout in milliseconds. The value of * <code>0</code> signifies the session cannot time out. * * @return socket timeout. */ int getSocketTimeout(); /** * Sets value of the socket timeout in milliseconds. The value of * <code>0</code> signifies the session cannot time out. * * @param timeout socket timeout. */ void setSocketTimeout(int timeout); /** * Quite often I/O sessions need to maintain internal I/O buffers in order * to transform input / output data prior to returning it to the consumer or * writing it to the underlying channel. Memory management in HttpCore NIO * is based on the fundamental principle that the data consumer can read * only as much input data as it can process without having to allocate more * memory. That means, quite often some input data may remain unread in one * of the internal or external session buffers. The I/O reactor can query * the status of these session buffers, and make sure the consumer gets * notified correctly as more data gets stored in one of the session * buffers, thus allowing the consumer to read the remaining data once it * is able to process it * <p> * I/O sessions can be made aware of the status of external session buffers * using the {@link SessionBufferStatus} interface. * * @param status */ void setBufferStatus(SessionBufferStatus status); /** * Determines if the input buffer associated with the session contains data. * * @return <code>true</code> if the session input buffer contains data, * <code>false</code> otherwise. */ boolean hasBufferedInput(); /** * Determines if the output buffer associated with the session contains * data. * * @return <code>true</code> if the session output buffer contains data, * <code>false</code> otherwise. */ boolean hasBufferedOutput(); /** * This method can be used to associate a particular object with the * session by the given attribute name. * <p> * I/O sessions are not bound to an execution thread, therefore one cannot * use the context of the thread to store a session's state. All details * about a particular session must be stored within the session itself. * * @param name name of the attribute. * @param obj value of the attribute. */ void setAttribute(String name, Object obj); /** * Returns the value of the attribute with the given name. The value can be * <code>null</code> if not set. * <p> * The value of the session attachment object can be obtained using * {@link #ATTACHMENT_KEY} name. * * @see #setAttribute(String, Object) * * @param name name of the attribute. * @return value of the attribute. */ Object getAttribute(String name); /** * Removes attribute with the given name. * * @see #setAttribute(String, Object) * * @param name name of the attribute to be removed. * @return value of the removed attribute. */ Object removeAttribute(String name); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOSession.java
Java
gpl3
7,585
/* * ==================================================================== * 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.http.nio.reactor; /** * SessionRequestCallback interface can be used to get notifications of * completion of session requests asynchronously without having to wait * for it, blocking the current thread of execution. * * @since 4.0 */ public interface SessionRequestCallback { /** * Triggered on successful completion of a {@link SessionRequest}. * The {@link SessionRequest#getSession()} method can now be used to obtain * the new I/O session. * * @param request session request. */ void completed(SessionRequest request); /** * Triggered on unsuccessful completion a {@link SessionRequest}. * The {@link SessionRequest#getException()} method can now be used to * obtain the cause of the error. * * @param request session request. */ void failed(SessionRequest request); /** * Triggered if a {@link SessionRequest} times out. * * @param request session request. */ void timeout(SessionRequest request); /** * Triggered on cancellation of a {@link SessionRequest}. * * @param request session request. */ void cancelled(SessionRequest request); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequestCallback.java
Java
gpl3
2,393
/* * ==================================================================== * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. * ==================================================================== * * This software consists of voluntary contributions made by many * individuals on behalf of the Apache Software Foundation. For more * information on the Apache Software Foundation, please see * <http://www.apache.org/>. * */ package org.apache.http.nio.reactor; import java.io.IOException; /** * HttpCore NIO is based on the Reactor pattern as described by Doug Lea. * The purpose of I/O reactors is to react to I/O events and to dispatch event * notifications to individual I/O sessions. The main idea of I/O reactor * pattern is to break away from the one thread per connection model imposed * by the classic blocking I/O model. * <p> * The IOReactor interface represents an abstract object implementing * the Reactor pattern. * <p> * I/O reactors usually employ a small number of dispatch threads (often as * few as one) to dispatch I/O event notifications to a much greater number * (often as many as several thousands) of I/O sessions or connections. It is * generally recommended to have one dispatch thread per CPU core. * * @since 4.0 */ public interface IOReactor { /** * Returns the current status of the reactor. * * @return reactor status. */ IOReactorStatus getStatus(); /** * Starts the reactor and initiates the dispatch of I/O event notifications * to the given {@link IOEventDispatch}. * * @param eventDispatch the I/O event dispatch. * @throws IOException in case of an I/O error. */ void execute(IOEventDispatch eventDispatch) throws IOException; /** * Initiates shutdown of the reactor and blocks approximately for the given * period of time in milliseconds waiting for the reactor to terminate all * active connections, to shut down itself and to release system resources * it currently holds. * * @param waitMs wait time in milliseconds. * @throws IOException in case of an I/O error. */ void shutdown(long waitMs) throws IOException; /** * Initiates shutdown of the reactor and blocks for a default period of * time waiting for the reactor to terminate all active connections, to shut * down itself and to release system resources it currently holds. It is * up to individual implementations to decide for how long this method can * remain blocked. * * @throws IOException in case of an I/O error. */ void shutdown() throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactor.java
Java
gpl3
3,431
/* * ==================================================================== * 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.http.nio.reactor; /** * IOReactorStatus represents an internal status of an I/O reactor. * * @since 4.0 */ public enum IOReactorStatus { /** * The reactor is inactive / has not been started */ INACTIVE, /** * The reactor is active / processing I/O events. */ ACTIVE, /** * Shutdown of the reactor has been requested. */ SHUTDOWN_REQUEST, /** * The reactor is shutting down. */ SHUTTING_DOWN, /** * The reactor has shut down. */ SHUT_DOWN; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorStatus.java
Java
gpl3
1,746
/* * ==================================================================== * 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.http.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import org.apache.http.util.CharArrayBuffer; /** * Session input buffer for non-blocking connections. This interface facilitates * intermediate buffering of input data streamed from a source channel and * reading buffered data to a destination, usually {@link ByteBuffer} or * {@link WritableByteChannel}. This interface also provides methods for reading * lines of text. * * @since 4.0 */ public interface SessionInputBuffer { /** * Determines if the buffer contains data. * * @return <code>true</code> if there is data in the buffer, * <code>false</code> otherwise. */ boolean hasData(); /** * Returns the length of this buffer. * * @return buffer length. */ int length(); /** * Makes an attempt to fill the buffer with data from the given * {@link ReadableByteChannel}. * * @param src the source channel * @return The number of bytes read, possibly zero, or <tt>-1</tt> if the * channel has reached end-of-stream. * @throws IOException in case of an I/O error. */ int fill(ReadableByteChannel src) throws IOException; /** * Reads one byte from the buffer. If the buffer is empty this method can * throw a runtime exception. The exact type of runtime exception thrown * by this method depends on implementation. * * @return one byte */ int read(); /** * Reads a sequence of bytes from this buffer into the destination buffer, * up to the given maximum limit. The exact number of bytes transferred * depends on availability of data in this buffer and capacity of the * destination buffer, but cannot be more than <code>maxLen</code> value. * * @param dst the destination buffer. * @param maxLen the maximum number of bytes to be read. * @return The number of bytes read, possibly zero. */ int read(ByteBuffer dst, int maxLen); /** * Reads a sequence of bytes from this buffer into the destination buffer. * The exact number of bytes transferred depends on availability of data * in this buffer and capacity of the destination buffer. * * @param dst the destination buffer. * @return The number of bytes read, possibly zero. */ int read(ByteBuffer dst); /** * Reads a sequence of bytes from this buffer into the destination channel, * up to the given maximum limit. The exact number of bytes transferred * depends on availability of data in this buffer, but cannot be more than * <code>maxLen</code> value. * * @param dst the destination channel. * @param maxLen the maximum number of bytes to be read. * @return The number of bytes read, possibly zero. * @throws IOException in case of an I/O error. */ int read(WritableByteChannel dst, int maxLen) throws IOException; /** * Reads a sequence of bytes from this buffer into the destination channel. * The exact number of bytes transferred depends on availability of data in * this buffer. * * @param dst the destination channel. * @return The number of bytes read, possibly zero. * @throws IOException in case of an I/O error. */ int read(WritableByteChannel dst) throws IOException; /** * Attempts to transfer a complete line of characters up to a line delimiter * from this buffer to the destination buffer. If a complete line is * available in the buffer, the sequence of chars is transferred to the * destination buffer the method returns <code>true</code>. The line * delimiter itself is discarded. If a complete line is not available in * the buffer, this method returns <code>false</code> without transferring * anything to the destination buffer. If <code>endOfStream</code> parameter * is set to <code>true</code> this method assumes the end of stream has * been reached and the content currently stored in the buffer should be * treated as a complete line. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param dst the destination buffer. * @param endOfStream * @return <code>true</code> if a sequence of chars representing a complete * line has been transferred to the destination buffer, <code>false</code> * otherwise. * * @throws CharacterCodingException in case a character encoding or decoding * error occurs. */ boolean readLine(CharArrayBuffer dst, boolean endOfStream) throws CharacterCodingException; /** * Attempts to transfer a complete line of characters up to a line delimiter * from this buffer to a newly created string. If a complete line is * available in the buffer, the sequence of chars is transferred to a newly * created string. The line delimiter itself is discarded. If a complete * line is not available in the buffer, this method returns * <code>null</code>. If <code>endOfStream</code> parameter * is set to <code>true</code> this method assumes the end of stream has * been reached and the content currently stored in the buffer should be * treated as a complete line. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param endOfStream * @return a string representing a complete line, if available. * <code>null</code> otherwise. * * @throws CharacterCodingException in case a character encoding or decoding * error occurs. */ String readLine(boolean endOfStream) throws CharacterCodingException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionInputBuffer.java
Java
gpl3
7,199
/* * ==================================================================== * 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.http.nio.reactor; import java.io.IOException; import java.net.SocketAddress; /** * SessionRequest interface represents a request to establish a new connection * (or session) to a remote host. It can be used to monitor the status of the * request, to block waiting for its completion, or to cancel the request. * <p> * Implementations of this interface are expected to be threading safe. * * @since 4.0 */ public interface SessionRequest { /** * Returns socket address of the remote host. * * @return socket address of the remote host */ SocketAddress getRemoteAddress(); /** * Returns local socket address. * * @return local socket address. */ SocketAddress getLocalAddress(); /** * Returns attachment object will be added to the session's context upon * initialization. This object can be used to pass an initial processing * state to the protocol handler. * * @return attachment object. */ Object getAttachment(); /** * Determines whether the request has been completed (either successfully * or unsuccessfully). * * @return <code>true</true> if the request has been completed, * <code>false</true> if still pending. */ boolean isCompleted(); /** * Returns {@link IOSession} instance created as a result of this request * or <code>null</code> if the request is still pending. * * @return I/O session or <code>null</code> if the request is still pending. */ IOSession getSession(); /** * Returns {@link IOException} instance if the request could not be * successfully executed due to an I/O error or <code>null</code> if no * error occurred to this point. * * @return I/O exception or <code>null</code> if no error occurred to * this point. */ IOException getException(); /** * Waits for completion of this session request. * * @throws InterruptedException in case the execution process was * interrupted. */ void waitFor() throws InterruptedException; /** * Sets connect timeout value in milliseconds. * * @param timeout connect timeout value in milliseconds. */ void setConnectTimeout(int timeout); /** * Returns connect timeout value in milliseconds. * * @return connect timeout value in milliseconds. */ int getConnectTimeout(); /** * Cancels the request. Invocation of this method will set the status of * the request to completed and will unblock threads blocked in * the {{@link #waitFor()}} method. */ void cancel(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionRequest.java
Java
gpl3
3,881
/* * $Date: * * ==================================================================== * 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.http.nio.reactor; /** * SessionBufferStatus interface is intended to query the status of session * I/O buffers. * * @since 4.0 */ public interface SessionBufferStatus { /** * Determines if the session input buffer contains data. * * @return <code>true</code> if the session input buffer contains data, * <code>false</code> otherwise. */ boolean hasBufferedInput(); /** * Determines if the session output buffer contains data. * * @return <code>true</code> if the session output buffer contains data, * <code>false</code> otherwise. */ boolean hasBufferedOutput(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionBufferStatus.java
Java
gpl3
1,862
/* * ==================================================================== * 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.http.nio.reactor; import java.io.IOException; /** * Abstract exception handler intended to deal with potentially recoverable * I/O exceptions thrown by an I/O reactor. * * @since 4.0 */ public interface IOReactorExceptionHandler { /** * This method is expected to examine the I/O exception passed as * a parameter and decide whether it is safe to continue execution of * the I/O reactor. * * @param ex potentially recoverable I/O exception * @return <code>true</code> if it is safe to ignore the exception * and continue execution of the I/O reactor; <code>false</code> if the * I/O reactor must throw {@link IOReactorException} and terminate */ boolean handle(IOException ex); /** * This method is expected to examine the runtime exception passed as * a parameter and decide whether it is safe to continue execution of * the I/O reactor. * * @param ex potentially recoverable runtime exception * @return <code>true</code> if it is safe to ignore the exception * and continue execution of the I/O reactor; <code>false</code> if the * I/O reactor must throw {@link RuntimeException} and terminate */ boolean handle(RuntimeException ex); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorExceptionHandler.java
Java
gpl3
2,458
/* * ==================================================================== * 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.http.nio.reactor; import java.net.SocketAddress; /** * ConnectingIOReactor represents an I/O reactor capable of establishing * connections to remote hosts. * * @since 4.0 */ public interface ConnectingIOReactor extends IOReactor { /** * Requests a connection to a remote host. * <p> * Opening a connection to a remote host usually tends to be a time * consuming process and may take a while to complete. One can monitor and * control the process of session initialization by means of the * {@link SessionRequest} interface. * <p> * There are several parameters one can use to exert a greater control over * the process of session initialization: * <p> * A non-null local socket address parameter can be used to bind the socket * to a specific local address. * <p> * An attachment object can added to the new session's context upon * initialization. This object can be used to pass an initial processing * state to the protocol handler. * <p> * It is often desirable to be able to react to the completion of a session * request asynchronously without having to wait for it, blocking the * current thread of execution. One can optionally provide an implementation * {@link SessionRequestCallback} instance to get notified of events related * to session requests, such as request completion, cancellation, failure or * timeout. * * @param remoteAddress the socket address of the remote host. * @param localAddress the local socket address. Can be <code>null</code>, * in which can the default local address and a random port will be used. * @param attachment the attachment object. Can be <code>null</code>. * @param callback interface. Can be <code>null</code>. * @return session request object. */ SessionRequest connect( SocketAddress remoteAddress, SocketAddress localAddress, Object attachment, SessionRequestCallback callback); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ConnectingIOReactor.java
Java
gpl3
3,260
/* * ==================================================================== * 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.http.nio.reactor; /** * IOEventDispatch interface is used by I/O reactors to notify clients of I/O * events pending for a particular session. All methods of this interface are * executed on a dispatch thread of the I/O reactor. Therefore, it is important * that processing that takes place in the event methods will not block the * dispatch thread for too long, as the I/O reactor will be unable to react to * other events. * * @since 4.0 */ public interface IOEventDispatch { /** * Triggered after the given session has been just created. * * @param session the I/O session. */ void connected(IOSession session); /** * Triggered when the given session has input pending. * * @param session the I/O session. */ void inputReady(IOSession session); /** * Triggered when the given session is ready for output. * * @param session the I/O session. */ void outputReady(IOSession session); /** * Triggered when the given session as timed out. * * @param session the I/O session. */ void timeout(IOSession session); /** * Triggered when the given session has been terminated. * * @param session the I/O session. */ void disconnected(IOSession session); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOEventDispatch.java
Java
gpl3
2,507
/* * ==================================================================== * 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.http.nio.reactor; import java.io.IOException; /** * I/O exception that can be thrown by an I/O reactor. Usually exceptions * of this type are fatal and are not recoverable. * * @since 4.0 */ public class IOReactorException extends IOException { private static final long serialVersionUID = -4248110651729635749L; public IOReactorException(final String message, final Exception cause) { super(message); if (cause != null) { initCause(cause); } } public IOReactorException(final String message) { super(message); } }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/IOReactorException.java
Java
gpl3
1,794
/* * ==================================================================== * 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.http.nio.reactor; import java.net.SocketAddress; import java.util.Set; import java.io.IOException; /** * ListeningIOReactor represents an I/O reactor capable of listening for * incoming connections on one or several ports. * * @since 4.0 */ public interface ListeningIOReactor extends IOReactor { /** * Opens a new listener endpoint with the given socket address. Once * the endpoint is fully initialized it starts accepting incoming * connections and propagates I/O activity notifications to the I/O event * dispatcher. * <p> * {@link ListenerEndpoint#waitFor()} can be used to wait for the * listener to be come ready to accept incoming connections. * <p> * {@link ListenerEndpoint#close()} can be used to shut down * the listener even before it is fully initialized. * * @param address the socket address to listen on. * @return listener endpoint. */ ListenerEndpoint listen(SocketAddress address); /** * Suspends the I/O reactor preventing it from accepting new connections on * all active endpoints. * * @throws IOException in case of an I/O error. */ void pause() throws IOException; /** * Resumes the I/O reactor restoring its ability to accept incoming * connections on all active endpoints. * * @throws IOException in case of an I/O error. */ void resume() throws IOException; /** * Returns a set of endpoints for this I/O reactor. * * @return set of endpoints. */ Set<ListenerEndpoint> getEndpoints(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListeningIOReactor.java
Java
gpl3
2,819
/* * ==================================================================== * 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.http.nio.reactor; import java.io.IOException; import java.net.SocketAddress; /** * ListenerEndpoint interface represents an endpoint used by an I/O reactor * to listen for incoming connection from remote clients. * * @since 4.0 */ public interface ListenerEndpoint { /** * Returns the socket address of this endpoint. * * @return socket address. */ SocketAddress getAddress(); /** * Returns an instance of {@link IOException} thrown during initialization * of this endpoint or <code>null</code>, if initialization was successful. * * @return I/O exception object or <code>null</code>. */ IOException getException(); /** * Waits for completion of initialization process of this endpoint. * * @throws InterruptedException in case the initialization process was * interrupted. */ void waitFor() throws InterruptedException; /** * Determines if this endpoint has been closed and is no longer listens * for incoming connections. * * @return <code>true</code> if the endpoint has been closed, * <code>false</code> otherwise. */ boolean isClosed(); /** * Closes this endpoint. The endpoint will stop accepting incoming * connection. */ void close(); }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/ListenerEndpoint.java
Java
gpl3
2,521
/* * ==================================================================== * 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.http.nio.reactor; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ReadableByteChannel; import java.nio.channels.WritableByteChannel; import java.nio.charset.CharacterCodingException; import org.apache.http.util.CharArrayBuffer; /** * Session output buffer for non-blocking connections. This interface * facilitates intermediate buffering of output data streamed out to * a destination channel and writing data to the buffer from a source, usually * {@link ByteBuffer} or {@link ReadableByteChannel}. This interface also * provides methods for writing lines of text. * * @since 4.0 */ public interface SessionOutputBuffer { /** * Determines if the buffer contains data. * * @return <code>true</code> if there is data in the buffer, * <code>false</code> otherwise. */ boolean hasData(); /** * Returns the length of this buffer. * * @return buffer length. */ int length(); /** * Makes an attempt to flush the content of this buffer to the given * destination {@link WritableByteChannel}. * * @param channel the destination channel. * @return The number of bytes written, possibly zero. * @throws IOException in case of an I/O error. */ int flush(WritableByteChannel channel) throws IOException; /** * Copies content of the source buffer into this buffer. The capacity of * the destination will be expanded in order to accommodate the entire * content of the source buffer. * * @param src the source buffer. */ void write(ByteBuffer src); /** * Reads a sequence of bytes from the source channel into this buffer. * * @param src the source channel. */ void write(ReadableByteChannel src) throws IOException; /** * Copies content of the source buffer into this buffer as one line of text * including a line delimiter. The capacity of the destination will be * expanded in order to accommodate the entire content of the source buffer. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param src the source buffer. */ void writeLine(CharArrayBuffer src) throws CharacterCodingException; /** * Copies content of the given string into this buffer as one line of text * including a line delimiter. * The capacity of the destination will be expanded in order to accommodate * the entire string. * <p> * The choice of a char encoding and line delimiter sequence is up to the * specific implementations of this interface. * * @param s the string. */ void writeLine(String s) throws IOException; }
zzy20080920-gps
OpenGPSTracker/external_sources/httpcore-4.1.1/httpcore-nio/src/main/java/org/apache/http/nio/reactor/SessionOutputBuffer.java
Java
gpl3
4,034
ant clean; ant release; adb install -r bin/MetaTracker-release.apk
zzy20080920-gps
MetaTracker/application/build-install.sh
Shell
gpl3
67
/* * 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; } } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/activity/TrackingState.java
Java
gpl3
2,800
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.activity; import 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); } } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/activity/UploadTrackActivity.java
Java
gpl3
6,069
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.activity; import 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 ); } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/activity/SettingsActivity.java
Java
gpl3
1,187
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.activity; import android.app.*; 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(); } } }; }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/activity/MainActivity.java
Java
gpl3
18,582
/* * 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 * * */
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/xml/DefaultVisitor.java
Java
gpl3
1,669
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.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 * * */
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/xml/ElementCopyVisitor.java
Java
gpl3
3,342
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; import org.w3c.dom.*; import 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 * * */
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/xml/DOMUtil.java
Java
gpl3
7,126
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; /** * 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 * * */
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/xml/Visitor.java
Java
gpl3
1,671
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; /** * 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 * * */
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/xml/TreeWalker.java
Java
gpl3
3,723
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.xml; 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) { } } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/xml/XMLPrintVisitor.java
Java
gpl3
5,835
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker; 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); } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/Constants.java
Java
gpl3
6,401
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.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); } } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/logger/GPSLoggerServiceManager.java
Java
gpl3
6,466
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.net; /** * 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(); } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/net/ClientException.java
Java
gpl3
1,533
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.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() { } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/net/Protocol.java
Java
gpl3
5,814
/* * Copyright (C) 2010 Just Objects B.V. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.opentraces.metatracker.net; import android.util.Log; import org.apache.http.HttpResponse; import org.apache.http.client.HttpClient; import org.apache.http.client.methods.HttpPost; import org.apache.http.entity.StringEntity; import org.apache.http.entity.mime.MultipartEntity; import org.apache.http.entity.mime.content.FileBody; import org.apache.http.entity.mime.content.StringBody; import org.apache.http.impl.client.DefaultHttpClient; import org.opentraces.metatracker.xml.DOMUtil; import org.w3c.dom.Document; import org.w3c.dom.Element; import org.w3c.dom.NodeList; import java.io.File; import java.util.ArrayList; import java.util.List; /** * Basic OpenTraces client using XML over HTTP. * <p/> * Use this class within Android HTTP clients. * * @author $Author: Just van den Broecke$ * @version $Revision: 3043 $ $Id: HTTPClient.java 3043 2009-01-17 16:25:21Z just $ * @see */ public class OpenTracesClient extends Protocol { private static final String LOG_TAG = "MT.OpenTracesClient"; /** * Default KW session timeout (minutes). */ public static final int DEFAULT_TIMEOUT_MINS = 5; /** * Full KW protocol URL. */ private String protocolURL; /** * Debug flag for verbose output. */ private boolean debug; /** * Key gotten on login ack */ private String agentKey; /** * Keyworx session timeout (minutes). */ private int timeout; /** * Saved login request for session restore on timeout. */ private Element loginRequest; /** * Constructor with full protocol URL e.g. http://www.bla.com/proto.srv. */ public OpenTracesClient(String aProtocolURL) { this(aProtocolURL, DEFAULT_TIMEOUT_MINS); } /** * Constructor with protocol URL and timeout. */ public OpenTracesClient(String aProtocolURL, int aTimeout) { protocolURL = aProtocolURL; if (!protocolURL.endsWith("/proto.srv")) { protocolURL += "/proto.srv"; } timeout = aTimeout; } /** * Create session. */ synchronized public Element createSession() throws ClientException { agentKey = null; // Create XML request Element request = createRequest(SERVICE_SESSION_CREATE); // Execute request Element response = doRequest(request); handleResponse(request, response); throwOnNrsp(response); // Returns positive response return response; } public String getAgentKey() { return agentKey; } public boolean hasSession() { return agentKey != null; } public boolean isLoggedIn() { return hasSession() && loginRequest != null; } /** * Login on portal. */ synchronized public Element login(String aName, String aPassword) throws ClientException { // Create XML request Element request = createLoginRequest(aName, aPassword); // Execute request Element response = doRequest(request); // Filter session-related attrs handleResponse(request, response); throwOnNrsp(response); // Returns positive response return response; } /** * Keep alive service. */ synchronized public Element ping() throws ClientException { return service(createRequest(SERVICE_SESSION_PING)); } /** * perform TWorx service request. */ synchronized public Element service(Element request) throws ClientException { throwOnInvalidSession(); // Execute request Element response = doRequest(request); // Check for session timeout response = redoRequestOnSessionTimeout(request, response); // Throw exception on negative response throwOnNrsp(response); // Positive response: return wrapped handler response return response; } /** * perform TWorx multi-service request. */ synchronized public List<Element> service(List<Element> requests, boolean stopOnError) throws ClientException { // We don't need a valid session as one of the requests // may be a login or create-session request. // Create multi-req request with individual requests as children Element request = createRequest(SERVICE_MULTI_REQ); request.setAttribute(ATTR_STOPONERROR, stopOnError + ""); for (Element req : requests) { request.appendChild(req); } // Execute request Element response = doRequest(request); // Check for session timeout response = redoRequestOnSessionTimeout(request, response); // Throw exception on negative response throwOnNrsp(response); // Filter child responses for session-based responses NodeList responseList = response.getChildNodes(); List<Element> responses = new ArrayList(responseList.getLength()); for (int i = 0; i < responseList.getLength(); i++) { handleResponse(requests.get(i), (Element) responseList.item(i)); responses.add((Element) responseList.item(i)); } // Positive multi-req response: return child responses return responses; } /** * Logout from portal. */ synchronized public Element logout() throws ClientException { throwOnInvalidSession(); // Create XML request Element request = createRequest(SERVICE_LOGOUT); // Execute request Element response = doRequest(request); handleResponse(request, response); // Throw exception or return positive response // throwOnNrsp(response); return response; } /* http://brainflush.wordpress.com/2008/10/17/talking-to-web-servers-via-http-in-android-10/ */ public void uploadFile(String fileName) { try { DefaultHttpClient httpclient = new DefaultHttpClient(); File f = new File(fileName); HttpPost httpost = new HttpPost("http://local.geotracing.com/tland/media.srv"); MultipartEntity entity = new MultipartEntity(); entity.addPart("myIdentifier", new StringBody("somevalue")); entity.addPart("myFile", new FileBody(f)); httpost.setEntity(entity); HttpResponse response; response = httpclient.execute(httpost); Log.d(LOG_TAG, "Upload result: " + response.getStatusLine()); if (entity != null) { entity.consumeContent(); } httpclient.getConnectionManager().shutdown(); } catch (Throwable ex) { Log.d(LOG_TAG, "Upload failed: " + ex.getMessage() + " Stacktrace: " + ex.getStackTrace()); } } public void setDebug(boolean b) { debug = b; } /** * Filter responses for session-related requests. */ private void handleResponse(Element request, Element response) throws ClientException { if (isNegativeResponse(response)) { return; } String service = Protocol.getServiceName(request.getTagName()); if (service.equals(SERVICE_LOGIN)) { // Save for later session restore loginRequest = request; // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); // if (response.hasAttribute(ATTR_TIME)) { // DateTimeUtils.setTime(response.getLongAttr(ATTR_TIME)); // } } else if (service.equals(SERVICE_SESSION_CREATE)) { // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); } else if (service.equals(SERVICE_LOGOUT)) { loginRequest = null; agentKey = null; } } /** * Throw exception on negative protocol response. */ private void throwOnNrsp(Element anElement) throws ClientException { if (isNegativeResponse(anElement)) { String details = "no details"; if (anElement.hasAttribute(ATTR_DETAILS)) { details = anElement.getAttribute(ATTR_DETAILS); } throw new ClientException(Integer.parseInt(anElement.getAttribute(ATTR_ERRORID)), anElement.getAttribute(ATTR_ERROR), details); } } /** * Throw exception when not logged in. */ private void throwOnInvalidSession() throws ClientException { if (agentKey == null) { throw new ClientException("Invalid tworx session"); } } /** * . */ private Element redoRequestOnSessionTimeout(Element request, Element response) throws ClientException { // Check for session timeout if (isNegativeResponse(response) && Integer.parseInt(response.getAttribute(ATTR_ERRORID)) == Protocol.ERR4007_AGENT_LEASE_EXPIRED) { p("Reestablishing session..."); // Reset session agentKey = null; // Do login if already logged in if (loginRequest != null) { response = doRequest(loginRequest); throwOnNrsp(response); } else { response = createSession(); throwOnNrsp(response); } // Save session key agentKey = response.getAttribute(ATTR_AGENTKEY); // Re-issue service request and return new response return doRequest(request); } // No session timeout so same response return response; } /** * Do XML over HTTP request and retun response. */ private Element doRequest(Element anElement) throws ClientException { // Create URL to use String url = protocolURL; if (agentKey != null) { url = url + "?agentkey=" + agentKey; } else { // Must be login url = url + "?timeout=" + timeout; } p("doRequest: " + url + " req=" + anElement.getTagName()); // Perform request/response HttpClient httpclient = new DefaultHttpClient(); HttpPost httpPost = new HttpPost(url); Element replyElement = null; try { // Make sure the server knows what kind of a response we will accept httpPost.addHeader("Accept", "text/xml"); // Also be sure to tell the server what kind of content we are sending httpPost.addHeader("Content-Type", "application/xml"); String xmlString = DOMUtil.dom2String(anElement.getOwnerDocument()); StringEntity entity = new StringEntity(xmlString, "UTF-8"); entity.setContentType("application/xml"); httpPost.setEntity(entity); // Execute HTTP Post Request HttpResponse response = httpclient.execute(httpPost); // Parse response Document replyDoc = DOMUtil.parse(response.getEntity().getContent()); replyElement = replyDoc.getDocumentElement(); p("doRequest: rsp=" + replyElement.getTagName()); } catch (Throwable t) { throw new ClientException("Error in doRequest: " + t); } finally { } return replyElement; } /** * Util: print. */ private void p(String s) { if (debug) { Log.d(LOG_TAG, s); } } /** * Util: warn. */ private void warn(String s) { warn(s, null); } /** * Util: warn with exception. */ private void warn(String s, Throwable t) { Log.e(LOG_TAG, s + " ex=" + t, t); } }
zzy20080920-gps
MetaTracker/application/src/org/opentraces/metatracker/net/OpenTracesClient.java
Java
gpl3
10,842
package nl.sogeti.android.gpstracker.logger; import android.net.Uri; interface IGPSLoggerServiceRemote { int loggingState(); long startLogging(); void pauseLogging(); long resumeLogging(); void stopLogging(); Uri storeMediaUri(in Uri mediaUri); boolean isMediaPrepared(); }
zzy20080920-gps
MetaTracker/application/src/nl/sogeti/android/gpstracker/logger/IGPSLoggerServiceRemote.aidl
AIDL
gpl3
295
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd"> <!-- saved from url=(0041)http://m.weather.com.cn/m/pn7/weather.htm --> <HTML xmlns="http://www.w3.org/1999/xhtml"><HEAD><TITLE>中国天气网-天气模块7</TITLE> <META content="text/html; charset=utf-8" http-equiv=Content-Type><LINK rel=stylesheet type=text/css href="weather_files/cj.css" media=screen> <STYLE type=text/css>IMG { BEHAVIOR: url(iepngfix.htc) } DIV { BEHAVIOR: url(iepngfix.htc) } </STYLE> <META name=GENERATOR content="MSHTML 8.00.6001.18999"></HEAD> <BODY> <UL class=row> <LI><A id=url1 href="http://m.weather.com.cn/m/pn7/weather.htm#" target=_blank><EM id=city></EM></A></LI> <LI><A id=url2 href="http://m.weather.com.cn/m/pn7/weather.htm#" target=_blank><IMG id=small1 alt=天气图标 src="weather_files/c1.gif" width=20 height=20></A> </LI> <LI><A id=url3 href="http://m.weather.com.cn/m/pn7/weather.htm#" target=_blank><EM id=temp1></EM></A></LI> <LI><A id=url4 href="http://m.weather.com.cn/m/pn7/weather.htm#" target=_blank><EM id=wind1></EM></A></LI></UL> <SCRIPT type=text/javascript src="weather_files/public_test.js"></SCRIPT> <!-- START WRating v1.0 --> <SCRIPT type=text/javascript src="weather_files/a1.js"> </SCRIPT> <SCRIPT type=text/javascript> var vjAcc="860010-2151010100"; var wrUrl="http://c.wrating.com/"; var wrRandom = 70; var now = new Date(); var seed = now.getTime(); var randomNumber = Math.random(seed); if (randomNumber <= parseFloat(1/wrRandom)) { vjTrack(""); } </SCRIPT> <NOSCRIPT><IMG src="" width=1 height=1></NOSCRIPT> <!-- END WRating v1.0 --></BODY></HTML>
zzzcw-template
trunk/d_red/images/weather.htm
HTML
bsd
1,719
* { PADDING-BOTTOM: 0px; LINE-HEIGHT: 180%; LIST-STYLE-TYPE: none; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; FONT-WEIGHT: normal; PADDING-TOP: 0px } IMG { BORDER-RIGHT-WIDTH: 0px; BORDER-TOP-WIDTH: 0px; BORDER-BOTTOM-WIDTH: 0px; BORDER-LEFT-WIDTH: 0px } BODY { TEXT-ALIGN: center; BACKGROUND-COLOR: transparent; FONT-FAMILY: Verdana, Arial, Helvetica, sans-serif; COLOR: #000; FONT-SIZE: 12px } A { COLOR: #000; TEXT-DECORATION: none } A:hover { COLOR: #ff6600; TEXT-DECORATION: underline } EM { FONT-STYLE: normal } STRONG { } A STRONG { } SELECT { LINE-HEIGHT: 20px; HEIGHT: 20px } UL.row { CLEAR: both } UL.row LI { MARGIN: 0px 4px; FLOAT: left } UL.row LI A { LINE-HEIGHT: 22px; DISPLAY: inline; HEIGHT: 22px } .more A { } UL.col LI { TEXT-ALIGN: center; MARGIN: 4px auto; FONT-SIZE: 14px; FONT-WEIGHT: bold } UL.col LI #city { MARGIN-LEFT: 10px; FONT-WEIGHT: bold } UL.col LI A { FONT-SIZE: 14px; FONT-WEIGHT: bold } UL.col .small { PADDING-TOP: 6px } UL.col .small A { FONT-SIZE: 12px } UL.col .line { BORDER-BOTTOM: #ddd 1px dashed; PADDING-BOTTOM: 10px; PADDING-LEFT: 10px; PADDING-RIGHT: 10px; PADDING-TOP: 10px } DL { MARGIN: 0px auto; CLEAR: both } DL DT { FLOAT: left; HEIGHT: 65px; MARGIN-RIGHT: 10px } DL DT STRONG { MARGIN-TOP: 10px; DISPLAY: block; _margin-top: 15px } DL DT A { } DL DD { TEXT-ALIGN: left; PADDING-BOTTOM: 0px; LINE-HEIGHT: 18px; MARGIN: 0px; PADDING-LEFT: 0px; PADDING-RIGHT: 0px; HEIGHT: 18px; PADDING-TOP: 0px } DL .title { MARGIN-BOTTOM: 4px; _margin-bottom: -4px } DL .title #city { FONT-SIZE: 14px; FONT-WEIGHT: bold } #cj { CLEAR: both } #left { TEXT-ALIGN: center; FLOAT: left } #left H3 { MARGIN-BOTTOM: 4px } #left H3 #city { FONT-SIZE: 14px; FONT-WEIGHT: bold } #cj H4 { MARGIN-BOTTOM: 5px; FONT-SIZE: 12px } #right { TEXT-ALIGN: left; FLOAT: left; MARGIN-LEFT: 10px } #cjbg { PADDING-BOTTOM: 10px; PADDING-LEFT: 10px; PADDING-RIGHT: 10px; BACKGROUND: url(/img/bg.gif) repeat-x left bottom; HEIGHT: 90px; PADDING-TOP: 10px } #cjbg .line { BORDER-LEFT: #ddd 1px solid; PADDING-LEFT: 8px } #cjbg H4 { FONT-SIZE: 12px } #right H3 #city { MARGIN-BOTTOM: 4px; FONT-SIZE: 14px; FONT-WEIGHT: bold; MARGIN-RIGHT: 10px } UL.new { LINE-HEIGHT: 28px; BACKGROUND-COLOR: transparent; HEIGHT: 28px } UL.new LI A IMG { MARGIN-TOP: 4px } UL.new LI A EM { LINE-HEIGHT: 28px; COLOR: #fff; FONT-WEIGHT: bold } UL.new LI A:hover { COLOR: #000; TEXT-DECORATION: none } UL.new LI A:hover EM { COLOR: #000 } #eNew { TEXT-ALIGN: left; MARGIN: 0px auto; WIDTH: 150px; HEIGHT: 180px } #eNew H1 { MARGIN-BOTTOM: 0px; FONT-SIZE: 20px } #eNew H2 A EM { FONT-SIZE: 14px; FONT-WEIGHT: normal } #eNew H4 { LINE-HEIGHT: 43px; TEXT-INDENT: 1em; WIDTH: 150px; BACKGROUND: url(/img/w.gif) no-repeat left top; HEIGHT: 43px } #eNew H4 A EM { LINE-HEIGHT: 43px; FONT-SIZE: 18px } #eNew P { FONT-SIZE: 12px } .blue { TEXT-ALIGN: right } .blue LI A { COLOR: #0070c0 } UL.blue LI { FLOAT: right }
zzzcw-template
trunk/d_red/images/weather_files/cj.css
CSS
bsd
3,113
/*by niuyi 2010年10月27日*/ /*公共函数*/ var xmlhttp=null; var jsonobj; var rs="http://61.4.185.48:81/g/"; var cookie_info= getCookie('newcity1'); var id1; var ids="url1,url2,url3,url4,url5,url6,url7,url8,url9,url10,url11,url12,url13"; var url=window.location.href; var start=url.indexOf("id"); var end=url.indexOf("T"); /*url赋值函数*/ var setURL=function(ids, url) { var nodes=ids; if(typeof nodes=="string") { nodes=nodes.split(","); } for( var i=0; i<nodes.length; i++) { if(document.getElementById(nodes[i])) { document.getElementById(nodes[i]).href=url; } } } /*保存cookies函数*/ function setCookie(name, value) { var argv = setCookie.arguments; var argc = setCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; if(expires!=null) { var LargeExpDate = new Date (); LargeExpDate.setTime(LargeExpDate.getTime() + (expires*365*24*60*60*1000*10)); } document.cookie = name + "=" + escape (value)+((expires == null) ? "" : ("; expires=" +LargeExpDate.toGMTString())); } /*获取cookies函数*/ function getCookie(Name) { var search = Name + "=" if(document.cookie.length > 0) { offset = document.cookie.indexOf(search) if(offset != -1) { offset += search.length end = document.cookie.indexOf(";", offset) if(end == -1) end = document.cookie.length return unescape(document.cookie.substring(offset, end)) } else return "" } } /*创建xmlhttp请求函数*/ function createXMLHTTPRequext() { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); //Mozilla } else if (window.ActiveXObject) { xmlhttp =new ActiveXObject("Msxml2.XMLHTTP") ; if (! xmlhttp ) { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } } } /*判断xmlhttp状态函数函数*/ function HandleStateChange() { if (xmlhttp.readyState == 4) { var jsontext =xmlhttp.responseText; var func = new Function("return " + jsontext); jsonobj = func(); } } /*发送请求函数*/ function PostOrder(xmldoc) { createXMLHTTPRequext(); xmlhttp.open("GET", xmldoc,false); xmlhttp.onreadystatechange= HandleStateChange; xmlhttp.send(null); } /*插件赋值函数*/ function returndata(id){ /*参数说明 id:城市九位站点号 img_s:小图路径 img_b:大图路径 div_names:要获取内容的div节点名称 */ var datastr1; if(id==""){ str="101010100"; datastr1='/data/'+str+'.html'; }else{ datastr1='/data/'+id+'.html'; } PostOrder(datastr1); HandleStateChange(); var parseData=new Object(); with(jsonobj.weatherinfo){ parseData={ city: {innerHTML: city}, temp1: {innerHTML: temp1}, temp2: {innerHTML: temp2}, temp3: {innerHTML: temp3}, temp4: {innerHTML: temp4}, wind1: {innerHTML: wind1}, wind2: {innerHTML: wind2}, date: {innerHTML: date}, date_y: {innerHTML: date_y}, weather1: {innerHTML: weather1}, weather2: {innerHTML: weather2}, weather3: {innerHTML: weather3}, weather4: {innerHTML: weather4}, index: {innerHTML: index}, index_d: {innerHTML: index_d}, index_xc: {innerHTML: index_xc}, index_uv: {innerHTML: index_uv}, index_tr: {innerHTML: index_tr}, small1: { src:"/img/c"+(img2==99?img1:img2)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, small2: { src:"/img/c"+img2+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, small3: { src:"/img/c"+(img4==99?img3:img4)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index48_uv+"。"+"穿衣指数:"+index48_d }, big1: { src:"/img/b"+(img2==99?img1:img2)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, big2: { src:"/img/b"+img2+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, big3: { src:"/img/b"+(img4==99?img3:img4)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index48_uv+"。"+"穿衣指数:"+index48_d } } } for( var m in parseData){ var node=document.getElementById(m); var sets=parseData[m]; if(node){ for( var prop in sets ){ node[prop]=sets[prop]; } } } } /*插件主体功能程序*/ if(start!=-1){ var first=start+parseInt(3); call=url.substring(first,end); returndata(call); setURL(ids,"http://www.weather.com.cn/weather/"+call+".shtml"); } else{ if(!cookie_info) { var js = document.createElement("script"); js.setAttribute("type", "text/javascript"); js.setAttribute("src",rs); document.body.insertBefore(js, null); function id_callback() { std = id; if(typeof(id)=="undefined") { id1="101010100"; setURL(ids,"http://www.weather.com.cn/weather/"+id1+".shtml"); returndata(id1); } else { id1=std; time=new Date(); time.setTime(time.getTime()+365*24*60*60*1000*10); date=time.toGMTString(); document.cookie = "newcity1=" + escape(std)+ ";expires="+date; setURL(ids,"http://www.weather.com.cn/weather/"+id1+".shtml"); returndata(std); } } } else{ id1=cookie_info; setURL(ids,"http://www.weather.com.cn/weather/"+id1+".shtml"); returndata(id1); } } /*by niuyi 2010年10月27日*/ /*公共函数*/ var xmlhttp=null; var jsonobj; var rs="http://61.4.185.48:81/g/"; var cookie_info= getCookie('newcity1'); var id1; var ids="url1,url2,url3,url4,url5,url6,url7,url8,url9,url10,url11,url12,url13"; var url=window.location.href; var start=url.indexOf("id"); var end=url.indexOf("T"); /*url赋值函数*/ var setURL=function(ids, url) { var nodes=ids; if(typeof nodes=="string") { nodes=nodes.split(","); } for( var i=0; i<nodes.length; i++) { if(document.getElementById(nodes[i])) { document.getElementById(nodes[i]).href=url; } } } /*保存cookies函数*/ function setCookie(name, value) { var argv = setCookie.arguments; var argc = setCookie.arguments.length; var expires = (argc > 2) ? argv[2] : null; if(expires!=null) { var LargeExpDate = new Date (); LargeExpDate.setTime(LargeExpDate.getTime() + (expires*365*24*60*60*1000*10)); } document.cookie = name + "=" + escape (value)+((expires == null) ? "" : ("; expires=" +LargeExpDate.toGMTString())); } /*获取cookies函数*/ function getCookie(Name) { var search = Name + "=" if(document.cookie.length > 0) { offset = document.cookie.indexOf(search) if(offset != -1) { offset += search.length end = document.cookie.indexOf(";", offset) if(end == -1) end = document.cookie.length return unescape(document.cookie.substring(offset, end)) } else return "" } } /*创建xmlhttp请求函数*/ function createXMLHTTPRequext() { if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); //Mozilla } else if (window.ActiveXObject) { xmlhttp =new ActiveXObject("Msxml2.XMLHTTP") ; if (! xmlhttp ) { xmlhttp = new ActiveXObject('Microsoft.XMLHTTP'); } } } /*判断xmlhttp状态函数函数*/ function HandleStateChange() { if (xmlhttp.readyState == 4) { var jsontext =xmlhttp.responseText; var func = new Function("return " + jsontext); jsonobj = func(); } } /*发送请求函数*/ function PostOrder(xmldoc) { createXMLHTTPRequext(); xmlhttp.open("GET", xmldoc,false); xmlhttp.onreadystatechange= HandleStateChange; xmlhttp.send(null); } /*插件赋值函数*/ function returndata(id){ /*参数说明 id:城市九位站点号 img_s:小图路径 img_b:大图路径 div_names:要获取内容的div节点名称 */ var datastr1; if(id==""){ str="101010100"; datastr1='/data/'+str+'.html'; }else{ datastr1='/data/'+id+'.html'; } PostOrder(datastr1); HandleStateChange(); var parseData=new Object(); with(jsonobj.weatherinfo){ parseData={ city: {innerHTML: city}, temp1: {innerHTML: temp1}, temp2: {innerHTML: temp2}, temp3: {innerHTML: temp3}, temp4: {innerHTML: temp4}, wind1: {innerHTML: wind1}, wind2: {innerHTML: wind2}, date: {innerHTML: date}, date_y: {innerHTML: date_y}, weather1: {innerHTML: weather1}, weather2: {innerHTML: weather2}, weather3: {innerHTML: weather3}, weather4: {innerHTML: weather4}, index: {innerHTML: index}, index_d: {innerHTML: index_d}, index_xc: {innerHTML: index_xc}, index_uv: {innerHTML: index_uv}, index_tr: {innerHTML: index_tr}, small1: { src:"/img/c"+(img2==99?img1:img2)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, small2: { src:"/img/c"+img2+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, small3: { src:"/img/c"+(img4==99?img3:img4)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index48_uv+"。"+"穿衣指数:"+index48_d }, big1: { src:"/img/b"+(img2==99?img1:img2)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, big2: { src:"/img/b"+img2+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index_uv+"。"+"穿衣指数:"+index_d }, big3: { src:"/img/b"+(img4==99?img3:img4)+".gif", title: "中国天气网今日天气指数 紫外线指数:"+index48_uv+"。"+"穿衣指数:"+index48_d } } } for( var m in parseData){ var node=document.getElementById(m); var sets=parseData[m]; if(node){ for( var prop in sets ){ node[prop]=sets[prop]; } } } } /*插件主体功能程序*/ if(start!=-1){ var first=start+parseInt(3); call=url.substring(first,end); returndata(call); setURL(ids,"http://www.weather.com.cn/weather/"+call+".shtml"); } else{ if(!cookie_info) { var js = document.createElement("script"); js.setAttribute("type", "text/javascript"); js.setAttribute("src",rs); document.body.insertBefore(js, null); function id_callback() { std = id; if(typeof(id)=="undefined") { id1="101010100"; setURL(ids,"http://www.weather.com.cn/weather/"+id1+".shtml"); returndata(id1); } else { id1=std; time=new Date(); time.setTime(time.getTime()+365*24*60*60*1000*10); date=time.toGMTString(); document.cookie = "newcity1=" + escape(std)+ ";expires="+date; setURL(ids,"http://www.weather.com.cn/weather/"+id1+".shtml"); returndata(std); } } } else{ id1=cookie_info; setURL(ids,"http://www.weather.com.cn/weather/"+id1+".shtml"); returndata(id1); } } var vjAcc="";var wrUrl="http://c.wrating.com/";var wrSv=0;function vjTrack(C){var B=vjValidateTrack();if(B===false){return }var A=wrUrl+"a.gif"+vjGetTrackImgUrl(C);document.write('<div style="display:none"><img src="'+A+'" id="wrTagImage" width="1" height="1"/></div>');vjSurveyCheck()}function vjEventTrack(D){var C=vjValidateTrack();if(C===false){return }var B=wrUrl+"a.gif"+vjGetTrackImgUrl(D);var A=new Image();A.src=B;A.onload=function(){}}function vjValidateTrack(){if(document.location.protocol=="file:"){return false}if(vjAcc==""){return false}else{if(wrUrl.substr(wrUrl.length-1,1)!="/"){wrUrl+="/"}}return true}function vjGetTrackImgUrl(S){var M=0;var N="expires=Fri, 1 Jan 2038 00:00:00 GMT;";var T=document.location;var P=document.referrer.toString();var D;var H=vjGetDomainFromUrl(T);var K;var V;var Y="";var L=vjFlash();var G="";var Z="";var J="";var O=navigator.appName+" "+navigator.appVersion;var F=new Date();var X=F.getTimezoneOffset()/-60;var A=0;var U="";var R="";if(typeof (H[1])!="undefined"){V=H[1]}else{if(typeof (H[0])!="undefined"){V=H[0]}}if(P!=""){Y=vjGetKeyword(P)}else{if((O.indexOf("MSIE")>=0)&&(parseInt(O.substr(O.indexOf("MSIE")+5),4)>=5)&&(O.indexOf("Mac")==-1)&&(navigator.userAgent.indexOf("Opera")==-1)){try{document.documentElement.addBehavior("#default#homePage");if(document.documentElement.isHomePage(location.href)){P="ishomepage"}}catch(W){}}}if(navigator.cookieEnabled){M=1}if(self.screen){G=screen.width+"x"+screen.height+"x"+screen.colorDepth}else{if(self.java){var Q=java.awt.Toolkit.getDefaultToolkit().getScreenSize();G=Q.width+"x"+Q.height+"x0"}}if(navigator.language){Z=navigator.language.toLowerCase()}else{if(navigator.browserLanguage){Z=navigator.browserLanguage.toLowerCase()}else{Z="-"}}if(navigator.javaEnabled()){A=1}if(M==1){D=document.cookie;if(D.indexOf("vjuids=")<0){K=vjVisitorID();document.cookie="vjuids="+escape(K)+";"+N+";domain="+V+";path=/;"}else{K=vjGetCookie("vjuids")}if(D.indexOf("vjlast=")<0){U="30";var E=vjGetTimestamp(F.getTime()).toString();R=E+"."+E+".30"}else{var a=vjGetCookie("vjlast");var C=a.split(".");var B="";if(typeof (C[0])!="undefined"){R=C[0].toString()}else{R=vjGetTimestamp(F.getTime()).toString()}if(typeof (C[1])!="undefined"){var I=new Date(parseInt(C[1])*1000);if(I.toDateString()!=F.toDateString()){R+="."+vjGetTimestamp(F.getTime()).toString();if(parseInt(vjGetTimestamp(F.getTime())-parseInt(C[1]))/86400>30){U="2"}else{U="1"}if(typeof (C[2])!="undefined"){U+=C[2].substr(0,1)}else{U+="0"}}else{R+="."+C[1].toString();if(typeof (C[2])!="undefined"){U+=C[2]}else{U="10"}}}else{R+="."+vjGetTimestamp(F.getTime()).toString();if(typeof (C[2])!="undefined"){U+=C[2]}else{U="10"}}R+="."+U}document.cookie="vjlast="+R+";"+N+";domain="+V+";path=/;"}J="?a="+F.getTime().toString(16)+"&t=&i="+escape(K);J+="&b="+escape(T)+"&c="+vjAcc;J+="&s="+G+"&l="+Z;J+="&z="+X+"&j="+A+"&f="+escape(L);if(P!=""){J+="&r="+escape(P)+"&kw="+Y}J+="&ut="+U+"&n=";if(typeof (S)=="undefined"){J+="&js="}else{J+="&js="+escape(S)}J+="&ck="+M;return J}function vjGetTimestamp(A){return Math.round(A/1000)}function vjGetKeyword(C){var A=[["baidu","wd"],["baidu","q1"],["google","q"],["google","as_q"],["yahoo","p"],["msn","q"],["live","q"],["sogou","query"],["youdao","q"],["soso","w"],["zhongsou","w"],["zhongsou","w1"]];var B=vjGetDomainFromUrl(C.toString().toLowerCase());var D=-1;var E="";if(typeof (B[0])=="undefined"){return""}for(i=0;i<A.length;i++){if(B[0].indexOf("."+A[i][0]+".")>=0){D=-1;D=C.indexOf("&"+A[i][1]+"=");if(D<0){D=C.indexOf("?"+A[i][1]+"=")}if(D>=0){E=C.substr(D+A[i][1].length+2,C.length-(D+A[i][1].length+2));D=E.indexOf("&");if(D>=0){E=E.substr(0,D)}if(E==""){return""}else{return A[i][0]+"|"+E}}}}return""}function vjGetDomainFromUrl(E){if(E==""){return false}E=E.toString().toLowerCase();var F=[];var C=E.indexOf("//")+2;var B=E.substr(C,E.length-C);var A=B.indexOf("/");if(A>=0){F[0]=B.substr(0,A)}else{F[0]=B}var D=F[0].match(/[^.]+\.(com.cn|net.cn|gov.cn|cn|com|net|org|gov|cc|biz|info)+$/);if(D){if(typeof (D[0])!="undefined"){F[1]=D[0]}}return F}function vjVisitorID(){var A=vjHash(document.location+document.cookie+document.referrer).toString(16);var B=new Date();return A+"."+B.getTime().toString(16)+"."+Math.random().toString(16)}function vjHash(C){if(!C||C==""){return 0}var B=0;for(var A=C.length-1;A>=0;A--){var D=parseInt(C.charCodeAt(A));B=(B<<5)+B+D}return B}function vjGetCookie(D){var B=D+"=";var F=B.length;var A=document.cookie.length;var E=0;while(E<A){var C=E+F;if(document.cookie.substring(E,C)==B){return vjGetCookieVal(C)}E=document.cookie.indexOf(" ",E)+1;if(E==1){break}}return null}function vjGetCookieVal(B){var A=document.cookie.indexOf(";",B);if(A==-1){A=document.cookie.length}return unescape(document.cookie.substring(B,A))}function vjFlash(){var _flashVer="-";var _navigator=navigator;if(_navigator.plugins&&_navigator.plugins.length){for(var ii=0;ii<_navigator.plugins.length;ii++){if(_navigator.plugins[ii].name.indexOf("Shockwave Flash")!=-1){_flashVer=_navigator.plugins[ii].description.split("Shockwave Flash ")[1];break}}}else{if(window.ActiveXObject){for(var ii=10;ii>=2;ii--){try{var fl=eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash."+ii+"');");if(fl){_flashVer=ii+".0";break}}catch(e){}}}}return _flashVer}function vjSurveyCheck(){if(wrSv<=0){return }var C=new Date();var A=C.getTime();var D=Math.random(A);if(D<=parseFloat(1/wrSv)){var B=document.createElement("script");B.type="text/javascript";B.id="wratingSuevey";B.src="http://tongji.wrating.com/survey/check.php?c="+vjAcc;document.getElementsByTagName("head")[0].appendChild(B)}};
zzzcw-template
trunk/d_red/images/weather_files/public_test.js
JavaScript
bsd
16,785
var lastDate = '';var lastMonth = '';var todayDate = '2010-12-18';var todayMonth = '12';
zzzcw-template
trunk/d_red/images/configJs.htm
HTML
bsd
88
lastDate='2010-12-18';lastMonth='12';
zzzcw-template
trunk/d_red/images/configJs.js
JavaScript
bsd
37
.topnav LI { POSITION: relative; FLOAT: left } .topnav LI UL.subnav { BORDER-BOTTOM: #a60000 1px solid; POSITION: absolute; FILTER: alpha(opacity=95); BORDER-LEFT: #a60000 1px solid; PADDING-BOTTOM: 0px; LIST-STYLE-TYPE: none; MARGIN: 0px; PADDING-LEFT: 0px; WIDTH: 85px; PADDING-RIGHT: 0px; DISPLAY: none; BACKGROUND: #b42727; FLOAT: left; BORDER-TOP: #a60000 1px solid; TOP: 30px; BORDER-RIGHT: #a60000 1px solid; PADDING-TOP: 0px; LEFT: -2px; -moz-opacity: 0.95; opacity: 0.95 } .topnav LI UL.subnav LI { PADDING-BOTTOM: 0px; MARGIN: 0px; PADDING-LEFT: 0px; WIDTH: 85px; PADDING-RIGHT: 0px; CLEAR: both; PADDING-TOP: 0px } .topnav LI UL.subnav LI A { WIDTH: 85px; BACKGROUND: #b42727; FLOAT: left; COLOR: #d6d5d5 } .topnav LI UL.subnav LI A:hover { BACKGROUND: #a61414; COLOR: #ffffff } #topBody .mainMenu .a { TEXT-ALIGN: center; LINE-HEIGHT: 31px; WIDTH: 84px; BACKGROUND: url(top_menuOver.gif) no-repeat } #topBody .mainMenu .b { TEXT-ALIGN: center; LINE-HEIGHT: 31px; WIDTH: 84px; BACKGROUND: none transparent scroll repeat 0% 0% }
zzzcw-template
trunk/d_red/images/navMenu11.css
CSS
bsd
1,067
(function () { $.fn.infiniteCarousel = function () { function repeat(str, n) { return new Array( n + 1 ).join(str); } return this.each(function () { // magic! var $wrapper = $('> div', this).css('overflow', 'hidden'), $slider = $wrapper.find('> ul').width(9999), $items = $slider.find('> li'), $single = $items.filter(':first') singleWidth = $single.outerWidth(), visible = Math.ceil($wrapper.innerWidth() / singleWidth), currentPage = 1, pages = Math.ceil($items.length / visible); /* TASKS */ // 1. pad the pages with empty element if required if ($items.length % visible != 0) { // pad $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible))); $items = $slider.find('> li'); } // 2. create the carousel padding on left and right (cloned) $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned')); $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned')); $items = $slider.find('> li'); // 3. reset scroll $wrapper.scrollLeft(singleWidth * visible); // 4. paging function function gotoPage(page) { var dir = page < currentPage ? -1 : 1, n = Math.abs(currentPage - page), left = singleWidth * dir * visible * n; $wrapper.filter(':not(:animated)').animate({ scrollLeft : '+=' + left }, 500, function () { // if page == last page - then reset position if (page > pages) { $wrapper.scrollLeft(singleWidth * visible); page = 1; } else if (page == 0) { page = pages; $wrapper.scrollLeft(singleWidth * visible * pages); } currentPage = page; }); } // 5. insert the back and forward link $wrapper.after('<a href="#" class="arrow back">&lt;</a><a href="#" class="arrow forward">&gt;</a>'); // 6. bind the back and forward links $('a.back', this).click(function () { gotoPage(currentPage - 1); return false; }); $('a.forward', this).click(function () { gotoPage(currentPage + 1); return false; }); $(this).bind('goto', function (event, page) { gotoPage(page); }); // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL $(this).bind('next', function () { gotoPage(currentPage + 1); }); }); }; })(jQuery); $(document).ready(function () { // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL var autoscrolling = true; $('.infiniteCarousel').infiniteCarousel().mouseover(function () { autoscrolling = false; }).mouseout(function () { autoscrolling = true; }); setInterval(function () { if (autoscrolling) { $('.infiniteCarousel').trigger('next'); } }, 5000); });
zzzcw-template
trunk/d_red/images/pic_scroll.js
JavaScript
bsd
3,762
.fLeft { float:left; } .mTB10 { margin-top: 10px; margin-bottom: 10px; } .overflow { overflow:hidden; } #bigpic { margin-top: 8px; margin-bottom: 25px; } .jCarouselLite button { border:none; } .jCarouselLite { margin-bottom: 25px; } .imgScroll { background: url(../images/img_scroll.gif) no-repeat; height: 100px; width: 14px; background-color: transparent; } .prev { background-position: left center; } .next { background-position: -14px center; } .artContent { clear:both; font-size:14px; line-height:23px; overflow:hidden; padding:9px 0; color:#2f2f2f; } #bigpic img { max-width: 560px; max-height:450px; width:expression(this.width>560 ? '560px' : true); width:expression(this.height>450 ? '450px' : true); } ul.w25 li { float: left; width: 25%; }
zzzcw-template
trunk/d_red/style/scroll.css
CSS
bsd
830
/*** * DedeCMS v5.3 Style (grass green) * dedecms.com Author pigz 2008-11-17 17:35 **/ /*---------- base ---------*/ *{ padding:0px; margin:0px; } html{ background:#FFF; } body{ margin:0px auto; font:12px Verdana,Arial,Tahoma; } img{ border:none; } a{ color:#3366CC; text-decoration:none; } a:hover{ color:#F33; text-decoration:underline; } ul{ list-style:none; } input,select,button{ font-size:12px; vertical-align:middle; } .fc_03c{ color:#03C; } .fc_f30{ color:#F30; } /*---------- frame ---------*/ .header{ width:100%; margin:0px auto; padding-top:10px; clear:both; overflow:hidden; } .header .toplogo{ width:300px; height:60px; float:left; } .header .toplogo h1{ width:200px; height:56px; } .header .toplogo h1 a{ width:200px; height:56px; display:block; font-size:0px; text-indent:-200px; overflow:hidden; background:url(../images/top-logo.gif) center center no-repeat; } .header .searchform{ float:left; padding-top:12px; } .header .searchform .s1{ float:left; height:29px; line-height:25px; font-size:14px; color:#333333; font-weight:bold; margin-right:6px; } .header .searchform .s2{ float:left; } .header .searchform .s2 .sf-keyword{ padding:3px 5px; height:14px; line-height:17px; overflow:hidden; color:#777; } .header .searchform .s2 .sf-option{ font-size:14px; color:#444; } .header .searchform .s2 .sf-submit{ width:62px; height:23px; font-size:14px; line-height:18px; color:#333; letter-spacing:5px; margin-left:5px; margin-top:-2px; } .header .searchform .s3{ height:29px; float:left; margin-left:20px; line-height:29px; } .header .searchform .s3 a{ margin-right:10px; font-size:14px; } .msgbar{ height:27px; line-height:27px; border-top:1px solid #E4F0DF; border-bottom:1px solid #E4F0DF; font-size:14px; color:#666; } .msgbar p{ padding-left:22px; background:#F3FAF1; border-top:1px solid #FFF; border-bottom:1px solid #FFF; } .resultlist{ padding:2px 20px; } .resultlist h2{ display:none; } .item h3 .title{ font-size:14px; font-weight:normal; line-height:25px; text-decoration:underline; } .item h3 .title:hover{ text-decoration:none; } .item{ margin-top:16px; } .item .intro{ font-size:14px; line-height:19px; padding-left:2px; color:#777; } .item .info{ font-size:12px; line-height:26px; color:#080; } .item .info small{ font-size:12px; } .item .info span{ margin-right:10px; } .item .info a{ color:#444; } .advancedsearch{ width:500px; float:left; padding:30px 40px; } .advancedsearch input,.advancedsearch select,.advancedsearch button{ font-size:14px; margin-left:5px; } .advancedsearch input{ font-size:12px; padding:3px; } .advancedsearch .f1{ width:500px; clear:both; overflow:hidden; } .advancedsearch .f1 small,.advancedsearch .f2 small{ font-size:14px; width:80px; height:40px; float:left; text-align:right; line-height:25px; color:#666; } .advancedsearch .f1 span,.advancedsearch .f2 span{ height:40px; float:left; font-size:14px; } .advancedsearch .f2{ width:200px; float:left; } .othersearch{ height:31px; overflow:hidden; clear:both; line-height:31px; padding-left:16px; margin-top:16px; } .othersearch h2{ float:left; font-size:14px; } .othersearch ul{ float:left; } .othersearch ul li{ float:left; margin-left:10px; font-size:14px; line-height:33px; } .footer{ color:#999; text-align:right; border-top:1px solid #E5EFD6; margin-top:16px; padding:8px 10px; clear:both; overflow:hidden; } .footer .link{ text-align:center; padding:5px 0px; float:left; } .footer .link a{ margin:0px 5px; color:#666666; } .footer .powered{ font-size:10px; line-height:25px; } .footer .powered strong{ color:#690; } .footer .powered strong span{ color:#F93; } .footer .powered a:hover{ text-decoration:none; } .dede_pages{ height:33px; clear:both; overflow:hidden; background:#FAFAFA; margin-top:16px; } .dede_pages ul{ float:left; padding:6px 0px 0px 16px; } .dede_pages ul li{ float:left; font-family:Tahoma; line-height:17px; margin-right:6px; } .dede_pages ul li a{ float:left; padding:2px 4px 2px; color:#666; } .dede_pages ul li a:hover{ color:#690; text-decoration:none; padding:2px 4px 1px; background:#EEE; } .dede_pages ul li.thisclass a,.pagebox ul li.thisclass a:hover{ color:#F63; padding:2px 4px 1px; border-bottom:1px solid #F63; font-weight:bold; } .dede_pages .pageinfo{ float:right; line-height:21px; padding:7px 10px 3px 16px; color:#999; } .dede_pages .pageinfo strong{ color:#666; font-weight:normal; margin:0px 2px; } .center{ margin:0px auto; } .w960{ width:960px; /*position:relative;*/ } .footer_body{ text-align:center; }
zzzcw-template
trunk/d_red/style/search.css
CSS
bsd
4,971
.px10 {height:10px;clear:both;display:block;font-size:1px;overflow:hidden;} .stico{overflow:hidden;display:block!important;height:16px!important;line-height:16px!important;padding-left:20px!important;background:url(/images/share.gif) no-repeat left;cursor:pointer; margin:0 5px;} .stico:hover {text-decoration:underline; color:#f60;} .stico_renren{background-position:0px 0px} .stico_reddit{background-position:0px -16px} .stico_sina{background-position:0px -32px} .stico_shareto{background-position:0px -48px} .stico_qzone{background-position:0px -64px} .stico_myspace{background-position:0px -80px} .stico_live{background-position:0px -96px} .stico_qq{background-position:0px -112px} .stico_pdf{background-position:0px -128px} .stico_t139{background-position:0px -144px} .stico_xianguo{background-position:0px -160px} .stico_vivi{background-position:0px -176px} .stico_youdao{background-position:0px -192px} .stico_yahoo{background-position:0px -208px} .stico_twitter{background-position:0px -224px} .stico_taojianghu{background-position:0px -240px} .stico_t163{background-position:0px -256px} .stico_tsohu{background-position:0px -272px} .stico_tsina{background-position:0px -288px} .stico_leshou{background-position:0px -304px} .stico_delicious{background-position:0px -320px} .stico_csdn{background-position:0px -336px} .stico_douban9{background-position:0px -352px} .stico_digg{background-position:0px -368px} .stico_buzz{background-position:0px -384px} .stico_115{background-position:0px -400px} .stico_51{background-position:0px -416px} .stico_baidu{background-position:0px -432px} .stico_bai{background-position:0px -448px} .stico_douban{background-position:0px -464px} .stico_hexun{background-position:0px -480px} .stico_greader{background-position:0px -496px} .stico_kaixin001{background-position:0px -512px} .stico_hi{background-position:0px -528px} .stico_facebook{background-position:0px -544px} .stico_gmail{background-position:0px -560px} .stico_google{background-position:0px -576px} .stico_fav{background-position:0px -592px;height:17px;padding-left:19px;} .stico_itieba{background-position:0px -609px;height:18px;padding-left:20px;} .stico_copy {background-position:0px -631px; } .button_dike {background:url(/images/share.gif) no-repeat 4px -723px; padding-left:25px;} .st_button{float:left} .web2 {border:1px solid #e8e8e8; background: #fafafa; padding:5px 8px; height:20px; overflow:hidden;} .web_zi {float:left; width:70px; font-weight:normal;} .web_defo {display:block; height:18px; line-height:18px; float:left; width:475px; padding-top:2px;} .web_defo .stico_copy:hover {text-decoration:underline; color:#f60;} .web_an {width:16px; height:20px; float:right; padding:2px 0 0 0;} .web_more {display:block; width:400px; height:180px; background:#fff; border:2px solid #c2e1d5; position:absolute; z-index:3; margin:18px 0 0 -400px;_margin:18px 0 0 -399px; padding:10px;} .web_more b {display:inline; float:left; width:80px; font-weight:normal; height:16px; line-height:16px; margin:5px 0;} .web_more .st_button {float:none;} .web_on {border:2px solid #c2e1d5; border-bottom:none; z-index:4; position:absolute; background:url(/images/share.gif) no-repeat 6px -652px #fff;width:19px; height:22px; margin:-4px 0 0 -4px} .web_an li {display:block; width:15px; height:15px;overflow:hidden; border:1px solid #ddd; background:url(/images/share.gif) no-repeat 4px -654px #fff;} .web_an .web_over {display:none;} .over .web_over {display:block;}
zzzcw-template
trunk/d_red/style/share.css
CSS
bsd
3,642
a.c1{ padding:3px 8px 3px 8px; border:1px solid #BADAA1; background:url(../images/but_bg_sr.gif) 0 0 repeat-x; color:#428C5B; } a.c2{ color:#063; border:1px solid #9C0; background:url(../images/but_bg_sr.gif) 0px 0px repeat-x; } a.c1:hover{ color:#369; border:1px solid #8CADCE; background:url(../images/but_bg_sr.gif) 0px -44px repeat-x; } a img { border:none; }
zzzcw-template
trunk/d_red/style/picture.css
CSS
bsd
400
<?xml version="1.0" encoding="gb2312" ?> <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> {dede:freelist/} </urlset>
zzzcw-template
trunk/d_red/googlemap.htm
HTML
bsd
133
/** * jCarouselLite - jQuery plugin to navigate images/any content in a carousel style widget. * @requires jQuery v1.2 or above * * http://gmarwaha.com/jquery/jcarousellite/ * * Copyright (c) 2007 Ganeshji Marwaha (gmarwaha.com) * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html * * Version: 1.0.1 * Note: Requires jquery 1.2 or above from version 1.0.1 */ /** * Creates a carousel-style navigation widget for images/any-content from a simple HTML markup. * * The HTML markup that is used to build the carousel can be as simple as... * * <div class="carousel"> * <ul> * <li><img src="image/1.jpg" alt="1"></li> * <li><img src="image/2.jpg" alt="2"></li> * <li><img src="image/3.jpg" alt="3"></li> * </ul> * </div> * * As you can see, this snippet is nothing but a simple div containing an unordered list of images. * You don't need any special "class" attribute, or a special "css" file for this plugin. * I am using a class attribute just for the sake of explanation here. * * To navigate the elements of the carousel, you need some kind of navigation buttons. * For example, you will need a "previous" button to go backward, and a "next" button to go forward. * This need not be part of the carousel "div" itself. It can be any element in your page. * Lets assume that the following elements in your document can be used as next, and prev buttons... * * <button class="prev">&lt;&lt;</button> * <button class="next">&gt;&gt;</button> * * Now, all you need to do is call the carousel component on the div element that represents it, and pass in the * navigation buttons as options. * * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev" * }); * * That's it, you would have now converted your raw div, into a magnificient carousel. * * There are quite a few other options that you can use to customize it though. * Each will be explained with an example below. * * @param an options object - You can specify all the options shown below as an options object param. * * @option btnPrev, btnNext : string - no defaults * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev" * }); * @desc Creates a basic carousel. Clicking "btnPrev" navigates backwards and "btnNext" navigates forward. * * @option btnGo - array - no defaults * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * btnGo: [".0", ".1", ".2"] * }); * @desc If you don't want next and previous buttons for navigation, instead you prefer custom navigation based on * the item number within the carousel, you can use this option. Just supply an array of selectors for each element * in the carousel. The index of the array represents the index of the element. What i mean is, if the * first element in the array is ".0", it means that when the element represented by ".0" is clicked, the carousel * will slide to the first element and so on and so forth. This feature is very powerful. For example, i made a tabbed * interface out of it by making my navigation elements styled like tabs in css. As the carousel is capable of holding * any content, not just images, you can have a very simple tabbed navigation in minutes without using any other plugin. * The best part is that, the tab will "slide" based on the provided effect. :-) * * @option mouseWheel : boolean - default is false * @example * $(".carousel").jCarouselLite({ * mouseWheel: true * }); * @desc The carousel can also be navigated using the mouse wheel interface of a scroll mouse instead of using buttons. * To get this feature working, you have to do 2 things. First, you have to include the mouse-wheel plugin from brandon. * Second, you will have to set the option "mouseWheel" to true. That's it, now you will be able to navigate your carousel * using the mouse wheel. Using buttons and mouseWheel or not mutually exclusive. You can still have buttons for navigation * as well. They complement each other. To use both together, just supply the options required for both as shown below. * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * mouseWheel: true * }); * * @option auto : number - default is null, meaning autoscroll is disabled by default * @example * $(".carousel").jCarouselLite({ * auto: 800, * speed: 500 * }); * @desc You can make your carousel auto-navigate itself by specfying a millisecond value in this option. * The value you specify is the amount of time between 2 slides. The default is null, and that disables auto scrolling. * Specify this value and magically your carousel will start auto scrolling. * * @option speed : number - 200 is default * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * speed: 800 * }); * @desc Specifying a speed will slow-down or speed-up the sliding speed of your carousel. Try it out with * different speeds like 800, 600, 1500 etc. Providing 0, will remove the slide effect. * * @option easing : string - no easing effects by default. * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * easing: "bounceout" * }); * @desc You can specify any easing effect. Note: You need easing plugin for that. Once specified, * the carousel will slide based on the provided easing effect. * * @option vertical : boolean - default is false * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * vertical: true * }); * @desc Determines the direction of the carousel. true, means the carousel will display vertically. The next and * prev buttons will slide the items vertically as well. The default is false, which means that the carousel will * display horizontally. The next and prev items will slide the items from left-right in this case. * * @option circular : boolean - default is true * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * circular: false * }); * @desc Setting it to true enables circular navigation. This means, if you click "next" after you reach the last * element, you will automatically slide to the first element and vice versa. If you set circular to false, then * if you click on the "next" button after you reach the last element, you will stay in the last element itself * and similarly for "previous" button and first element. * * @option visible : number - default is 3 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * visible: 4 * }); * @desc This specifies the number of items visible at all times within the carousel. The default is 3. * You are even free to experiment with real numbers. Eg: "3.5" will have 3 items fully visible and the * last item half visible. This gives you the effect of showing the user that there are more images to the right. * * @option start : number - default is 0 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * start: 2 * }); * @desc You can specify from which item the carousel should start. Remember, the first item in the carousel * has a start of 0, and so on. * * @option scrool : number - default is 1 * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * scroll: 2 * }); * @desc The number of items that should scroll/slide when you click the next/prev navigation buttons. By * default, only one item is scrolled, but you may set it to any number. Eg: setting it to "2" will scroll * 2 items when you click the next or previous buttons. * * @option beforeStart, afterEnd : function - callbacks * @example * $(".carousel").jCarouselLite({ * btnNext: ".next", * btnPrev: ".prev", * beforeStart: function(a) { * alert("Before animation starts:" + a); * }, * afterEnd: function(a) { * alert("After animation ends:" + a); * } * }); * @desc If you wanted to do some logic in your page before the slide starts and after the slide ends, you can * register these 2 callbacks. The functions will be passed an argument that represents an array of elements that * are visible at the time of callback. * * * @cat Plugins/Image Gallery * @author Ganeshji Marwaha/ganeshread@gmail.com */ (function($) { // Compliant with jquery.noConflict() $.fn.jCarouselLite = function(o) { o = $.extend({ btnPrev: '.next', btnNext: '.prev', btnGo: null, mouseWheel: false, auto: null, speed: 200, easing: null, vertical: false, circular: true, visible: 4, start: 0, scroll: 1, beforeStart: null, afterEnd: null }, o || {}); return this.each(function() { // Returns the element collection. Chainable. var running = false, animCss=o.vertical?"top":"left", sizeCss=o.vertical?"height":"width"; var div = $(this), ul = $("ul", div), tLi = $("li", ul), tl = tLi.size(), v = o.visible; if(o.circular) { ul.prepend(tLi.slice(tl-v-1+1).clone()) .append(tLi.slice(0,v).clone()); o.start += v; } var li = $("li", ul), itemLength = li.size(), curr = o.start; div.css("visibility", "visible"); li.css({overflow: "hidden", float: o.vertical ? "none" : "left"}); ul.css({margin: "0", padding: "0", position: "relative", "list-style-type": "none", "z-index": "1"}); div.css({overflow: "hidden", position: "relative", "z-index": "2", left: "0px"}); var liSize = o.vertical ? height(li) : width(li); // Full li size(incl margin)-Used for animation var ulSize = liSize * itemLength; // size of full ul(total length, not just for the visible items) var divSize = liSize * v; // size of entire div(total length for just the visible items) li.css({width: li.width(), height: li.height()}); ul.css(sizeCss, ulSize+"px").css(animCss, -(curr*liSize)); div.css(sizeCss, divSize+"px"); // Width of the DIV. length of visible images if(o.btnPrev) $(o.btnPrev).click(function() { return go(curr-o.scroll); }); if(o.btnNext) $(o.btnNext).click(function() { return go(curr+o.scroll); }); if(o.btnGo) $.each(o.btnGo, function(i, val) { $(val).click(function() { return go(o.circular ? o.visible+i : i); }); }); if(o.mouseWheel && div.mousewheel) div.mousewheel(function(e, d) { return d>0 ? go(curr-o.scroll) : go(curr+o.scroll); }); if(o.auto) setInterval(function() { go(curr+o.scroll); }, o.auto+o.speed); function vis() { return li.slice(curr).slice(0,v); }; function go(to) { if(!running) { if(o.beforeStart) o.beforeStart.call(this, vis()); if(o.circular) { // If circular we are in first or last, then goto the other end if(to<=o.start-v-1) { // If first, then goto last ul.css(animCss, -((itemLength-(v*2))*liSize)+"px"); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be lesser depending on the number of elements. curr = to==o.start-v-1 ? itemLength-(v*2)-1 : itemLength-(v*2)-o.scroll; } else if(to>=itemLength-v+1) { // If last, then goto first ul.css(animCss, -( (v) * liSize ) + "px" ); // If "scroll" > 1, then the "to" might not be equal to the condition; it can be greater depending on the number of elements. curr = to==itemLength-v+1 ? v+1 : v+o.scroll; } else curr = to; } else { // If non-circular and to points to first or last, we just return. if(to<0 || to>itemLength-v) return; else curr = to; } // If neither overrides it, the curr will still be "to" and we can proceed. running = true; ul.animate( animCss == "left" ? { left: -(curr*liSize) } : { top: -(curr*liSize) } , o.speed, o.easing, function() { if(o.afterEnd) o.afterEnd.call(this, vis()); running = false; } ); // Disable buttons when the carousel reaches the last/first, and enable when not if(!o.circular) { $(o.btnPrev + "," + o.btnNext).removeClass("disabled"); $( (curr-o.scroll<0 && o.btnPrev) || (curr+o.scroll > itemLength-v && o.btnNext) || [] ).addClass("disabled"); } } return false; }; }); }; function css(el, prop) { return parseInt($.css(el[0], prop)) || 0; }; function width(el) { return el[0].offsetWidth + css(el, 'marginLeft') + css(el, 'marginRight'); }; function height(el) { return el[0].offsetHeight + css(el, 'marginTop') + css(el, 'marginBottom'); }; })(jQuery);
zzzcw-template
trunk/d_red/js/jcarousellite.js
JavaScript
bsd
14,320
(function () { $.fn.infiniteCarousel = function () { function repeat(str, n) { return new Array( n + 1 ).join(str); } return this.each(function () { // magic! var $wrapper = $('> div', this).css('overflow', 'hidden'), $slider = $wrapper.find('> ul').width(9999), $items = $slider.find('> li'), $single = $items.filter(':first') singleWidth = $single.outerWidth(), visible = Math.ceil($wrapper.innerWidth() / singleWidth), currentPage = 1, pages = Math.ceil($items.length / visible); /* TASKS */ // 1. pad the pages with empty element if required if ($items.length % visible != 0) { // pad $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible))); $items = $slider.find('> li'); } // 2. create the carousel padding on left and right (cloned) $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned')); $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned')); $items = $slider.find('> li'); // 3. reset scroll $wrapper.scrollLeft(singleWidth * visible); // 4. paging function function gotoPage(page) { var dir = page < currentPage ? -1 : 1, n = Math.abs(currentPage - page), left = singleWidth * dir * visible * n; $wrapper.filter(':not(:animated)').animate({ scrollLeft : '+=' + left }, 500, function () { // if page == last page - then reset position if (page > pages) { $wrapper.scrollLeft(singleWidth * visible); page = 1; } else if (page == 0) { page = pages; $wrapper.scrollLeft(singleWidth * visible * pages); } currentPage = page; }); } // 5. insert the back and forward link $wrapper.after('<a href="#" class="arrow back">&lt;</a><a href="#" class="arrow forward">&gt;</a>'); // 6. bind the back and forward links $('a.back', this).click(function () { gotoPage(currentPage - 1); return false; }); $('a.forward', this).click(function () { gotoPage(currentPage + 1); return false; }); $(this).bind('goto', function (event, page) { gotoPage(page); }); // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL $(this).bind('next', function () { gotoPage(currentPage + 1); }); }); }; })(jQuery); $(document).ready(function () { // THIS IS NEW CODE FOR THE AUTOMATIC INFINITE CAROUSEL var autoscrolling = true; if($('#imgscroll > li').length>0) { $('.infiniteCarousel').infiniteCarousel().mouseover(function () { autoscrolling = false; }).mouseout(function () { autoscrolling = true; }); setInterval(function () { if (autoscrolling) { $('.infiniteCarousel').trigger('next'); } }, 5000); } });
zzzcw-template
trunk/d_red/js/pic_scroll.js
JavaScript
bsd
3,854
package org.dna.mqtt.bechnmark; import java.net.URISyntaxException; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.Message; import org.fusesource.mqtt.client.QoS; import org.fusesource.mqtt.client.Topic; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class ConsumerBlocking implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(ConsumerBlocking.class); private String m_clientID; public ConsumerBlocking(String clientID) { m_clientID = clientID; } public void run() { MQTT mqtt = new MQTT(); try { // mqtt.setHost("test.mosquitto.org", 1883); mqtt.setHost("localhost", 1883); } catch (URISyntaxException ex) { LOG.error(null, ex); return; } mqtt.setClientId(m_clientID); BlockingConnection connection = mqtt.blockingConnection(); try { connection.connect(); } catch (Exception ex) { LOG.error("Cant't CONNECT to the server", ex); return; } try { Topic[] topics = {new Topic("/topic", QoS.AT_MOST_ONCE)}; byte[] qoses = connection.subscribe(topics); LOG.info("Subscribed to topic"); } catch (Exception ex) { LOG.error("Cant't PUSBLISH to the server", ex); return; } Message message = null; for (int i = 0; i < Producer.PUB_LOOP; i++) { try { message = connection.receive(); } catch (Exception ex) { LOG.error(null, ex); return; } byte[] payload = message.getPayload(); StringBuffer sb = new StringBuffer().append("Topic: ").append(message.getTopic()) .append(", payload: ").append(new String(payload)); LOG.info(sb.toString()); } try { LOG.info("Disconneting"); connection.disconnect(); LOG.info("Disconnected"); } catch (Exception ex) { LOG.error("Cant't DISCONNECT to the server", ex); } } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/ConsumerBlocking.java
Java
asf20
2,329
package org.dna.mqtt.bechnmark; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; /** * * Benchmark tool entry point. * * You could set the number of producers and consumers * * @author andrea */ public class Main { private static final int PUBLISHER_POOL_SIZE = 2; private static final int NUM_CONCURRENT_PRODS = 2; public static void main(String[] args) throws InterruptedException { ExecutorService consumerPool = Executors.newFixedThreadPool(PUBLISHER_POOL_SIZE); ExecutorService producerPool = Executors.newFixedThreadPool(PUBLISHER_POOL_SIZE); consumerPool.submit(new ConsumerFuture("Cons1")); //force wait to let the consumer be registered before the producer Thread.sleep(1000); int len = Producer.PUB_LOOP / NUM_CONCURRENT_PRODS; for (int i = 0; i < NUM_CONCURRENT_PRODS; i++) { producerPool.submit(new Producer("Prod " + i, i * len, len)); } consumerPool.shutdown(); producerPool.shutdown(); } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/Main.java
Java
asf20
1,083
package org.dna.mqtt.bechnmark.mina; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import static org.dna.mqtt.moquette.proto.messages.AbstractMessage.*; /** * * @author andrea */ public class MQTTDropHandler extends IoHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(MQTTDropHandler.class); @Override public void messageReceived(IoSession session, Object message) throws Exception { AbstractMessage msg = (AbstractMessage) message; try { switch (msg.getMessageType()) { case CONNECT: case SUBSCRIBE: case UNSUBSCRIBE: case PUBLISH: case PINGREQ: case DISCONNECT: LOG.debug("Received a message of type " + msg.getMessageType()); break; } } catch (Exception ex) { LOG.error("Bad error in processing the message", ex); } } @Override public void sessionIdle(IoSession session, IdleStatus status) { session.close(false); } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/mina/MQTTDropHandler.java
Java
asf20
1,326
package org.dna.mqtt.bechnmark.mina; import org.apache.mina.core.service.IoHandlerAdapter; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class DummyClientHandler extends IoHandlerAdapter { private static final Logger LOG = LoggerFactory.getLogger(DummyClientHandler.class); @Override public void messageReceived(IoSession session, Object message) throws Exception { AbstractMessage msg = (AbstractMessage) message; LOG.debug("Received a message of type " + msg.getMessageType()); } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/mina/DummyClientHandler.java
Java
asf20
685
package org.dna.mqtt.bechnmark.mina; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.core.RuntimeIoException; import org.apache.mina.core.future.ConnectFuture; import org.apache.mina.core.future.WriteFuture; import org.apache.mina.core.service.IoConnector; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.demux.DemuxingProtocolDecoder; import org.apache.mina.filter.codec.demux.DemuxingProtocolEncoder; import org.apache.mina.transport.socket.nio.NioSocketConnector; import org.dna.mqtt.commons.Constants; import org.dna.mqtt.moquette.MQTTException; import org.dna.mqtt.moquette.PublishException; import org.dna.mqtt.moquette.proto.*; import org.dna.mqtt.moquette.proto.messages.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class MQTTBulkClient { public int NUM_MESSAGES = 10000; private static final Logger LOG = LoggerFactory.getLogger(MQTTBulkClient.class); private String m_hostname; private int m_port = 1883; //internal management used for conversation with the server private IoConnector m_connector; private IoSession m_session; boolean m_withWaitWriteFuture = false; public static void main(String[] args) throws IOException { MQTTBulkClient client = new MQTTBulkClient(); if (args.length > 0) { client.m_hostname = args[0]; client.m_withWaitWriteFuture = Boolean.parseBoolean(args[1]); client.NUM_MESSAGES = Integer.parseInt(args[2]); } else { client.m_hostname = "localhost"; } client.init(); client.connect(); long start = System.currentTimeMillis(); for (int i = 0; i < client.NUM_MESSAGES; i++) { client.publish("/topic", "Hello world".getBytes(), AbstractMessage.QOSType.MOST_ONE, false); } long stop = System.currentTimeMillis(); LOG.info("Client sent " + client.NUM_MESSAGES + " in " + (stop - start) + " ms"); client.shutdown(); } protected void init() { DemuxingProtocolDecoder decoder = new DemuxingProtocolDecoder(); decoder.addMessageDecoder(new ConnAckDecoder()); decoder.addMessageDecoder(new SubAckDecoder()); decoder.addMessageDecoder(new UnsubAckDecoder()); decoder.addMessageDecoder(new PublishDecoder()); decoder.addMessageDecoder(new PubAckDecoder()); decoder.addMessageDecoder(new PingRespDecoder()); DemuxingProtocolEncoder encoder = new DemuxingProtocolEncoder(); encoder.addMessageEncoder(ConnectMessage.class, new ConnectEncoder()); encoder.addMessageEncoder(PublishMessage.class, new PublishEncoder()); encoder.addMessageEncoder(SubscribeMessage.class, new SubscribeEncoder()); encoder.addMessageEncoder(UnsubscribeMessage.class, new UnsubscribeEncoder()); encoder.addMessageEncoder(DisconnectMessage.class, new DisconnectEncoder()); encoder.addMessageEncoder(PingReqMessage.class, new PingReqEncoder()); m_connector = new NioSocketConnector(); // m_connector.getFilterChain().addLast("logger", new LoggingFilter()); m_connector.getFilterChain().addLast("codec", new ProtocolCodecFilter(encoder, decoder)); m_connector.setHandler(new DummyClientHandler()); m_connector.getSessionConfig().setReadBufferSize(2048); m_connector.getSessionConfig().setIdleTime(IdleStatus.BOTH_IDLE, Constants.DEFAULT_CONNECT_TIMEOUT); } public void connect() throws MQTTException { try { ConnectFuture future = m_connector.connect(new InetSocketAddress(m_hostname, m_port)); LOG.debug("Client waiting to connect to server"); future.awaitUninterruptibly(); m_session = future.getSession(); } catch (RuntimeIoException e) { LOG.debug("Failed to connect", e); } } public void publish(String topic, byte[] payload, AbstractMessage.QOSType qos, boolean retain) throws PublishException { PublishMessage msg = new PublishMessage(); msg.setRetainFlag(retain); msg.setTopicName(topic); msg.setPayload(payload); //QoS 0 case msg.setQos(AbstractMessage.QOSType.MOST_ONE); WriteFuture wf = m_session.write(msg); if (m_withWaitWriteFuture) { try { wf.await(); } catch (InterruptedException ex) { LOG.debug(null, ex); throw new PublishException(ex); } Throwable ex = wf.getException(); if (ex != null) { throw new PublishException(ex); } } } public void shutdown() { m_connector.dispose(); } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/mina/MQTTBulkClient.java
Java
asf20
4,972
package org.dna.mqtt.bechnmark.mina; import java.io.IOException; import java.net.InetSocketAddress; import org.apache.mina.core.service.IoAcceptor; import org.apache.mina.core.service.IoServiceStatistics; import org.apache.mina.core.session.IdleStatus; import org.apache.mina.core.session.IoSession; import org.apache.mina.filter.codec.ProtocolCodecFilter; import org.apache.mina.filter.codec.demux.DemuxingProtocolDecoder; import org.apache.mina.filter.codec.demux.DemuxingProtocolEncoder; import org.apache.mina.transport.socket.nio.NioSocketAcceptor; import org.dna.mqtt.moquette.proto.*; import org.dna.mqtt.moquette.proto.messages.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class MQTTDropServer { private static final Logger LOG = LoggerFactory.getLogger(MQTTDropServer.class); public static final int PORT = 1883; public static final int DEFAULT_CONNECT_TIMEOUT = 10; private IoAcceptor m_acceptor; public static void main(String[] args) throws IOException { new MQTTDropServer().startServer(); } protected void startServer() throws IOException { DemuxingProtocolDecoder decoder = new DemuxingProtocolDecoder(); decoder.addMessageDecoder(new ConnectDecoder()); decoder.addMessageDecoder(new PublishDecoder()); decoder.addMessageDecoder(new SubscribeDecoder()); decoder.addMessageDecoder(new UnsubscribeDecoder()); decoder.addMessageDecoder(new DisconnectDecoder()); decoder.addMessageDecoder(new PingReqDecoder()); DemuxingProtocolEncoder encoder = new DemuxingProtocolEncoder(); // encoder.addMessageEncoder(ConnectMessage.class, new ConnectEncoder()); encoder.addMessageEncoder(ConnAckMessage.class, new ConnAckEncoder()); encoder.addMessageEncoder(SubAckMessage.class, new SubAckEncoder()); encoder.addMessageEncoder(UnsubAckMessage.class, new UnsubAckEncoder()); encoder.addMessageEncoder(PubAckMessage.class, new PubAckEncoder()); encoder.addMessageEncoder(PublishMessage.class, new PublishEncoder()); encoder.addMessageEncoder(PingRespMessage.class, new PingRespEncoder()); m_acceptor = new NioSocketAcceptor(); m_acceptor.getFilterChain().addLast( "logger", new MQTTLoggingFilter("SERVER LOG") ); m_acceptor.getFilterChain().addLast( "codec", new ProtocolCodecFilter(encoder, decoder)); MQTTDropHandler handler = new MQTTDropHandler(); m_acceptor.setHandler(handler); ((NioSocketAcceptor)m_acceptor).setReuseAddress(true); ((NioSocketAcceptor)m_acceptor).getSessionConfig().setReuseAddress(true); m_acceptor.getSessionConfig().setReadBufferSize( 2048 ); m_acceptor.getSessionConfig().setIdleTime( IdleStatus.BOTH_IDLE, DEFAULT_CONNECT_TIMEOUT ); m_acceptor.getStatistics().setThroughputCalculationInterval(10); m_acceptor.getStatistics().updateThroughput(System.currentTimeMillis()); m_acceptor.bind( new InetSocketAddress(PORT) ); LOG.info("Server binded"); //Bind a shutdown hook Runtime.getRuntime().addShutdownHook(new Thread() { @Override public void run() { stopServer(); } }); } protected void stopServer() { LOG.info("Server stopping..."); //log statistics IoServiceStatistics statistics = m_acceptor.getStatistics(); statistics.updateThroughput(System.currentTimeMillis()); System.out.println(String.format("Total read bytes: %d, read throughtput: %f (b/s)", statistics.getReadBytes(), statistics.getReadBytesThroughput())); System.out.println(String.format("Total read msgs: %d, read msg throughtput: %f (msg/s)", statistics.getReadMessages(), statistics.getReadMessagesThroughput())); for(IoSession session: m_acceptor.getManagedSessions().values()) { if(session.isConnected() && !session.isClosing()){ session.close(false); } } m_acceptor.unbind(); m_acceptor.dispose(); LOG.info("Server stopped"); } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/mina/MQTTDropServer.java
Java
asf20
4,250
package org.dna.mqtt.bechnmark; import java.io.*; import java.net.URISyntaxException; import org.fusesource.mqtt.client.BlockingConnection; import org.fusesource.mqtt.client.MQTT; import org.fusesource.mqtt.client.QoS; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * This class only publish MQTT messages to a define topic with a certain frequency. * * * @author andrea */ public class Producer implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(Producer.class); private String m_clientID; public static final int PUB_LOOP = 100000; private int m_starIndex; private int m_len; private long m_startMillis; private static final String BENCHMARK_FILE = "producer_bechmark_%s.txt"; private PrintWriter m_benchMarkOut; private ByteArrayOutputStream m_baos = new ByteArrayOutputStream(1024 * 1024 * 2); public Producer(String clientID, int start, int len) { m_clientID = clientID; m_starIndex = start; m_len = len; m_benchMarkOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(m_baos))); m_benchMarkOut.println("msg ID, ns"); } public void run() { m_startMillis = System.currentTimeMillis(); MQTT mqtt = new MQTT(); try { // mqtt.setHost("test.mosquitto.org", 1883); mqtt.setHost("localhost", 1883); } catch (URISyntaxException ex) { LOG.error(null, ex); return; } mqtt.setClientId(m_clientID); BlockingConnection connection = mqtt.blockingConnection(); try { connection.connect(); } catch (Exception ex) { LOG.error("Cant't CONNECT to the server", ex); return; } long time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s connected in %d ms", Thread.currentThread().getName(), time)); LOG.info("Starting from index " + m_starIndex + " up to " + (m_starIndex + m_len)); m_startMillis = System.currentTimeMillis(); for (int i = m_starIndex; i < m_starIndex + m_len; i++) { try { // LOG.info("Publishing"); String payload = "Hello world MQTT!!" + i; connection.publish("/topic", payload.getBytes(), QoS.AT_MOST_ONCE, false); m_benchMarkOut.println(String.format("%d, %d", i, System.nanoTime())); } catch (Exception ex) { LOG.error("Cant't PUBLISH to the server", ex); return; } } time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s published %d messages in %d ms", Thread.currentThread().getName(), m_len, time)); m_startMillis = System.currentTimeMillis(); try { LOG.info("Disconneting"); connection.disconnect(); LOG.info("Disconnected"); } catch (Exception ex) { LOG.error("Cant't DISCONNECT to the server", ex); } time = System.currentTimeMillis() - m_startMillis; LOG.info(String.format("Producer %s disconnected in %d ms", Thread.currentThread().getName(), time)); m_benchMarkOut.flush(); m_benchMarkOut.close(); try { FileOutputStream fw = new FileOutputStream(String.format(BENCHMARK_FILE, m_clientID)); fw.write(m_baos.toByteArray()); fw.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/Producer.java
Java
asf20
3,683
package org.dna.mqtt.bechnmark; import java.io.*; import java.net.URISyntaxException; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.fusesource.mqtt.client.*; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * * @author andrea */ public class ConsumerFuture implements Runnable { private static final Logger LOG = LoggerFactory.getLogger(ConsumerFuture.class); private String m_clientID; private static final String BENCHMARK_FILE = "consumer_bechmark.txt"; private PrintWriter m_benchMarkOut; private ByteArrayOutputStream m_baos = new ByteArrayOutputStream(1024 * 1024); public ConsumerFuture(String clientID) { m_clientID = clientID; m_benchMarkOut = new PrintWriter(new BufferedWriter(new OutputStreamWriter(m_baos))); m_benchMarkOut.println("msg ID, ns"); } public void run() { MQTT mqtt = new MQTT(); try { // mqtt.setHost("test.mosquitto.org", 1883); mqtt.setHost("localhost", 1883); } catch (URISyntaxException ex) { LOG.error(null, ex); return; } mqtt.setClientId(m_clientID); FutureConnection connection = mqtt.futureConnection(); Future<Void> futConn = connection.connect(); try { futConn.await(); } catch (Exception ex) { LOG.error("Cant't CONNECT to the server", ex); return; } Topic[] topics = {new Topic("/topic", QoS.AT_MOST_ONCE)}; Future<byte[]> futSub = connection.subscribe(topics); try { byte[] qoses = futSub.await(); LOG.info("Subscribed to topic"); } catch (Exception ex) { LOG.error("Cant't PUSBLISH to the server", ex); return; } Pattern p = Pattern.compile(".*!!(\\d+)"); Message message = null; long startMillis = System.currentTimeMillis(); for (int i = 0; i < Producer.PUB_LOOP; i++) { Future<Message> futReceive = connection.receive(); try { message = futReceive.await(); String content = new String(message.getPayload()); //metrics part Matcher matcher = p.matcher(content); matcher.matches(); String numMsg = matcher.group(1); m_benchMarkOut.println(String.format("%s, %d", numMsg, System.nanoTime())); } catch (Exception ex) { LOG.error(null, ex); return; } byte[] payload = message.getPayload(); StringBuffer sb = new StringBuffer().append("Topic: ").append(message.getTopic()) .append(", payload: ").append(new String(payload)); LOG.debug(sb.toString()); } long time = System.currentTimeMillis() - startMillis; LOG.info(String.format("Consumer %s received %d messages in %d ms", Thread.currentThread().getName(), Producer.PUB_LOOP, time)); Future<Void> f4 = connection.disconnect(); try { LOG.info("Disconneting"); f4.await(); LOG.info("Disconnected"); } catch (Exception ex) { LOG.error("Cant't DISCONNECT to the server", ex); } m_benchMarkOut.close(); try { FileOutputStream fw = new FileOutputStream(BENCHMARK_FILE); fw.write(m_baos.toByteArray()); fw.close(); } catch (IOException e) { e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates. } } }
zzkzzk56-mqtt
benchmarking/src/main/java/org/dna/mqtt/bechnmark/ConsumerFuture.java
Java
asf20
3,716
package org.dna.mqtt.moquette.messaging.spi.impl; import org.dna.mqtt.moquette.messaging.spi.IMatchingCondition; import org.dna.mqtt.moquette.messaging.spi.IStorageService; import org.dna.mqtt.moquette.messaging.spi.impl.events.PublishEvent; import org.dna.mqtt.moquette.messaging.spi.impl.subscriptions.Subscription; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import java.util.Collection; import java.util.Collections; import java.util.List; /** */ public class DummyStorageService implements IStorageService { public void initStore() { //To change body of implemented methods use File | Settings | File Templates. } public void storeRetained(String topic, byte[] message, AbstractMessage.QOSType qos) { //To change body of implemented methods use File | Settings | File Templates. } public Collection<HawtDBStorageService.StoredMessage> searchMatching(IMatchingCondition condition) { return null; //To change body of implemented methods use File | Settings | File Templates. } public void storePublishForFuture(PublishEvent evt) { //To change body of implemented methods use File | Settings | File Templates. } public List<PublishEvent> retrivePersistedPublishes(String clientID) { return null; //To change body of implemented methods use File | Settings | File Templates. } public void cleanPersistedPublishes(String clientID) { //To change body of implemented methods use File | Settings | File Templates. } public void cleanInFlight(String msgID) { //To change body of implemented methods use File | Settings | File Templates. } public void addInFlight(PublishEvent evt, String publishKey) { //To change body of implemented methods use File | Settings | File Templates. } public void addNewSubscription(Subscription newSubscription, String clientID) { //To change body of implemented methods use File | Settings | File Templates. } public void removeAllSubscriptions(String clientID) { //To change body of implemented methods use File | Settings | File Templates. } public List<Subscription> retrieveAllSubscriptions() { return Collections.EMPTY_LIST; } public void close() { //To change body of implemented methods use File | Settings | File Templates. } public void persistQoS2Message(String publishKey, PublishEvent evt) { //To change body of implemented methods use File | Settings | File Templates. } public void removeQoS2Message(String publishKey) { //To change body of implemented methods use File | Settings | File Templates. } public PublishEvent retrieveQoS2Message(String publishKey) { return null; //To change body of implemented methods use File | Settings | File Templates. } }
zzkzzk56-mqtt
broker/src/test/java/org/dna/mqtt/moquette/messaging/impl/DummyStorageService.java
Java
asf20
2,877
package org.dna.mqtt.moquette.messaging.spi; import org.dna.mqtt.moquette.messaging.spi.impl.subscriptions.Subscription; import org.dna.mqtt.moquette.messaging.spi.impl.events.PublishEvent; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import static org.dna.mqtt.moquette.messaging.spi.impl.HawtDBStorageService.StoredMessage; import java.util.Collection; import java.util.List; /** * Defines the SPI to be implemented by a StorageService that handle persistence of messages and subscriptions. */ public interface IStorageService { /** * Used to initialize all persistent store structures * */ void initStore(); void storeRetained(String topic, byte[] message, AbstractMessage.QOSType qos); Collection<StoredMessage> searchMatching(IMatchingCondition condition); void storePublishForFuture(PublishEvent evt); List<PublishEvent> retrivePersistedPublishes(String clientID); void cleanPersistedPublishes(String clientID); void cleanInFlight(String msgID); void addInFlight(PublishEvent evt, String publishKey); void addNewSubscription(Subscription newSubscription, String clientID); void removeAllSubscriptions(String clientID); List<Subscription> retrieveAllSubscriptions(); void close(); void persistQoS2Message(String publishKey, PublishEvent evt); void removeQoS2Message(String publishKey); PublishEvent retrieveQoS2Message(String publishKey); }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/IStorageService.java
Java
asf20
1,456
package org.dna.mqtt.moquette.messaging.spi; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.messaging.spi.impl.events.MessagingEvent; import org.dna.mqtt.moquette.messaging.spi.impl.events.PubAckEvent; import org.dna.mqtt.moquette.proto.messages.AbstractMessage; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.ConnectMessage; /** * Interface to the underling messaging system used to publish, subscribe. * * @author andrea */ public interface IMessaging { void stop(); void disconnect(IoSession session); void republishStored(String clientID); void handleProtocolMessage(IoSession session, AbstractMessage msg); }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/IMessaging.java
Java
asf20
736
package org.dna.mqtt.moquette.messaging.spi; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.messaging.spi.impl.events.NotifyEvent; import org.dna.mqtt.moquette.messaging.spi.impl.events.PubAckEvent; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import org.dna.mqtt.moquette.proto.messages.PubAckMessage; /** * * @author andrea */ public interface INotifier { public void notify(NotifyEvent evt/*String clientId, String topic, QOSType qOSType, byte[] payload, boolean retained*/); public void disconnect(IoSession session); void sendPubAck(PubAckEvent evt); }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/INotifier.java
Java
asf20
632
package org.dna.mqtt.moquette.messaging.spi.impl.events; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; /** * TODO it's identical to PublishEvent * * @author andrea */ public class NotifyEvent extends MessagingEvent { private String m_clientId; private String m_topic; private QOSType m_qos; private byte[] m_message; private boolean m_retaned; //Optional attribute, available only fo QoS 1 and 2 int m_msgID; public NotifyEvent(String clientId, String topic, QOSType qos, byte[] message, boolean retained) { m_clientId = clientId; m_topic = topic; m_qos = qos; m_message = message; m_retaned = retained; } public NotifyEvent(String clientId, String topic, QOSType qos, byte[] message, boolean retained, int msgID) { this(clientId, topic, qos, message, retained); m_msgID = msgID; } public String getClientId() { return m_clientId; } public String getTopic() { return m_topic; } public QOSType getQos() { return m_qos; } public byte[] getMessage() { return m_message; } public boolean isRetained() { return m_retaned; } public int getMessageID() { return m_msgID; } @Override public String toString() { return "NotifyEvent{" + "m_retaned=" + m_retaned + ", m_msgID=" + m_msgID + ", m_qos=" + m_qos + ", m_topic='" + m_topic + '\'' + ", m_clientId='" + m_clientId + '\'' + '}'; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/NotifyEvent.java
Java
asf20
1,641
package org.dna.mqtt.moquette.messaging.spi.impl.events; /** * Used to send the ack message back to the client after a publish */ public class PubAckEvent extends MessagingEvent { int m_messageId; String m_clientID; public PubAckEvent(int messageID, String clientID) { m_messageId = messageID ; m_clientID = clientID; } public int getMessageId() { return m_messageId; } public String getClientID() { return m_clientID; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/PubAckEvent.java
Java
asf20
495
package org.dna.mqtt.moquette.messaging.spi.impl.events; /** *Event used to push work request on the SimpleMessaging. * * @author andrea */ public abstract class MessagingEvent { }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/MessagingEvent.java
Java
asf20
192
package org.dna.mqtt.moquette.messaging.spi.impl.events; /** */ public class InitEvent extends MessagingEvent { }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/InitEvent.java
Java
asf20
116
package org.dna.mqtt.moquette.messaging.spi.impl.events; /** * Poison pill to shutdown the event loop * * @author andrea */ public class StopEvent extends MessagingEvent { }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/StopEvent.java
Java
asf20
184
package org.dna.mqtt.moquette.messaging.spi.impl.events; import org.apache.mina.core.session.IoSession; import org.dna.mqtt.moquette.proto.messages.AbstractMessage.QOSType; import java.io.Serializable; /** * * @author andrea */ public class PublishEvent extends MessagingEvent implements Serializable { String m_topic; QOSType m_qos; byte[] m_message; boolean m_retain; String m_clientID; //Optional attribute, available only fo QoS 1 and 2 int m_msgID; transient IoSession m_session; public PublishEvent(String topic, QOSType qos, byte[] message, boolean retain, String clientID, IoSession session) { m_topic = topic; m_qos = qos; m_message = message; m_retain = retain; m_clientID = clientID; m_session = session; } public PublishEvent(String topic, QOSType qos, byte[] message, boolean retain, String clientID, int msgID, IoSession session) { this(topic, qos, message, retain, clientID, session); m_msgID = msgID; } public String getTopic() { return m_topic; } public QOSType getQos() { return m_qos; } public byte[] getMessage() { return m_message; } public boolean isRetain() { return m_retain; } public String getClientID() { return m_clientID; } public int getMessageID() { return m_msgID; } public IoSession getSession() { return m_session; } @Override public String toString() { return "PublishEvent{" + "m_msgID=" + m_msgID + ", m_clientID='" + m_clientID + '\'' + ", m_retain=" + m_retain + ", m_qos=" + m_qos + ", m_topic='" + m_topic + '\'' + '}'; } }
zzkzzk56-mqtt
broker/src/main/java/org/dna/mqtt/moquette/messaging/spi/impl/events/PublishEvent.java
Java
asf20
1,870