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 |
|---|---|---|---|---|---|
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.lang.reflect.Method;
/**
* Serializing an object for known object types.
*/
public class EnumSerializer extends AbstractSerializer {
private Method _name;
public EnumSerializer(Class cl)
{
// hessian/32b[12], hessian/3ab[23]
if (! cl.isEnum() && cl.getSuperclass().isEnum())
cl = cl.getSuperclass();
try {
_name = cl.getMethod("name", new Class[0]);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (out.addRef(obj))
return;
Class cl = obj.getClass();
if (! cl.isEnum() && cl.getSuperclass().isEnum())
cl = cl.getSuperclass();
String name = null;
try {
name = (String) _name.invoke(obj, (Object[]) null);
} catch (Exception e) {
throw new RuntimeException(e);
}
int ref = out.writeObjectBegin(cl.getName());
if (ref < -1) {
out.writeString("name");
out.writeString(name);
out.writeMapEnd();
}
else {
if (ref == -1) {
out.writeClassFieldLength(1);
out.writeString("name");
out.writeObjectBegin(cl.getName());
}
out.writeString(name);
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/EnumSerializer.java | Java | asf20 | 3,525 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import com.caucho.hessian.util.IdentityIntMap;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
/**
* Output stream for Hessian 2 requests.
*
* <p>Since HessianOutput does not depend on any classes other than
* in the JDK, it can be extracted independently into a smaller package.
*
* <p>HessianOutput is unbuffered, so any client needs to provide
* its own buffering.
*
* <pre>
* OutputStream os = ...; // from http connection
* Hessian2Output out = new Hessian11Output(os);
* String value;
*
* out.startCall("hello"); // start hello call
* out.writeString("arg1"); // write a string argument
* out.completeCall(); // complete the call
* </pre>
*/
public class Hessian2Output
extends AbstractHessianOutput
implements Hessian2Constants
{
// the output stream/
protected OutputStream _os;
// map of references
private IdentityIntMap _refs = new IdentityIntMap();
private boolean _isCloseStreamOnClose;
// map of classes
private HashMap _classRefs;
// map of types
private HashMap _typeRefs;
private final static int SIZE = 1024;
private final byte []_buffer = new byte[SIZE];
private int _offset;
private boolean _isStreaming;
/**
* Creates a new Hessian output stream, initialized with an
* underlying output stream.
*
* @param os the underlying output stream.
*/
public Hessian2Output(OutputStream os)
{
_os = os;
}
public void setCloseStreamOnClose(boolean isClose)
{
_isCloseStreamOnClose = isClose;
}
public boolean isCloseStreamOnClose()
{
return _isCloseStreamOnClose;
}
/**
* Writes a complete method call.
*/
public void call(String method, Object []args)
throws IOException
{
startCall(method);
if (args != null) {
for (int i = 0; i < args.length; i++)
writeObject(args[i]);
}
completeCall();
}
/**
* Starts the method call. Clients would use <code>startCall</code>
* instead of <code>call</code> if they wanted finer control over
* writing the arguments, or needed to write headers.
*
* <code><pre>
* c major minor
* m b16 b8 method-name
* </pre></code>
*
* @param method the method name to call.
*/
public void startCall(String method)
throws IOException
{
int offset = _offset;
if (SIZE < offset + 32) {
flush();
offset = 0;
}
byte []buffer = _buffer;
buffer[offset++] = (byte) 'c';
buffer[offset++] = (byte) 2;
buffer[offset++] = (byte) 0;
buffer[offset++] = (byte) 'm';
int len = method.length();
buffer[offset++] = (byte) (len >> 8);
buffer[offset++] = (byte) len;
_offset = offset;
printString(method, 0, len);
}
/**
* Writes the call tag. This would be followed by the
* headers and the method tag.
*
* <code><pre>
* c major minor
* </pre></code>
*
* @param method the method name to call.
*/
public void startCall()
throws IOException
{
flushIfFull();
int offset = _offset;
byte []buffer = _buffer;
buffer[offset++] = (byte) 'c';
buffer[offset++] = (byte) 2;
buffer[offset++] = (byte) 0;
}
/**
* Writes the streaming call tag. This would be followed by the
* headers and the method tag.
*
* <code><pre>
* C major minor
* </pre></code>
*
* @param method the method name to call.
*/
public void startStreamingCall()
throws IOException
{
flushIfFull();
int offset = _offset;
byte []buffer = _buffer;
buffer[offset++] = (byte) 'C';
buffer[offset++] = (byte) 2;
buffer[offset++] = (byte) 0;
}
/**
* Starts an envelope.
*
* <code><pre>
* E major minor
* m b16 b8 method-name
* </pre></code>
*
* @param method the method name to call.
*/
public void startEnvelope(String method)
throws IOException
{
int offset = _offset;
if (SIZE < offset + 32) {
flush();
offset = 0;
}
byte []buffer = _buffer;
buffer[offset++] = (byte) 'E';
buffer[offset++] = (byte) 2;
buffer[offset++] = (byte) 0;
buffer[offset++] = (byte) 'm';
int len = method.length();
buffer[offset++] = (byte) (len >> 8);
buffer[offset++] = (byte) len;
_offset = offset;
printString(method, 0, len);
}
/**
* Completes an envelope.
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeEnvelope()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'z';
}
/**
* Writes the method tag.
*
* <code><pre>
* m b16 b8 method-name
* </pre></code>
*
* @param method the method name to call.
*/
public void writeMethod(String method)
throws IOException
{
flushIfFull();
byte []buffer = _buffer;
int offset = _offset;
buffer[offset++] = (byte) 'm';
int len = method.length();
buffer[offset++] = (byte) (len >> 8);
buffer[offset++] = (byte) len;
_offset = offset;
printString(method, 0, len);
}
/**
* Completes.
*
* <code><pre>
* z
* </pre></code>
*/
public void completeCall()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'z';
}
/**
* Starts the reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* r
* </pre>
*/
public void startReply()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'r';
_buffer[_offset++] = (byte) 2;
_buffer[_offset++] = (byte) 0;
}
/**
* Starts the streaming reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* r
* </pre>
*/
public void startStreamingReply()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'R';
_buffer[_offset++] = (byte) 2;
_buffer[_offset++] = (byte) 0;
}
/**
* Completes reading the reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeReply()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'z';
}
/**
* Starts the message
*
* <p>A message contains several objects followed by a 'z'</p>
*
* <pre>
* p x02 x00
* </pre>
*/
public void startMessage()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'p';
_buffer[_offset++] = (byte) 2;
_buffer[_offset++] = (byte) 0;
}
/**
* Completes reading the message
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeMessage()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'z';
}
/**
* Writes a header name. The header value must immediately follow.
*
* <code><pre>
* H b16 b8 foo <em>value</em>
* </pre></code>
*/
public void writeHeader(String name)
throws IOException
{
int len = name.length();
flushIfFull();
_buffer[_offset++] = (byte) 'H';
_buffer[_offset++] = (byte) (len >> 8);
_buffer[_offset++] = (byte) (len);
printString(name);
}
/**
* Writes a fault. The fault will be written
* as a descriptive string followed by an object:
*
* <code><pre>
* f
* <string>code
* <string>the fault code
*
* <string>message
* <string>the fault mesage
*
* <string>detail
* mt\x00\xnnjavax.ejb.FinderException
* ...
* z
* z
* </pre></code>
*
* @param code the fault code, a three digit
*/
public void writeFault(String code, String message, Object detail)
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'f'
;
writeString("code");
writeString(code);
writeString("message");
writeString(message);
if (detail != null) {
writeString("detail");
writeObject(detail);
}
flushIfFull();
_buffer[_offset++] = (byte) ('z');
}
/**
* Writes any object to the output stream.
*/
public void writeObject(Object object)
throws IOException
{
if (object == null) {
writeNull();
return;
}
Serializer serializer;
serializer = findSerializerFactory().getSerializer(object.getClass());
serializer.writeObject(object, this);
}
/**
* Writes the list header to the stream. List writers will call
* <code>writeListBegin</code> followed by the list contents and then
* call <code>writeListEnd</code>.
*
* <code><pre>
* V
* t b16 b8 type
* l b32 b24 b16 b8
* </pre></code>
*/
public boolean writeListBegin(int length, String type)
throws IOException
{
flushIfFull();
if (_typeRefs != null) {
Integer refV = (Integer) _typeRefs.get(type);
if (refV != null) {
_buffer[_offset++] = (byte) (LIST_FIXED);
writeInt(refV.intValue());
writeInt(length);
return false;
}
}
_buffer[_offset++] = (byte) 'V';
writeType(type);
flushIfFull();
if (length < 0) {
}
else if (length < 0x100) {
_buffer[_offset++] = (byte) (LENGTH_BYTE);
_buffer[_offset++] = (byte) (length);
}
else {
_buffer[_offset++] = (byte) ('l');
_buffer[_offset++] = (byte) (length >> 24);
_buffer[_offset++] = (byte) (length >> 16);
_buffer[_offset++] = (byte) (length >> 8);
_buffer[_offset++] = (byte) (length);
}
return true;
}
/**
* Writes the tail of the list to the stream.
*/
public void writeListEnd()
throws IOException
{
flushIfFull();
_buffer[_offset++] = (byte) 'z';
}
/**
* Writes the map header to the stream. Map writers will call
* <code>writeMapBegin</code> followed by the map contents and then
* call <code>writeMapEnd</code>.
*
* <code><pre>
* Mt b16 b8 (<key> <value>)z
* </pre></code>
*/
public void writeMapBegin(String type)
throws IOException
{
if (SIZE < _offset + 32)
flush();
_buffer[_offset++] = 'M';
writeType(type);
}
/**
* Writes the tail of the map to the stream.
*/
public void writeMapEnd()
throws IOException
{
if (SIZE < _offset + 32)
flush();
_buffer[_offset++] = (byte) 'z';
}
/**
* Writes the object definition
*
* <code><pre>
* O t b16 b8 <string>*
* </pre></code>
*/
public int writeObjectBegin(String type)
throws IOException
{
if (_classRefs == null)
_classRefs = new HashMap();
Integer refV = (Integer) _classRefs.get(type);
if (refV != null) {
int ref = refV.intValue();
if (SIZE < _offset + 32)
flush();
_buffer[_offset++] = (byte) 'o';
writeInt(ref);
return ref;
}
else {
int ref = _classRefs.size();
_classRefs.put(type, Integer.valueOf(ref));
if (SIZE < _offset + 32)
flush();
_buffer[_offset++] = (byte) 'O';
writeString(type);
return -1;
}
}
/**
* Writes the tail of the class definition to the stream.
*/
public void writeClassFieldLength(int len)
throws IOException
{
writeInt(len);
}
/**
* Writes the tail of the object definition to the stream.
*/
public void writeObjectEnd()
throws IOException
{
}
/**
* Writes a remote object reference to the stream. The type is the
* type of the remote interface.
*
* <code><pre>
* 'r' 't' b16 b8 type url
* </pre></code>
*/
public void writeRemote(String type, String url)
throws IOException
{
if (SIZE < _offset + 32)
flush();
_buffer[_offset++] = (byte) 'r';
writeType(type);
if (SIZE < _offset + 32)
flush();
_buffer[_offset++] = (byte) 'S';
printLenString(url);
}
private void writeType(String type)
throws IOException
{
if (type == null)
return;
int len = type.length();
if (len == 0)
return;
if (_typeRefs == null)
_typeRefs = new HashMap();
Integer typeRefV = (Integer) _typeRefs.get(type);
if (typeRefV != null) {
int typeRef = typeRefV.intValue();
flushIfFull();
_buffer[_offset++] = (byte) TYPE_REF;
writeInt(typeRef);
}
else {
_typeRefs.put(type, Integer.valueOf(_typeRefs.size()));
if (SIZE < _offset + 32)
flush();
_buffer[_offset++] = (byte) 't';
printLenString(type);
}
}
/**
* Writes a boolean value to the stream. The boolean will be written
* with the following syntax:
*
* <code><pre>
* T
* F
* </pre></code>
*
* @param value the boolean value to write.
*/
public void writeBoolean(boolean value)
throws IOException
{
if (SIZE < _offset + 16)
flush();
if (value)
_buffer[_offset++] = (byte) 'T';
else
_buffer[_offset++] = (byte) 'F';
}
/**
* Writes an integer value to the stream. The integer will be written
* with the following syntax:
*
* <code><pre>
* I b32 b24 b16 b8
* </pre></code>
*
* @param value the integer value to write.
*/
public void writeInt(int value)
throws IOException
{
int offset = _offset;
byte []buffer = _buffer;
if (SIZE <= offset + 16) {
flush();
offset = 0;
}
if (INT_DIRECT_MIN <= value && value <= INT_DIRECT_MAX)
buffer[offset++] = (byte) (value + INT_ZERO);
else if (INT_BYTE_MIN <= value && value <= INT_BYTE_MAX) {
buffer[offset++] = (byte) (INT_BYTE_ZERO + (value >> 8));
buffer[offset++] = (byte) (value);
}
else if (INT_SHORT_MIN <= value && value <= INT_SHORT_MAX) {
buffer[offset++] = (byte) (INT_SHORT_ZERO + (value >> 16));
buffer[offset++] = (byte) (value >> 8);
buffer[offset++] = (byte) (value);
}
else {
buffer[offset++] = (byte) ('I');
buffer[offset++] = (byte) (value >> 24);
buffer[offset++] = (byte) (value >> 16);
buffer[offset++] = (byte) (value >> 8);
buffer[offset++] = (byte) (value);
}
_offset = offset;
}
/**
* Writes a long value to the stream. The long will be written
* with the following syntax:
*
* <code><pre>
* L b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param value the long value to write.
*/
public void writeLong(long value)
throws IOException
{
int offset = _offset;
byte []buffer = _buffer;
if (SIZE <= offset + 16) {
flush();
offset = 0;
}
if (LONG_DIRECT_MIN <= value && value <= LONG_DIRECT_MAX) {
buffer[offset++] = (byte) (value + LONG_ZERO);
}
else if (LONG_BYTE_MIN <= value && value <= LONG_BYTE_MAX) {
buffer[offset++] = (byte) (LONG_BYTE_ZERO + (value >> 8));
buffer[offset++] = (byte) (value);
}
else if (LONG_SHORT_MIN <= value && value <= LONG_SHORT_MAX) {
buffer[offset++] = (byte) (LONG_SHORT_ZERO + (value >> 16));
buffer[offset++] = (byte) (value >> 8);
buffer[offset++] = (byte) (value);
}
else if (-0x80000000L <= value && value <= 0x7fffffffL) {
buffer[offset + 0] = (byte) LONG_INT;
buffer[offset + 1] = (byte) (value >> 24);
buffer[offset + 2] = (byte) (value >> 16);
buffer[offset + 3] = (byte) (value >> 8);
buffer[offset + 4] = (byte) (value);
offset += 5;
}
else {
buffer[offset + 0] = (byte) 'L';
buffer[offset + 1] = (byte) (value >> 56);
buffer[offset + 2] = (byte) (value >> 48);
buffer[offset + 3] = (byte) (value >> 40);
buffer[offset + 4] = (byte) (value >> 32);
buffer[offset + 5] = (byte) (value >> 24);
buffer[offset + 6] = (byte) (value >> 16);
buffer[offset + 7] = (byte) (value >> 8);
buffer[offset + 8] = (byte) (value);
offset += 9;
}
_offset = offset;
}
/**
* Writes a double value to the stream. The double will be written
* with the following syntax:
*
* <code><pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param value the double value to write.
*/
public void writeDouble(double value)
throws IOException
{
int offset = _offset;
byte []buffer = _buffer;
if (SIZE <= offset + 16) {
flush();
offset = 0;
}
int intValue = (int) value;
if (intValue == value) {
if (intValue == 0) {
buffer[offset++] = (byte) DOUBLE_ZERO;
_offset = offset;
return;
}
else if (intValue == 1) {
buffer[offset++] = (byte) DOUBLE_ONE;
_offset = offset;
return;
}
else if (-0x80 <= intValue && intValue < 0x80) {
buffer[offset++] = (byte) DOUBLE_BYTE;
buffer[offset++] = (byte) intValue;
_offset = offset;
return;
}
else if (-0x8000 <= intValue && intValue < 0x8000) {
buffer[offset + 0] = (byte) DOUBLE_SHORT;
buffer[offset + 1] = (byte) (intValue >> 8);
buffer[offset + 2] = (byte) intValue;
_offset = offset + 3;
return;
}
}
float f = (float) value;
if (f == value) {
int bits = Float.floatToIntBits(f);
buffer[offset + 0] = (byte) (DOUBLE_FLOAT);
buffer[offset + 1] = (byte) (bits >> 24);
buffer[offset + 2] = (byte) (bits >> 16);
buffer[offset + 3] = (byte) (bits >> 8);
buffer[offset + 4] = (byte) (bits);
_offset = offset + 5;
return;
}
long bits = Double.doubleToLongBits(value);
buffer[offset + 0] = (byte) 'D';
buffer[offset + 1] = (byte) (bits >> 56);
buffer[offset + 2] = (byte) (bits >> 48);
buffer[offset + 3] = (byte) (bits >> 40);
buffer[offset + 4] = (byte) (bits >> 32);
buffer[offset + 5] = (byte) (bits >> 24);
buffer[offset + 6] = (byte) (bits >> 16);
buffer[offset + 7] = (byte) (bits >> 8);
buffer[offset + 8] = (byte) (bits);
_offset = offset + 9;
}
/**
* Writes a date to the stream.
*
* <code><pre>
* T b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param time the date in milliseconds from the epoch in UTC
*/
public void writeUTCDate(long time)
throws IOException
{
if (SIZE < _offset + 32)
flush();
int offset = _offset;
byte []buffer = _buffer;
buffer[offset++] = (byte) ('d');
buffer[offset++] = ((byte) (time >> 56));
buffer[offset++] = ((byte) (time >> 48));
buffer[offset++] = ((byte) (time >> 40));
buffer[offset++] = ((byte) (time >> 32));
buffer[offset++] = ((byte) (time >> 24));
buffer[offset++] = ((byte) (time >> 16));
buffer[offset++] = ((byte) (time >> 8));
buffer[offset++] = ((byte) (time));
_offset = offset;
}
/**
* Writes a null value to the stream.
* The null will be written with the following syntax
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeNull()
throws IOException
{
int offset = _offset;
byte []buffer = _buffer;
if (SIZE <= offset + 16) {
flush();
offset = 0;
}
buffer[offset++] = 'N';
_offset = offset;
}
/**
* Writes a string value to the stream using UTF-8 encoding.
* The string will be written with the following syntax:
*
* <code><pre>
* S b16 b8 string-value
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeString(String value)
throws IOException
{
int offset = _offset;
byte []buffer = _buffer;
if (SIZE <= offset + 16) {
flush();
offset = 0;
}
if (value == null) {
buffer[offset++] = (byte) 'N';
_offset = offset;
}
else {
int length = value.length();
int strOffset = 0;
while (length > 0x8000) {
int sublen = 0x8000;
offset = _offset;
if (SIZE <= offset + 16) {
flush();
offset = 0;
}
// chunk can't end in high surrogate
char tail = value.charAt(strOffset + sublen - 1);
if (0xd800 <= tail && tail <= 0xdbff)
sublen--;
buffer[offset + 0] = (byte) 's';
buffer[offset + 1] = (byte) (sublen >> 8);
buffer[offset + 2] = (byte) (sublen);
_offset = offset + 3;
printString(value, strOffset, sublen);
length -= sublen;
strOffset += sublen;
}
offset = _offset;
if (SIZE <= offset + 16) {
flush();
offset = 0;
}
if (length <= STRING_DIRECT_MAX) {
buffer[offset++] = (byte) (STRING_DIRECT + length);
}
else {
buffer[offset++] = (byte) ('S');
buffer[offset++] = (byte) (length >> 8);
buffer[offset++] = (byte) (length);
}
_offset = offset;
printString(value, strOffset, length);
}
}
/**
* Writes a string value to the stream using UTF-8 encoding.
* The string will be written with the following syntax:
*
* <code><pre>
* S b16 b8 string-value
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeString(char []buffer, int offset, int length)
throws IOException
{
if (buffer == null) {
if (SIZE < _offset + 16)
flush();
_buffer[_offset++] = (byte) ('N');
}
else {
while (length > 0x8000) {
int sublen = 0x8000;
if (SIZE < _offset + 16)
flush();
// chunk can't end in high surrogate
char tail = buffer[offset + sublen - 1];
if (0xd800 <= tail && tail <= 0xdbff)
sublen--;
_buffer[_offset++] = (byte) 's';
_buffer[_offset++] = (byte) (sublen >> 8);
_buffer[_offset++] = (byte) (sublen);
printString(buffer, offset, sublen);
length -= sublen;
offset += sublen;
}
if (SIZE < _offset + 16)
flush();
if (length <= STRING_DIRECT_MAX) {
_buffer[_offset++] = (byte) (STRING_DIRECT + length);
}
else {
_buffer[_offset++] = (byte) ('S');
_buffer[_offset++] = (byte) (length >> 8);
_buffer[_offset++] = (byte) (length);
}
printString(buffer, offset, length);
}
}
/**
* Writes a byte array to the stream.
* The array will be written with the following syntax:
*
* <code><pre>
* B b16 b18 bytes
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeBytes(byte []buffer)
throws IOException
{
if (buffer == null) {
if (SIZE < _offset + 16)
flush();
_buffer[_offset++] = 'N';
}
else
writeBytes(buffer, 0, buffer.length);
}
/**
* Writes a byte array to the stream.
* The array will be written with the following syntax:
*
* <code><pre>
* B b16 b18 bytes
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeBytes(byte []buffer, int offset, int length)
throws IOException
{
if (buffer == null) {
if (SIZE < _offset + 16)
flushBuffer();
_buffer[_offset++] = (byte) 'N';
}
else {
flush();
while (length > SIZE - _offset - 3) {
int sublen = SIZE - _offset - 3;
if (sublen < 16) {
flushBuffer();
sublen = SIZE - _offset - 3;
if (length < sublen)
sublen = length;
}
_buffer[_offset++] = (byte) 'b';
_buffer[_offset++] = (byte) (sublen >> 8);
_buffer[_offset++] = (byte) sublen;
System.arraycopy(buffer, offset, _buffer, _offset, sublen);
_offset += sublen;
length -= sublen;
offset += sublen;
}
if (SIZE < _offset + 16)
flushBuffer();
if (length < 0x10) {
_buffer[_offset++] = (byte) (BYTES_DIRECT + length);
}
else {
_buffer[_offset++] = (byte) 'B';
_buffer[_offset++] = (byte) (length >> 8);
_buffer[_offset++] = (byte) (length);
}
System.arraycopy(buffer, offset, _buffer, _offset, length);
_offset += length;
}
}
/**
* Writes a byte buffer to the stream.
*
* <code><pre>
* </pre></code>
*/
public void writeByteBufferStart()
throws IOException
{
}
/**
* Writes a byte buffer to the stream.
*
* <code><pre>
* b b16 b18 bytes
* </pre></code>
*/
public void writeByteBufferPart(byte []buffer, int offset, int length)
throws IOException
{
while (length > 0) {
int sublen = length;
if (0x8000 < sublen)
sublen = 0x8000;
flush(); // bypass buffer
_os.write('b');
_os.write(sublen >> 8);
_os.write(sublen);
_os.write(buffer, offset, sublen);
length -= sublen;
offset += sublen;
}
}
/**
* Writes a byte buffer to the stream.
*
* <code><pre>
* b b16 b18 bytes
* </pre></code>
*/
public void writeByteBufferEnd(byte []buffer, int offset, int length)
throws IOException
{
writeBytes(buffer, offset, length);
}
/**
* Returns an output stream to write binary data.
*/
public OutputStream getBytesOutputStream()
throws IOException
{
return new BytesOutputStream();
}
/**
* Writes a reference.
*
* <code><pre>
* R b32 b24 b16 b8
* </pre></code>
*
* @param value the integer value to write.
*/
public void writeRef(int value)
throws IOException
{
if (SIZE < _offset + 16)
flush();
if (value < 0x100) {
_buffer[_offset++] = (byte) (REF_BYTE);
_buffer[_offset++] = (byte) (value);
}
else if (value < 0x10000) {
_buffer[_offset++] = (byte) (REF_SHORT);
_buffer[_offset++] = (byte) (value >> 8);
_buffer[_offset++] = (byte) (value);
}
else {
_buffer[_offset++] = (byte) ('R');
_buffer[_offset++] = (byte) (value >> 24);
_buffer[_offset++] = (byte) (value >> 16);
_buffer[_offset++] = (byte) (value >> 8);
_buffer[_offset++] = (byte) (value);
}
}
/**
* If the object has already been written, just write its ref.
*
* @return true if we're writing a ref.
*/
public boolean addRef(Object object)
throws IOException
{
int ref = _refs.get(object);
if (ref >= 0) {
writeRef(ref);
return true;
}
else {
_refs.put(object, _refs.size());
return false;
}
}
/**
* Removes a reference.
*/
public boolean removeRef(Object obj)
throws IOException
{
if (_refs != null) {
_refs.remove(obj);
return true;
}
else
return false;
}
/**
* Replaces a reference from one object to another.
*/
public boolean replaceRef(Object oldRef, Object newRef)
throws IOException
{
Integer value = (Integer) _refs.remove(oldRef);
if (value != null) {
_refs.put(newRef, value);
return true;
}
else
return false;
}
/**
* Resets the references for streaming.
*/
public void resetReferences()
{
if (_refs != null)
_refs.clear();
}
/**
* Starts the streaming message
*
* <p>A streaming message starts with 'P'</p>
*
* <pre>
* P x02 x00
* </pre>
*/
public void writeStreamingObject(Object obj)
throws IOException
{
if (_refs != null)
_refs.clear();
flush();
_isStreaming = true;
_offset = 3;
writeObject(obj);
int len = _offset - 3;
_buffer[0] = (byte) 'P';
_buffer[1] = (byte) (len >> 8);
_buffer[2] = (byte) len;
_isStreaming = false;
flush();
}
/**
* Prints a string to the stream, encoded as UTF-8 with preceeding length
*
* @param v the string to print.
*/
public void printLenString(String v)
throws IOException
{
if (SIZE < _offset + 16)
flush();
if (v == null) {
_buffer[_offset++] = (byte) (0);
_buffer[_offset++] = (byte) (0);
}
else {
int len = v.length();
_buffer[_offset++] = (byte) (len >> 8);
_buffer[_offset++] = (byte) (len);
printString(v, 0, len);
}
}
/**
* Prints a string to the stream, encoded as UTF-8
*
* @param v the string to print.
*/
public void printString(String v)
throws IOException
{
printString(v, 0, v.length());
}
/**
* Prints a string to the stream, encoded as UTF-8
*
* @param v the string to print.
*/
public void printString(String v, int strOffset, int length)
throws IOException
{
int offset = _offset;
byte []buffer = _buffer;
for (int i = 0; i < length; i++) {
if (SIZE <= offset + 16) {
_offset = offset;
flush();
offset = 0;
}
char ch = v.charAt(i + strOffset);
if (ch < 0x80)
buffer[offset++] = (byte) (ch);
else if (ch < 0x800) {
buffer[offset++] = (byte) (0xc0 + ((ch >> 6) & 0x1f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
else {
buffer[offset++] = (byte) (0xe0 + ((ch >> 12) & 0xf));
buffer[offset++] = (byte) (0x80 + ((ch >> 6) & 0x3f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
}
_offset = offset;
}
/**
* Prints a string to the stream, encoded as UTF-8
*
* @param v the string to print.
*/
public void printString(char []v, int strOffset, int length)
throws IOException
{
int offset = _offset;
byte []buffer = _buffer;
for (int i = 0; i < length; i++) {
if (SIZE <= offset + 16) {
_offset = offset;
flush();
offset = 0;
}
char ch = v[i + strOffset];
if (ch < 0x80)
buffer[offset++] = (byte) (ch);
else if (ch < 0x800) {
buffer[offset++] = (byte) (0xc0 + ((ch >> 6) & 0x1f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
else {
buffer[offset++] = (byte) (0xe0 + ((ch >> 12) & 0xf));
buffer[offset++] = (byte) (0x80 + ((ch >> 6) & 0x3f));
buffer[offset++] = (byte) (0x80 + (ch & 0x3f));
}
}
_offset = offset;
}
private final void flushIfFull()
throws IOException
{
int offset = _offset;
if (SIZE < offset + 32) {
_offset = 0;
_os.write(_buffer, 0, offset);
}
}
public final void flush()
throws IOException
{
flushBuffer();
_os.flush();
}
public final void flushBuffer()
throws IOException
{
int offset = _offset;
if (! _isStreaming && offset > 0) {
_offset = 0;
_os.write(_buffer, 0, offset);
}
else if (_isStreaming && offset > 3) {
int len = offset - 3;
_buffer[0] = 'p';
_buffer[1] = (byte) (len >> 8);
_buffer[2] = (byte) len;
_offset = 3;
_os.write(_buffer, 0, offset);
}
}
public final void close()
throws IOException
{
flushBuffer();
OutputStream os = _os;
_os = null;
if (os != null) {
if (_isCloseStreamOnClose)
os.close();
}
}
class BytesOutputStream extends OutputStream {
private int _startOffset;
BytesOutputStream()
throws IOException
{
if (SIZE < _offset + 16) {
Hessian2Output.this.flush();
}
_startOffset = _offset;
_offset += 3; // skip 'b' xNN xNN
}
@Override
public void write(int ch)
throws IOException
{
if (SIZE <= _offset) {
int length = (_offset - _startOffset) - 3;
_buffer[_startOffset] = (byte) 'b';
_buffer[_startOffset + 1] = (byte) (length >> 8);
_buffer[_startOffset + 2] = (byte) (length);
Hessian2Output.this.flush();
_startOffset = _offset;
_offset += 3;
}
_buffer[_offset++] = (byte) ch;
}
@Override
public void write(byte []buffer, int offset, int length)
throws IOException
{
while (length > 0) {
int sublen = SIZE - _offset;
if (length < sublen)
sublen = length;
if (sublen > 0) {
System.arraycopy(buffer, offset, _buffer, _offset, sublen);
_offset += sublen;
}
length -= sublen;
offset += sublen;
if (SIZE <= _offset) {
int chunkLength = (_offset - _startOffset) - 3;
_buffer[_startOffset] = (byte) 'b';
_buffer[_startOffset + 1] = (byte) (chunkLength >> 8);
_buffer[_startOffset + 2] = (byte) (chunkLength);
Hessian2Output.this.flush();
_startOffset = _offset;
_offset += 3;
}
}
}
@Override
public void close()
throws IOException
{
int startOffset = _startOffset;
_startOffset = -1;
if (startOffset < 0)
return;
int length = (_offset - startOffset) - 3;
_buffer[startOffset] = (byte) 'B';
_buffer[startOffset + 1] = (byte) (length >> 8);
_buffer[startOffset + 2] = (byte) (length);
Hessian2Output.this.flush();
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/Hessian2Output.java | Java | asf20 | 35,695 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.InputStream;
/**
* Output stream for Hessian 2 streaming requests.
*/
public class Hessian2StreamingInput
{
private Hessian2Input _in;
/**
* Creates a new Hessian input stream, initialized with an
* underlying input stream.
*
* @param is the underlying output stream.
*/
public Hessian2StreamingInput(InputStream is)
{
_in = new Hessian2Input(new StreamingInputStream(is));
}
/**
* Read the next object
*/
public Object readObject()
throws IOException
{
return _in.readStreamingObject();
}
/**
* Close the output.
*/
public void close()
throws IOException
{
_in.close();
}
static class StreamingInputStream extends InputStream {
private InputStream _is;
private int _length;
StreamingInputStream(InputStream is)
{
_is = is;
}
public int read()
throws IOException
{
InputStream is = _is;
while (_length == 0) {
int code = is.read();
if (code < 0)
return -1;
else if (code != 'p' && code != 'P')
throw new HessianProtocolException("expected streaming packet at 0x"
+ Integer.toHexString(code & 0xff));
int d1 = is.read();
int d2 = is.read();
if (d2 < 0)
return -1;
_length = (d1 << 8) + d2;
}
_length--;
return is.read();
}
public int read(byte []buffer, int offset, int length)
throws IOException
{
InputStream is = _is;
while (_length == 0) {
int code = is.read();
if (code < 0)
return -1;
else if (code != 'p' && code != 'P') {
throw new HessianProtocolException("expected streaming packet at 0x"
+ Integer.toHexString(code & 0xff)
+ " (" + (char) code + ")");
}
int d1 = is.read();
int d2 = is.read();
if (d2 < 0)
return -1;
_length = (d1 << 8) + d2;
}
int sublen = _length;
if (length < sublen)
sublen = length;
sublen = is.read(buffer, offset, sublen);
if (sublen < 0)
return -1;
_length -= sublen;
return sublen;
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/Hessian2StreamingInput.java | Java | asf20 | 4,363 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.util.Locale;
/**
* Handle for a locale object.
*/
public class LocaleHandle implements java.io.Serializable, HessianHandle {
private String value;
public LocaleHandle(String locale)
{
this.value = locale;
}
private Object readResolve()
{
String s = this.value;
if (s == null)
return null;
int len = s.length();
char ch = ' ';
int i = 0;
for (;
i < len && ('a' <= (ch = s.charAt(i)) && ch <= 'z'
|| 'A' <= ch && ch <= 'Z'
|| '0' <= ch && ch <= '9');
i++) {
}
String language = s.substring(0, i);
String country = null;
String var = null;
if (ch == '-' || ch == '_') {
int head = ++i;
for (;
i < len && ('a' <= (ch = s.charAt(i)) && ch <= 'z'
|| 'A' <= ch && ch <= 'Z'
|| '0' <= ch && ch <= '9');
i++) {
}
country = s.substring(head, i);
}
if (ch == '-' || ch == '_') {
int head = ++i;
for (;
i < len && ('a' <= (ch = s.charAt(i)) && ch <= 'z'
|| 'A' <= ch && ch <= 'Z'
|| '0' <= ch && ch <= '9');
i++) {
}
var = s.substring(head, i);
}
if (var != null)
return new Locale(language, country, var);
else if (country != null)
return new Locale(language, country);
else
return new Locale(language);
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/LocaleHandle.java | Java | asf20 | 3,652 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.Enumeration;
/**
* Serializing a JDK 1.2 Enumeration.
*/
public class EnumerationSerializer extends AbstractSerializer {
private static EnumerationSerializer _serializer;
public static EnumerationSerializer create()
{
if (_serializer == null)
_serializer = new EnumerationSerializer();
return _serializer;
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
Enumeration iter = (Enumeration) obj;
boolean hasEnd = out.writeListBegin(-1, null);
while (iter.hasMoreElements()) {
Object value = iter.nextElement();
out.writeObject(value);
}
if (hasEnd)
out.writeListEnd();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/EnumerationSerializer.java | Java | asf20 | 3,001 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Exception during field reading.
*/
public class HessianFieldException extends HessianProtocolException {
/**
* Zero-arg constructor.
*/
public HessianFieldException()
{
}
/**
* Create the exception.
*/
public HessianFieldException(String message)
{
super(message);
}
/**
* Create the exception.
*/
public HessianFieldException(String message, Throwable cause)
{
super(message, cause);
}
/**
* Create the exception.
*/
public HessianFieldException(Throwable cause)
{
super(cause);
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianFieldException.java | Java | asf20 | 2,864 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.lang.reflect.Constructor;
/**
* Deserializing a string valued object
*/
public class StringValueDeserializer extends AbstractDeserializer {
private Class _cl;
private Constructor _constructor;
public StringValueDeserializer(Class cl)
{
try {
_cl = cl;
_constructor = cl.getConstructor(new Class[] { String.class });
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public Class getType()
{
return _cl;
}
public Object readMap(AbstractHessianInput in)
throws IOException
{
String value = null;
while (! in.isEnd()) {
String key = in.readString();
if (key.equals("value"))
value = in.readString();
else
in.readObject();
}
in.readMapEnd();
Object object = create(value);
in.addRef(object);
return object;
}
public Object readObject(AbstractHessianInput in, String []fieldNames)
throws IOException
{
String value = null;
for (int i = 0; i < fieldNames.length; i++) {
if ("value".equals(fieldNames[i]))
value = in.readString();
else
in.readObject();
}
Object object = create(value);
in.addRef(object);
return object;
}
private Object create(String value)
throws IOException
{
if (value == null)
throw new IOException(_cl.getName() + " expects name.");
try {
return _constructor.newInstance(new Object[] { value });
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/StringValueDeserializer.java | Java | asf20 | 3,839 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.*;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.logging.*;
/**
* Input stream for Hessian requests.
*
* <p>HessianInput is unbuffered, so any client needs to provide
* its own buffering.
*
* <pre>
* InputStream is = ...; // from http connection
* HessianInput in = new HessianInput(is);
* String value;
*
* in.startReply(); // read reply header
* value = in.readString(); // read string value
* in.completeReply(); // read reply footer
* </pre>
*/
public class Hessian2Input
extends AbstractHessianInput
implements Hessian2Constants
{
private static final Logger log
= Logger.getLogger(Hessian2Input.class.getName());
private static final double D_256 = 1.0 / 256.0;
private static final int END_OF_DATA = -2;
private static Field _detailMessageField;
private static final int SIZE = 256;
private static final int GAP = 16;
// factory for deserializing objects in the input stream
protected SerializerFactory _serializerFactory;
private static boolean _isCloseStreamOnClose;
protected ArrayList _refs;
protected ArrayList _classDefs;
protected ArrayList _types;
// the underlying input stream
private InputStream _is;
private final byte []_buffer = new byte[SIZE];
// a peek character
private int _offset;
private int _length;
// true for streaming data
private boolean _isStreaming;
// the method for a call
private String _method;
private Reader _chunkReader;
private InputStream _chunkInputStream;
private Throwable _replyFault;
private StringBuffer _sbuf = new StringBuffer();
// true if this is the last chunk
private boolean _isLastChunk;
// the chunk length
private int _chunkLength;
/**
* Creates a new Hessian input stream, initialized with an
* underlying input stream.
*
* @param is the underlying input stream.
*/
public Hessian2Input(InputStream is)
{
_is = is;
}
/**
* Sets the serializer factory.
*/
public void setSerializerFactory(SerializerFactory factory)
{
_serializerFactory = factory;
}
/**
* Gets the serializer factory.
*/
public SerializerFactory getSerializerFactory()
{
return _serializerFactory;
}
/**
* Gets the serializer factory, creating a default if necessary.
*/
public final SerializerFactory findSerializerFactory()
{
SerializerFactory factory = _serializerFactory;
if (factory == null)
_serializerFactory = factory = new SerializerFactory();
return factory;
}
public void setCloseStreamOnClose(boolean isClose)
{
_isCloseStreamOnClose = isClose;
}
public boolean isCloseStreamOnClose()
{
return _isCloseStreamOnClose;
}
/**
* Returns the calls method
*/
public String getMethod()
{
return _method;
}
/**
* Returns any reply fault.
*/
public Throwable getReplyFault()
{
return _replyFault;
}
/**
* Starts reading the call
*
* <pre>
* c major minor
* </pre>
*/
public int readCall()
throws IOException
{
int tag = read();
if (tag != 'c')
throw error("expected hessian call ('c') at " + codeName(tag));
int major = read();
int minor = read();
return (major << 16) + minor;
}
/**
* Starts reading the envelope
*
* <pre>
* E major minor
* </pre>
*/
public int readEnvelope()
throws IOException
{
int tag = read();
if (tag != 'E')
throw error("expected hessian Envelope ('E') at " + codeName(tag));
int major = read();
int minor = read();
return (major << 16) + minor;
}
/**
* Completes reading the envelope
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeEnvelope()
throws IOException
{
int tag = read();
if (tag != 'z')
error("expected end of envelope at " + codeName(tag));
}
/**
* Starts reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* m b16 b8 method
* </pre>
*/
public String readMethod()
throws IOException
{
int tag = read();
if (tag != 'm')
throw error("expected hessian method ('m') at " + codeName(tag));
int d1 = read();
int d2 = read();
_isLastChunk = true;
_chunkLength = d1 * 256 + d2;
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
_method = _sbuf.toString();
return _method;
}
/**
* Starts reading the call, including the headers.
*
* <p>The call expects the following protocol data
*
* <pre>
* c major minor
* m b16 b8 method
* </pre>
*/
public void startCall()
throws IOException
{
readCall();
while (readHeader() != null) {
readObject();
}
readMethod();
}
/**
* Completes reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeCall()
throws IOException
{
int tag = read();
if (tag == 'z') {
}
else if (tag < 0)
throw error("expected end of call ('z') at end of stream.");
else
throw error("expected end of call ('z') at " + codeName(tag) + ". Check method arguments and ensure method overloading is enabled if necessary");
}
/**
* Reads a reply as an object.
* If the reply has a fault, throws the exception.
*/
@Override
public Object readReply(Class expectedClass)
throws Throwable
{
int tag = read();
if (tag != 'r') {
StringBuilder sb = new StringBuilder();
sb.append((char) tag);
try {
int ch;
while ((ch = read()) >= 0) {
sb.append((char) ch);
}
} catch (IOException e) {
log.log(Level.FINE, e.toString(), e);
}
throw error("expected hessian reply at " + codeName(tag) + "\n"
+ sb);
}
int major = read();
int minor = read();
if (major > 2 || major == 2 && minor > 0)
throw error("Cannot understand Hessian " + major + "." + minor + " response");
tag = read();
if (tag == 'f')
throw prepareFault();
else {
if (tag >= 0)
_offset--;
Object value = readObject(expectedClass);
completeValueReply();
return value;
}
}
/**
* Starts reading the reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* r
* </pre>
*/
public void startReply()
throws Throwable
{
int tag = read();
if (tag != 'r') {
StringBuilder sb = new StringBuilder();
sb.append((char) tag);
try {
int ch;
while ((ch = read()) >= 0) {
sb.append((char) ch);
}
} catch (IOException e) {
log.log(Level.FINE, e.toString(), e);
}
throw error("expected hessian reply at " + codeName(tag) + "\n"
+ sb);
}
int major = read();
int minor = read();
if (major > 2 || major == 2 && minor > 0)
throw error("Cannot understand Hessian " + major + "." + minor + " response");
tag = read();
if (tag == 'f')
throw prepareFault();
else if (tag >= 0)
_offset--;
}
/**
* Prepares the fault.
*/
private Throwable prepareFault()
throws IOException
{
HashMap fault = readFault();
Object detail = fault.get("detail");
String message = (String) fault.get("message");
if (detail instanceof Throwable) {
_replyFault = (Throwable) detail;
if (message != null && _detailMessageField != null) {
try {
_detailMessageField.set(_replyFault, message);
} catch (Throwable e) {
}
}
return _replyFault;
}
else {
String code = (String) fault.get("code");
_replyFault = new HessianServiceException(message, code, detail);
return _replyFault;
}
}
/**
* Completes reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeReply()
throws IOException
{
int tag = read();
if (tag != 'z')
error("expected end of reply at " + codeName(tag));
}
/**
* Completes reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeValueReply()
throws IOException
{
int tag = read();
if (tag != 'z')
error("expected end of reply at " + codeName(tag));
}
/**
* Reads a header, returning null if there are no headers.
*
* <pre>
* H b16 b8 value
* </pre>
*/
public String readHeader()
throws IOException
{
int tag = read();
if (tag == 'H') {
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
}
if (tag >= 0)
_offset--;
return null;
}
/**
* Starts reading the message
*
* <pre>
* p major minor
* </pre>
*/
public int startMessage()
throws IOException
{
int tag = read();
if (tag == 'p')
_isStreaming = false;
else if (tag == 'P')
_isStreaming = true;
else
throw error("expected Hessian message ('p') at " + codeName(tag));
int major = read();
int minor = read();
return (major << 16) + minor;
}
/**
* Completes reading the message
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeMessage()
throws IOException
{
int tag = read();
if (tag != 'z')
error("expected end of message at " + codeName(tag));
}
/**
* Reads a null
*
* <pre>
* N
* </pre>
*/
public void readNull()
throws IOException
{
int tag = read();
switch (tag) {
case 'N': return;
default:
throw expect("null", tag);
}
}
/**
* Reads a boolean
*
* <pre>
* T
* F
* </pre>
*/
public boolean readBoolean()
throws IOException
{
int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
switch (tag) {
case 'T': return true;
case 'F': return false;
// direct integer
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
return tag != INT_ZERO;
// INT_BYTE = 0
case 0xc8:
return read() != 0;
// INT_BYTE != 0
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
read();
return true;
// INT_SHORT = 0
case 0xd4:
return (256 * read() + read()) != 0;
// INT_SHORT != 0
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd5: case 0xd6: case 0xd7:
read();
read();
return true;
case 'I': return
parseInt() != 0;
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
return tag != LONG_ZERO;
// LONG_BYTE = 0
case 0xf8:
return read() != 0;
// LONG_BYTE != 0
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
read();
return true;
// INT_SHORT = 0
case 0x3c:
return (256 * read() + read()) != 0;
// INT_SHORT != 0
case 0x38: case 0x39: case 0x3a: case 0x3b:
case 0x3d: case 0x3e: case 0x3f:
read();
read();
return true;
case LONG_INT:
return (0x1000000L * read()
+ 0x10000L * read()
+ 0x100 * read()
+ read()) != 0;
case 'L':
return parseLong() != 0;
case DOUBLE_ZERO:
return false;
case DOUBLE_ONE:
return true;
case DOUBLE_BYTE:
return read() != 0;
case DOUBLE_SHORT:
return (0x100 * read() + read()) != 0;
case DOUBLE_FLOAT:
{
int f = parseInt();
return Float.intBitsToFloat(f) != 0;
}
case 'D':
return parseDouble() != 0.0;
case 'N':
return false;
default:
throw expect("boolean", tag);
}
}
/**
* Reads a short
*
* <pre>
* I b32 b24 b16 b8
* </pre>
*/
public short readShort()
throws IOException
{
return (short) readInt();
}
/**
* Reads an integer
*
* <pre>
* I b32 b24 b16 b8
* </pre>
*/
public final int readInt()
throws IOException
{
//int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
int tag = read();
switch (tag) {
case 'N':
return 0;
case 'F':
return 0;
case 'T':
return 1;
// direct integer
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
return tag - INT_ZERO;
/* byte int */
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc8: case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
return ((tag - INT_BYTE_ZERO) << 8) + read();
/* short int */
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd4: case 0xd5: case 0xd6: case 0xd7:
return ((tag - INT_SHORT_ZERO) << 16) + 256 * read() + read();
case 'I':
case LONG_INT:
return ((read() << 24)
+ (read() << 16)
+ (read() << 8)
+ read());
// direct long
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
return tag - LONG_ZERO;
/* byte long */
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf8: case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
return ((tag - LONG_BYTE_ZERO) << 8) + read();
/* short long */
case 0x38: case 0x39: case 0x3a: case 0x3b:
case 0x3c: case 0x3d: case 0x3e: case 0x3f:
return ((tag - LONG_SHORT_ZERO) << 16) + 256 * read() + read();
case 'L':
return (int) parseLong();
case DOUBLE_ZERO:
return 0;
case DOUBLE_ONE:
return 1;
//case LONG_BYTE:
case DOUBLE_BYTE:
return (byte) (_offset < _length ? _buffer[_offset++] : read());
//case INT_SHORT:
//case LONG_SHORT:
case DOUBLE_SHORT:
return (short) (256 * read() + read());
case DOUBLE_FLOAT:
{
int f = parseInt();
return (int) Float.intBitsToFloat(f);
}
case 'D':
return (int) parseDouble();
default:
throw expect("integer", tag);
}
}
/**
* Reads a long
*
* <pre>
* L b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public long readLong()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return 0;
case 'F':
return 0;
case 'T':
return 1;
// direct integer
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
return tag - INT_ZERO;
/* byte int */
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc8: case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
return ((tag - INT_BYTE_ZERO) << 8) + read();
/* short int */
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd4: case 0xd5: case 0xd6: case 0xd7:
return ((tag - INT_SHORT_ZERO) << 16) + 256 * read() + read();
//case LONG_BYTE:
case DOUBLE_BYTE:
return (byte) (_offset < _length ? _buffer[_offset++] : read());
//case INT_SHORT:
//case LONG_SHORT:
case DOUBLE_SHORT:
return (short) (256 * read() + read());
case 'I':
case LONG_INT:
return parseInt();
// direct long
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
return tag - LONG_ZERO;
/* byte long */
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf8: case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
return ((tag - LONG_BYTE_ZERO) << 8) + read();
/* short long */
case 0x38: case 0x39: case 0x3a: case 0x3b:
case 0x3c: case 0x3d: case 0x3e: case 0x3f:
return ((tag - LONG_SHORT_ZERO) << 16) + 256 * read() + read();
case 'L':
return parseLong();
case DOUBLE_ZERO:
return 0;
case DOUBLE_ONE:
return 1;
case DOUBLE_FLOAT:
{
int f = parseInt();
return (long) Float.intBitsToFloat(f);
}
case 'D':
return (long) parseDouble();
default:
throw expect("long", tag);
}
}
/**
* Reads a float
*
* <pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public float readFloat()
throws IOException
{
return (float) readDouble();
}
/**
* Reads a double
*
* <pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public double readDouble()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return 0;
case 'F':
return 0;
case 'T':
return 1;
// direct integer
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
return tag - 0x90;
/* byte int */
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc8: case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
return ((tag - INT_BYTE_ZERO) << 8) + read();
/* short int */
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd4: case 0xd5: case 0xd6: case 0xd7:
return ((tag - INT_SHORT_ZERO) << 16) + 256 * read() + read();
case 'I':
case LONG_INT:
return parseInt();
// direct long
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
return tag - LONG_ZERO;
/* byte long */
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf8: case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
return ((tag - LONG_BYTE_ZERO) << 8) + read();
/* short long */
case 0x38: case 0x39: case 0x3a: case 0x3b:
case 0x3c: case 0x3d: case 0x3e: case 0x3f:
return ((tag - LONG_SHORT_ZERO) << 16) + 256 * read() + read();
case 'L':
return (double) parseLong();
case DOUBLE_ZERO:
return 0;
case DOUBLE_ONE:
return 1;
case DOUBLE_BYTE:
return (byte) (_offset < _length ? _buffer[_offset++] : read());
case DOUBLE_SHORT:
return (short) (256 * read() + read());
case DOUBLE_FLOAT:
{
int f = parseInt();
return Float.intBitsToFloat(f);
}
case 'D':
return parseDouble();
default:
throw expect("double", tag);
}
}
/**
* Reads a date.
*
* <pre>
* T b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public long readUTCDate()
throws IOException
{
int tag = read();
if (tag != 'd')
throw expect("date", tag);
long b64 = read();
long b56 = read();
long b48 = read();
long b40 = read();
long b32 = read();
long b24 = read();
long b16 = read();
long b8 = read();
return ((b64 << 56)
+ (b56 << 48)
+ (b48 << 40)
+ (b40 << 32)
+ (b32 << 24)
+ (b24 << 16)
+ (b16 << 8)
+ b8);
}
/**
* Reads a byte from the stream.
*/
public int readChar()
throws IOException
{
if (_chunkLength > 0) {
_chunkLength--;
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
int ch = parseUTF8Char();
return ch;
}
else if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
_chunkLength--;
int value = parseUTF8Char();
// special code so successive read byte won't
// be read as a single object.
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
return value;
default:
throw expect("char", tag);
}
}
/**
* Reads a byte array from the stream.
*/
public int readString(char []buffer, int offset, int length)
throws IOException
{
int readLength = 0;
if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
else if (_chunkLength == 0) {
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
break;
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
_isLastChunk = true;
_chunkLength = tag - 0x00;
break;
default:
throw expect("string", tag);
}
}
while (length > 0) {
if (_chunkLength > 0) {
buffer[offset++] = (char) parseUTF8Char();
_chunkLength--;
length--;
readLength++;
}
else if (_isLastChunk) {
if (readLength == 0)
return -1;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
else {
int tag = read();
switch (tag) {
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
break;
default:
throw expect("string", tag);
}
}
}
if (readLength == 0)
return -1;
else if (_chunkLength > 0 || ! _isLastChunk)
return readLength;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
/**
* Reads a string
*
* <pre>
* S b16 b8 string value
* </pre>
*/
public String readString()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'T':
return "true";
case 'F':
return "false";
// direct integer
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
return String.valueOf((tag - 0x90));
/* byte int */
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc8: case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
return String.valueOf(((tag - INT_BYTE_ZERO) << 8) + read());
/* short int */
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd4: case 0xd5: case 0xd6: case 0xd7:
return String.valueOf(((tag - INT_SHORT_ZERO) << 16)
+ 256 * read() + read());
case 'I':
case LONG_INT:
return String.valueOf(parseInt());
// direct long
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
return String.valueOf(tag - LONG_ZERO);
/* byte long */
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf8: case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
return String.valueOf(((tag - LONG_BYTE_ZERO) << 8) + read());
/* short long */
case 0x38: case 0x39: case 0x3a: case 0x3b:
case 0x3c: case 0x3d: case 0x3e: case 0x3f:
return String.valueOf(((tag - LONG_SHORT_ZERO) << 16)
+ 256 * read() + read());
case 'L':
return String.valueOf(parseLong());
case DOUBLE_ZERO:
return "0.0";
case DOUBLE_ONE:
return "1.0";
case DOUBLE_BYTE:
return String.valueOf((byte) (_offset < _length
? _buffer[_offset++]
: read()));
case DOUBLE_SHORT:
return String.valueOf(((short) (256 * read() + read())));
case DOUBLE_FLOAT:
{
int f = parseInt();
return String.valueOf(Float.intBitsToFloat(f));
}
case 'D':
return String.valueOf(parseDouble());
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
// 0-byte string
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
_isLastChunk = true;
_chunkLength = tag - 0x00;
_sbuf.setLength(0);
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
default:
throw expect("string", tag);
}
}
/**
* Reads an XML node.
*
* <pre>
* S b16 b8 string value
* </pre>
*/
public org.w3c.dom.Node readNode()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
throw error("XML is not supported");
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
_isLastChunk = true;
_chunkLength = tag - 0x00;
throw error("XML is not supported");
default:
throw expect("string", tag);
}
}
/**
* Reads a byte array
*
* <pre>
* B b16 b8 data value
* </pre>
*/
public byte []readBytes()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data;
while ((data = parseByte()) >= 0)
bos.write(data);
return bos.toByteArray();
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
_isLastChunk = true;
_chunkLength = tag - 0x20;
bos = new ByteArrayOutputStream();
while ((data = parseByte()) >= 0)
bos.write(data);
return bos.toByteArray();
default:
throw expect("bytes", tag);
}
}
/**
* Reads a byte from the stream.
*/
public int readByte()
throws IOException
{
if (_chunkLength > 0) {
_chunkLength--;
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
return read();
}
else if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
int value = parseByte();
// special code so successive read byte won't
// be read as a single object.
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
return value;
default:
throw expect("binary", tag);
}
}
/**
* Reads a byte array from the stream.
*/
public int readBytes(byte []buffer, int offset, int length)
throws IOException
{
int readLength = 0;
if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
else if (_chunkLength == 0) {
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
break;
default:
throw expect("binary", tag);
}
}
while (length > 0) {
if (_chunkLength > 0) {
buffer[offset++] = (byte) read();
_chunkLength--;
length--;
readLength++;
}
else if (_isLastChunk) {
if (readLength == 0)
return -1;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
else {
int tag = read();
switch (tag) {
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
break;
default:
throw expect("binary", tag);
}
}
}
if (readLength == 0)
return -1;
else if (_chunkLength > 0 || ! _isLastChunk)
return readLength;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
/**
* Reads a fault.
*/
private HashMap readFault()
throws IOException
{
HashMap map = new HashMap();
int code = read();
for (; code > 0 && code != 'z'; code = read()) {
_offset--;
Object key = readObject();
Object value = readObject();
if (key != null && value != null)
map.put(key, value);
}
if (code != 'z')
throw expect("fault", code);
return map;
}
/**
* Reads an object from the input stream with an expected type.
*/
public Object readObject(Class cl)
throws IOException
{
if (cl == null || cl == Object.class)
return readObject();
int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
switch (tag) {
case 'N':
return null;
case 'M':
{
String type = readType();
// hessian/3bb3
if ("".equals(type)) {
Deserializer reader;
reader = findSerializerFactory().getDeserializer(cl);
return reader.readMap(this);
}
else {
Deserializer reader;
reader = findSerializerFactory().getObjectDeserializer(type, cl);
return reader.readMap(this);
}
}
case 'O':
{
readObjectDefinition(cl);
return readObject(cl);
}
case 'o':
{
int ref = readInt();
int size = _classDefs.size();
if (ref < 0 || size <= ref)
throw new HessianProtocolException("'" + ref + "' is an unknown class definition");
ObjectDefinition def = (ObjectDefinition) _classDefs.get(ref);
return readObjectInstance(cl, def);
}
case 'V':
{
String type = readType();
int length = readLength();
Deserializer reader;
reader = findSerializerFactory().getListDeserializer(type, cl);
Object v = reader.readList(this, length);
return v;
}
case 'v':
{
int ref = readInt();
String type = (String) _types.get(ref);
int length = readInt();
Deserializer reader;
reader = findSerializerFactory().getListDeserializer(type, cl);
Object v = reader.readLengthList(this, length);
return v;
}
case 'R':
{
int ref = parseInt();
return _refs.get(ref);
}
case 'r':
{
String type = readType();
String url = readString();
return resolveRemote(type, url);
}
case REF_BYTE: {
int ref = read();
return _refs.get(ref);
}
case REF_SHORT: {
int ref = 256 * read() + read();
return _refs.get(ref);
}
}
if (tag >= 0)
_offset--;
// hessian/3b2i vs hessian/3406
// return readObject();
Object value = findSerializerFactory().getDeserializer(cl).readObject(this);
return value;
}
/**
* Reads an arbitrary object from the input stream when the type
* is unknown.
*/
public Object readObject()
throws IOException
{
int tag = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
switch (tag) {
case 'N':
return null;
case 'T':
return Boolean.valueOf(true);
case 'F':
return Boolean.valueOf(false);
// direct integer
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
return Integer.valueOf(tag - INT_ZERO);
/* byte int */
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc8: case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
return Integer.valueOf(((tag - INT_BYTE_ZERO) << 8) + read());
/* short int */
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd4: case 0xd5: case 0xd6: case 0xd7:
return Integer.valueOf(((tag - INT_SHORT_ZERO) << 16) + 256 * read() + read());
case 'I':
return Integer.valueOf(parseInt());
// direct long
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
return Long.valueOf(tag - LONG_ZERO);
/* byte long */
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf8: case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
return Long.valueOf(((tag - LONG_BYTE_ZERO) << 8) + read());
/* short long */
case 0x38: case 0x39: case 0x3a: case 0x3b:
case 0x3c: case 0x3d: case 0x3e: case 0x3f:
return Long.valueOf(((tag - LONG_SHORT_ZERO) << 16) + 256 * read() + read());
case LONG_INT:
return Long.valueOf(parseInt());
case 'L':
return Long.valueOf(parseLong());
case DOUBLE_ZERO:
return Double.valueOf(0);
case DOUBLE_ONE:
return Double.valueOf(1);
case DOUBLE_BYTE:
return Double.valueOf((byte) read());
case DOUBLE_SHORT:
return Double.valueOf((short) (256 * read() + read()));
case DOUBLE_FLOAT:
{
int f = parseInt();
return Double.valueOf(Float.intBitsToFloat(f));
}
case 'D':
return Double.valueOf(parseDouble());
case 'd':
return new Date(parseLong());
case 'x':
case 'X': {
_isLastChunk = tag == 'X';
_chunkLength = (read() << 8) + read();
return parseXML();
}
case 's':
case 'S': {
_isLastChunk = tag == 'S';
_chunkLength = (read() << 8) + read();
int data;
_sbuf.setLength(0);
while ((data = parseChar()) >= 0)
_sbuf.append((char) data);
return _sbuf.toString();
}
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
{
_isLastChunk = true;
_chunkLength = tag - 0x00;
int data;
_sbuf.setLength(0);
while ((data = parseChar()) >= 0)
_sbuf.append((char) data);
return _sbuf.toString();
}
case 'b':
case 'B': {
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
int data;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((data = parseByte()) >= 0)
bos.write(data);
return bos.toByteArray();
}
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
{
_isLastChunk = true;
int len = tag - 0x20;
_chunkLength = 0;
byte []data = new byte[len];
for (int i = 0; i < len; i++)
data[i] = (byte) read();
return data;
}
case 'V': {
String type = readType();
int length = readLength();
return findSerializerFactory().readList(this, length, type);
}
// direct lists
case 'v': {
int ref = readInt();
String type = (String) _types.get(ref);
int length = readInt();
Deserializer reader;
reader = findSerializerFactory().getObjectDeserializer(type, null);
return reader.readLengthList(this, length);
}
case 'M': {
String type = readType();
return findSerializerFactory().readMap(this, type);
}
case 'O': {
readObjectDefinition(null);
return readObject();
}
case 'o': {
int ref = readInt();
ObjectDefinition def = (ObjectDefinition) _classDefs.get(ref);
return readObjectInstance(null, def);
}
case 'R': {
int ref = parseInt();
return _refs.get(ref);
}
case REF_BYTE: {
int ref = read();
return _refs.get(ref);
}
case REF_SHORT: {
int ref = 256 * read() + read();
return _refs.get(ref);
}
case 'r': {
String type = readType();
String url = readString();
return resolveRemote(type, url);
}
default:
if (tag < 0)
throw new EOFException("readObject: unexpected end of file");
else
throw error("readObject: unknown code " + codeName(tag));
}
}
/**
* Reads an object definition:
*
* <pre>
* O string <int> (string)* <value>*
* </pre>
*/
private void readObjectDefinition(Class cl)
throws IOException
{
String type = readString();
int len = readInt();
String []fieldNames = new String[len];
for (int i = 0; i < len; i++)
fieldNames[i] = readString();
ObjectDefinition def = new ObjectDefinition(type, fieldNames);
if (_classDefs == null)
_classDefs = new ArrayList();
_classDefs.add(def);
}
private Object readObjectInstance(Class cl, ObjectDefinition def)
throws IOException
{
String type = def.getType();
String []fieldNames = def.getFieldNames();
if (cl != null) {
Deserializer reader;
reader = findSerializerFactory().getObjectDeserializer(type, cl);
return reader.readObject(this, fieldNames);
}
else {
return findSerializerFactory().readObject(this, type, fieldNames);
}
}
private String readLenString()
throws IOException
{
int len = readInt();
_isLastChunk = true;
_chunkLength = len;
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
}
private String readLenString(int len)
throws IOException
{
_isLastChunk = true;
_chunkLength = len;
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
}
/**
* Reads a remote object.
*/
public Object readRemote()
throws IOException
{
String type = readType();
String url = readString();
return resolveRemote(type, url);
}
/**
* Reads a reference.
*/
public Object readRef()
throws IOException
{
return _refs.get(parseInt());
}
/**
* Reads the start of a list.
*/
public int readListStart()
throws IOException
{
return read();
}
/**
* Reads the start of a list.
*/
public int readMapStart()
throws IOException
{
return read();
}
/**
* Returns true if this is the end of a list or a map.
*/
public boolean isEnd()
throws IOException
{
int code;
if (_offset < _length)
code = (_buffer[_offset] & 0xff);
else {
code = read();
if (code >= 0)
_offset--;
}
return (code < 0 || code == 'z');
}
/**
* Reads the end byte.
*/
public void readEnd()
throws IOException
{
int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
if (code == 'z')
return;
else if (code < 0)
throw error("unexpected end of file");
else
throw error("unknown code:" + codeName(code));
}
/**
* Reads the end byte.
*/
public void readMapEnd()
throws IOException
{
int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
if (code != 'z')
throw error("expected end of map ('z') at '" + codeName(code) + "'");
}
/**
* Reads the end byte.
*/
public void readListEnd()
throws IOException
{
int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
if (code != 'z')
throw error("expected end of list ('z') at '" + codeName(code) + "'");
}
/**
* Adds a list/map reference.
*/
public int addRef(Object ref)
{
if (_refs == null)
_refs = new ArrayList();
_refs.add(ref);
return _refs.size() - 1;
}
/**
* Adds a list/map reference.
*/
public void setRef(int i, Object ref)
{
_refs.set(i, ref);
}
/**
* Resets the references for streaming.
*/
public void resetReferences()
{
if (_refs != null)
_refs.clear();
}
public Object readStreamingObject()
throws IOException
{
if (_refs != null)
_refs.clear();
return readObject();
}
/**
* Resolves a remote object.
*/
public Object resolveRemote(String type, String url)
throws IOException
{
HessianRemoteResolver resolver = getRemoteResolver();
if (resolver != null)
return resolver.lookup(type, url);
else
return new HessianRemote(type, url);
}
/**
* Parses a type from the stream.
*
* <pre>
* t b16 b8
* </pre>
*/
public String readType()
throws IOException
{
int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
switch (code) {
case 't':
{
int len = 256 * read() + read();
String type = readLenString(len);
if (_types == null)
_types = new ArrayList();
_types.add(type);
return type;
}
case 'T':
{
int ref = readInt();
return (String) _types.get(ref);
}
case TYPE_REF:
{
int ref = readInt();
return (String) _types.get(ref);
}
default:
{
if (code >= 0)
_offset--;
return "";
}
}
}
/**
* Parses the length for an array
*
* <pre>
* l b32 b24 b16 b8
* </pre>
*/
public int readLength()
throws IOException
{
int code = read();
if (code == LENGTH_BYTE)
return read();
else if (code == 'l')
return parseInt();
else {
if (code >= 0)
_offset--;
return -1;
}
}
/**
* Parses a 32-bit integer value from the stream.
*
* <pre>
* b32 b24 b16 b8
* </pre>
*/
private int parseInt()
throws IOException
{
int offset = _offset;
if (offset + 3 < _length) {
byte []buffer = _buffer;
int b32 = buffer[offset + 0] & 0xff;
int b24 = buffer[offset + 1] & 0xff;
int b16 = buffer[offset + 2] & 0xff;
int b8 = buffer[offset + 3] & 0xff;
_offset = offset + 4;
return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8;
}
else {
int b32 = read();
int b24 = read();
int b16 = read();
int b8 = read();
return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8;
}
}
/**
* Parses a 64-bit long value from the stream.
*
* <pre>
* b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
private long parseLong()
throws IOException
{
long b64 = read();
long b56 = read();
long b48 = read();
long b40 = read();
long b32 = read();
long b24 = read();
long b16 = read();
long b8 = read();
return ((b64 << 56) +
(b56 << 48) +
(b48 << 40) +
(b40 << 32) +
(b32 << 24) +
(b24 << 16) +
(b16 << 8) +
b8);
}
/**
* Parses a 64-bit double value from the stream.
*
* <pre>
* b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
private double parseDouble()
throws IOException
{
long bits = parseLong();
return Double.longBitsToDouble(bits);
}
org.w3c.dom.Node parseXML()
throws IOException
{
throw new UnsupportedOperationException();
}
/**
* Reads a character from the underlying stream.
*/
private int parseChar()
throws IOException
{
while (_chunkLength <= 0) {
if (_isLastChunk)
return -1;
int code = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
switch (code) {
case 's':
case 'x':
_isLastChunk = false;
_chunkLength = (read() << 8) + read();
break;
case 'S':
case 'X':
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
break;
case 0x00: case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
_isLastChunk = true;
_chunkLength = code - 0x00;
break;
default:
throw expect("string", code);
}
}
_chunkLength--;
return parseUTF8Char();
}
/**
* Parses a single UTF8 character.
*/
private int parseUTF8Char()
throws IOException
{
int ch = _offset < _length ? (_buffer[_offset++] & 0xff) : read();
if (ch < 0x80)
return ch;
else if ((ch & 0xe0) == 0xc0) {
int ch1 = read();
int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f);
return v;
}
else if ((ch & 0xf0) == 0xe0) {
int ch1 = read();
int ch2 = read();
int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f);
return v;
}
else
throw error("bad utf-8 encoding at " + codeName(ch));
}
/**
* Reads a byte from the underlying stream.
*/
private int parseByte()
throws IOException
{
while (_chunkLength <= 0) {
if (_isLastChunk) {
return -1;
}
int code = read();
switch (code) {
case 'b':
_isLastChunk = false;
_chunkLength = (read() << 8) + read();
break;
case 'B':
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
break;
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
_isLastChunk = true;
_chunkLength = code - 0x20;
break;
default:
throw expect("byte[]", code);
}
}
_chunkLength--;
return read();
}
/**
* Reads bytes based on an input stream.
*/
public InputStream readInputStream()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
break;
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
_isLastChunk = true;
_chunkLength = tag - 0x20;
break;
default:
throw expect("binary", tag);
}
return new ReadInputStream();
}
/**
* Reads bytes from the underlying stream.
*/
int read(byte []buffer, int offset, int length)
throws IOException
{
int readLength = 0;
while (length > 0) {
while (_chunkLength <= 0) {
if (_isLastChunk)
return readLength == 0 ? -1 : readLength;
int code = read();
switch (code) {
case 'b':
_isLastChunk = false;
_chunkLength = (read() << 8) + read();
break;
case 'B':
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
break;
case 0x20: case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
_isLastChunk = true;
_chunkLength = code - 0x20;
break;
default:
throw expect("byte[]", code);
}
}
int sublen = _chunkLength;
if (length < sublen)
sublen = length;
if (_length <= _offset && ! readBuffer())
return -1;
if (_length - _offset < sublen)
sublen = _length - _offset;
System.arraycopy(_buffer, _offset, buffer, offset, sublen);
_offset += sublen;
offset += sublen;
readLength += sublen;
length -= sublen;
_chunkLength -= sublen;
}
return readLength;
}
/**
* Normally, shouldn't be called externally, but needed for QA, e.g.
* ejb/3b01.
*/
public final int read()
throws IOException
{
if (_length <= _offset && ! readBuffer())
return -1;
return _buffer[_offset++] & 0xff;
}
private final boolean readBuffer()
throws IOException
{
byte []buffer = _buffer;
int offset = _offset;
int length = _length;
if (offset < length) {
System.arraycopy(buffer, offset, buffer, 0, length - offset);
offset = length - offset;
}
else
offset = 0;
int len = _is.read(buffer, offset, SIZE - offset);
if (len <= 0) {
_length = offset;
_offset = 0;
return offset > 0;
}
_length = offset + len;
_offset = 0;
return true;
}
public Reader getReader()
{
return null;
}
protected IOException expect(String expect, int ch)
throws IOException
{
if (ch < 0)
return error("expected " + expect + " at end of file");
else {
_offset--;
try {
Object obj = readObject();
if (obj != null) {
return error("expected " + expect
+ " at 0x" + Integer.toHexString(ch & 0xff)
+ " " + obj.getClass().getName() + " (" + obj + ")");
}
else
return error("expected " + expect
+ " at 0x" + Integer.toHexString(ch & 0xff) + " null");
} catch (IOException e) {
log.log(Level.FINE, e.toString(), e);
return error("expected " + expect
+ " at 0x" + Integer.toHexString(ch & 0xff));
}
}
}
protected String codeName(int ch)
{
if (ch < 0)
return "end of file";
else
return "0x" + Integer.toHexString(ch & 0xff) + " (" + (char) + ch + ")";
}
protected IOException error(String message)
{
if (_method != null)
return new HessianProtocolException(_method + ": " + message);
else
return new HessianProtocolException(message);
}
public void close()
throws IOException
{
InputStream is = _is;
_is = null;
if (_isCloseStreamOnClose && is != null)
is.close();
}
class ReadInputStream extends InputStream {
boolean _isClosed = false;
public int read()
throws IOException
{
if (_isClosed)
return -1;
int ch = parseByte();
if (ch < 0)
_isClosed = true;
return ch;
}
public int read(byte []buffer, int offset, int length)
throws IOException
{
if (_isClosed)
return -1;
int len = Hessian2Input.this.read(buffer, offset, length);
if (len < 0)
_isClosed = true;
return len;
}
public void close()
throws IOException
{
while (read() >= 0) {
}
}
};
final static class ObjectDefinition {
private final String _type;
private final String []_fields;
ObjectDefinition(String type, String []fields)
{
_type = type;
_fields = fields;
}
String getType()
{
return _type;
}
String []getFieldNames()
{
return _fields;
}
}
static {
try {
_detailMessageField = Throwable.class.getDeclaredField("detailMessage");
_detailMessageField.setAccessible(true);
} catch (Throwable e) {
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/Hessian2Input.java | Java | asf20 | 60,937 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.HashMap;
/**
* Serializing an object for known object types.
*/
public class AbstractMapDeserializer extends AbstractDeserializer {
public Class getType()
{
return HashMap.class;
}
public Object readObject(AbstractHessianInput in)
throws IOException
{
Object obj = in.readObject();
if (obj != null)
throw error("expected map/object at " + obj.getClass().getName() + " (" + obj + ")");
else
throw error("expected map/object at null");
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/AbstractMapDeserializer.java | Java | asf20 | 2,803 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.InputStream;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
/**
* Input stream for Hessian requests, deserializing objects using the
* java.io.Serialization protocol.
*
* <p>HessianSerializerInput is unbuffered, so any client needs to provide
* its own buffering.
*
* <h3>Serialization</h3>
*
* <pre>
* InputStream is = new FileInputStream("test.xml");
* HessianOutput in = new HessianSerializerOutput(is);
*
* Object obj = in.readObject();
* is.close();
* </pre>
*
* <h3>Parsing a Hessian reply</h3>
*
* <pre>
* InputStream is = ...; // from http connection
* HessianInput in = new HessianSerializerInput(is);
* String value;
*
* in.startReply(); // read reply header
* value = in.readString(); // read string value
* in.completeReply(); // read reply footer
* </pre>
*/
public class HessianSerializerInput extends HessianInput {
/**
* Creates a new Hessian input stream, initialized with an
* underlying input stream.
*
* @param is the underlying input stream.
*/
public HessianSerializerInput(InputStream is)
{
super(is);
}
/**
* Creates an uninitialized Hessian input stream.
*/
public HessianSerializerInput()
{
}
/**
* Reads an object from the input stream. cl is known not to be
* a Map.
*/
protected Object readObjectImpl(Class cl)
throws IOException
{
try {
Object obj = cl.newInstance();
if (_refs == null)
_refs = new ArrayList();
_refs.add(obj);
HashMap fieldMap = getFieldMap(cl);
int code = read();
for (; code >= 0 && code != 'z'; code = read()) {
_peek = code;
Object key = readObject();
Field field = (Field) fieldMap.get(key);
if (field != null) {
Object value = readObject(field.getType());
field.set(obj, value);
}
else {
Object value = readObject();
}
}
if (code != 'z')
throw expect("map", code);
// if there's a readResolve method, call it
try {
Method method = cl.getMethod("readResolve", new Class[0]);
return method.invoke(obj, new Object[0]);
} catch (Exception e) {
}
return obj;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
/**
* Creates a map of the classes fields.
*/
protected HashMap getFieldMap(Class cl)
{
HashMap fieldMap = new HashMap();
for (; cl != null; cl = cl.getSuperclass()) {
Field []fields = cl.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (Modifier.isTransient(field.getModifiers()) ||
Modifier.isStatic(field.getModifiers()))
continue;
// XXX: could parameterize the handler to only deal with public
field.setAccessible(true);
fieldMap.put(field.getName(), field);
}
}
return fieldMap;
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianSerializerInput.java | Java | asf20 | 5,433 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
/**
* Input stream for Hessian requests.
*
* <p>HessianInput is unbuffered, so any client needs to provide
* its own buffering.
*
* <pre>
* InputStream is = ...; // from http connection
* HessianInput in = new HessianInput(is);
* String value;
*
* in.startReply(); // read reply header
* value = in.readString(); // read string value
* in.completeReply(); // read reply footer
* </pre>
*/
public class HessianInput extends AbstractHessianInput {
private static int END_OF_DATA = -2;
private static Field _detailMessageField;
// factory for deserializing objects in the input stream
protected SerializerFactory _serializerFactory;
protected ArrayList _refs;
// the underlying input stream
private InputStream _is;
// a peek character
protected int _peek = -1;
// the method for a call
private String _method;
private Reader _chunkReader;
private InputStream _chunkInputStream;
private Throwable _replyFault;
private StringBuffer _sbuf = new StringBuffer();
// true if this is the last chunk
private boolean _isLastChunk;
// the chunk length
private int _chunkLength;
/**
* Creates an uninitialized Hessian input stream.
*/
public HessianInput()
{
}
/**
* Creates a new Hessian input stream, initialized with an
* underlying input stream.
*
* @param is the underlying input stream.
*/
public HessianInput(InputStream is)
{
init(is);
}
/**
* Sets the serializer factory.
*/
public void setSerializerFactory(SerializerFactory factory)
{
_serializerFactory = factory;
}
/**
* Gets the serializer factory.
*/
public SerializerFactory getSerializerFactory()
{
return _serializerFactory;
}
/**
* Initialize the hessian stream with the underlying input stream.
*/
public void init(InputStream is)
{
_is = is;
_method = null;
_isLastChunk = true;
_chunkLength = 0;
_peek = -1;
_refs = null;
_replyFault = null;
if (_serializerFactory == null)
_serializerFactory = new SerializerFactory();
}
/**
* Returns the calls method
*/
public String getMethod()
{
return _method;
}
/**
* Returns any reply fault.
*/
public Throwable getReplyFault()
{
return _replyFault;
}
/**
* Starts reading the call
*
* <pre>
* c major minor
* </pre>
*/
public int readCall()
throws IOException
{
int tag = read();
if (tag != 'c')
throw error("expected hessian call ('c') at " + codeName(tag));
int major = read();
int minor = read();
return (major << 16) + minor;
}
/**
* For backward compatibility with HessianSkeleton
*/
public void skipOptionalCall()
throws IOException
{
int tag = read();
if (tag == 'c') {
read();
read();
}
else
_peek = tag;
}
/**
* Starts reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* m b16 b8 method
* </pre>
*/
public String readMethod()
throws IOException
{
int tag = read();
if (tag != 'm')
throw error("expected hessian method ('m') at " + codeName(tag));
int d1 = read();
int d2 = read();
_isLastChunk = true;
_chunkLength = d1 * 256 + d2;
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
_method = _sbuf.toString();
return _method;
}
/**
* Starts reading the call, including the headers.
*
* <p>The call expects the following protocol data
*
* <pre>
* c major minor
* m b16 b8 method
* </pre>
*/
public void startCall()
throws IOException
{
readCall();
while (readHeader() != null) {
readObject();
}
readMethod();
}
/**
* Completes reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeCall()
throws IOException
{
int tag = read();
if (tag == 'z') {
}
else
throw error("expected end of call ('z') at " + codeName(tag) + ". Check method arguments and ensure method overloading is enabled if necessary");
}
/**
* Reads a reply as an object.
* If the reply has a fault, throws the exception.
*/
public Object readReply(Class expectedClass)
throws Throwable
{
int tag = read();
if (tag != 'r')
error("expected hessian reply at " + codeName(tag));
int major = read();
int minor = read();
tag = read();
if (tag == 'f')
throw prepareFault();
else {
_peek = tag;
Object value = readObject(expectedClass);
completeValueReply();
return value;
}
}
/**
* Starts reading the reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* r
* </pre>
*/
public void startReply()
throws Throwable
{
int tag = read();
if (tag != 'r')
error("expected hessian reply at " + codeName(tag));
int major = read();
int minor = read();
tag = read();
if (tag == 'f')
throw prepareFault();
else
_peek = tag;
}
/**
* Prepares the fault.
*/
private Throwable prepareFault()
throws IOException
{
HashMap fault = readFault();
Object detail = fault.get("detail");
String message = (String) fault.get("message");
if (detail instanceof Throwable) {
_replyFault = (Throwable) detail;
if (message != null && _detailMessageField != null) {
try {
_detailMessageField.set(_replyFault, message);
} catch (Throwable e) {
}
}
return _replyFault;
}
else {
String code = (String) fault.get("code");
_replyFault = new HessianServiceException(message, code, detail);
return _replyFault;
}
}
/**
* Completes reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeReply()
throws IOException
{
int tag = read();
if (tag != 'z')
error("expected end of reply at " + codeName(tag));
}
/**
* Completes reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeValueReply()
throws IOException
{
int tag = read();
if (tag != 'z')
error("expected end of reply at " + codeName(tag));
}
/**
* Reads a header, returning null if there are no headers.
*
* <pre>
* H b16 b8 value
* </pre>
*/
public String readHeader()
throws IOException
{
int tag = read();
if (tag == 'H') {
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
}
_peek = tag;
return null;
}
/**
* Reads a null
*
* <pre>
* N
* </pre>
*/
public void readNull()
throws IOException
{
int tag = read();
switch (tag) {
case 'N': return;
default:
throw expect("null", tag);
}
}
/**
* Reads a boolean
*
* <pre>
* T
* F
* </pre>
*/
public boolean readBoolean()
throws IOException
{
int tag = read();
switch (tag) {
case 'T': return true;
case 'F': return false;
case 'I': return parseInt() == 0;
case 'L': return parseLong() == 0;
case 'D': return parseDouble() == 0.0;
case 'N': return false;
default:
throw expect("boolean", tag);
}
}
/**
* Reads a byte
*
* <pre>
* I b32 b24 b16 b8
* </pre>
*/
/*
public byte readByte()
throws IOException
{
return (byte) readInt();
}
*/
/**
* Reads a short
*
* <pre>
* I b32 b24 b16 b8
* </pre>
*/
public short readShort()
throws IOException
{
return (short) readInt();
}
/**
* Reads an integer
*
* <pre>
* I b32 b24 b16 b8
* </pre>
*/
public int readInt()
throws IOException
{
int tag = read();
switch (tag) {
case 'T': return 1;
case 'F': return 0;
case 'I': return parseInt();
case 'L': return (int) parseLong();
case 'D': return (int) parseDouble();
default:
throw expect("int", tag);
}
}
/**
* Reads a long
*
* <pre>
* L b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public long readLong()
throws IOException
{
int tag = read();
switch (tag) {
case 'T': return 1;
case 'F': return 0;
case 'I': return parseInt();
case 'L': return parseLong();
case 'D': return (long) parseDouble();
default:
throw expect("long", tag);
}
}
/**
* Reads a float
*
* <pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public float readFloat()
throws IOException
{
return (float) readDouble();
}
/**
* Reads a double
*
* <pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public double readDouble()
throws IOException
{
int tag = read();
switch (tag) {
case 'T': return 1;
case 'F': return 0;
case 'I': return parseInt();
case 'L': return (double) parseLong();
case 'D': return parseDouble();
default:
throw expect("long", tag);
}
}
/**
* Reads a date.
*
* <pre>
* T b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
public long readUTCDate()
throws IOException
{
int tag = read();
if (tag != 'd')
throw error("expected date at " + codeName(tag));
long b64 = read();
long b56 = read();
long b48 = read();
long b40 = read();
long b32 = read();
long b24 = read();
long b16 = read();
long b8 = read();
return ((b64 << 56) +
(b56 << 48) +
(b48 << 40) +
(b40 << 32) +
(b32 << 24) +
(b24 << 16) +
(b16 << 8) +
b8);
}
/**
* Reads a byte from the stream.
*/
public int readChar()
throws IOException
{
if (_chunkLength > 0) {
_chunkLength--;
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
int ch = parseUTF8Char();
return ch;
}
else if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
_chunkLength--;
int value = parseUTF8Char();
// special code so successive read byte won't
// be read as a single object.
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
return value;
default:
throw new IOException("expected 'S' at " + (char) tag);
}
}
/**
* Reads a byte array from the stream.
*/
public int readString(char []buffer, int offset, int length)
throws IOException
{
int readLength = 0;
if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
else if (_chunkLength == 0) {
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
break;
default:
throw new IOException("expected 'S' at " + (char) tag);
}
}
while (length > 0) {
if (_chunkLength > 0) {
buffer[offset++] = (char) parseUTF8Char();
_chunkLength--;
length--;
readLength++;
}
else if (_isLastChunk) {
if (readLength == 0)
return -1;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
else {
int tag = read();
switch (tag) {
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
break;
default:
throw new IOException("expected 'S' at " + (char) tag);
}
}
}
if (readLength == 0)
return -1;
else if (_chunkLength > 0 || ! _isLastChunk)
return readLength;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
/**
* Reads a string
*
* <pre>
* S b16 b8 string value
* </pre>
*/
public String readString()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'I':
return String.valueOf(parseInt());
case 'L':
return String.valueOf(parseLong());
case 'D':
return String.valueOf(parseDouble());
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
default:
throw expect("string", tag);
}
}
/**
* Reads an XML node.
*
* <pre>
* S b16 b8 string value
* </pre>
*/
public org.w3c.dom.Node readNode()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'S':
case 's':
case 'X':
case 'x':
_isLastChunk = tag == 'S' || tag == 'X';
_chunkLength = (read() << 8) + read();
throw error("Can't handle string in this context");
default:
throw expect("string", tag);
}
}
/**
* Reads a byte array
*
* <pre>
* B b16 b8 data value
* </pre>
*/
public byte []readBytes()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
int data;
while ((data = parseByte()) >= 0)
bos.write(data);
return bos.toByteArray();
default:
throw expect("bytes", tag);
}
}
/**
* Reads a byte from the stream.
*/
public int readByte()
throws IOException
{
if (_chunkLength > 0) {
_chunkLength--;
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
return read();
}
else if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
int value = parseByte();
// special code so successive read byte won't
// be read as a single object.
if (_chunkLength == 0 && _isLastChunk)
_chunkLength = END_OF_DATA;
return value;
default:
throw new IOException("expected 'B' at " + (char) tag);
}
}
/**
* Reads a byte array from the stream.
*/
public int readBytes(byte []buffer, int offset, int length)
throws IOException
{
int readLength = 0;
if (_chunkLength == END_OF_DATA) {
_chunkLength = 0;
return -1;
}
else if (_chunkLength == 0) {
int tag = read();
switch (tag) {
case 'N':
return -1;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
break;
default:
throw new IOException("expected 'B' at " + (char) tag);
}
}
while (length > 0) {
if (_chunkLength > 0) {
buffer[offset++] = (byte) read();
_chunkLength--;
length--;
readLength++;
}
else if (_isLastChunk) {
if (readLength == 0)
return -1;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
else {
int tag = read();
switch (tag) {
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
break;
default:
throw new IOException("expected 'B' at " + (char) tag);
}
}
}
if (readLength == 0)
return -1;
else if (_chunkLength > 0 || ! _isLastChunk)
return readLength;
else {
_chunkLength = END_OF_DATA;
return readLength;
}
}
/**
* Reads a fault.
*/
private HashMap readFault()
throws IOException
{
HashMap map = new HashMap();
int code = read();
for (; code > 0 && code != 'z'; code = read()) {
_peek = code;
Object key = readObject();
Object value = readObject();
if (key != null && value != null)
map.put(key, value);
}
if (code != 'z')
throw expect("fault", code);
return map;
}
/**
* Reads an object from the input stream with an expected type.
*/
public Object readObject(Class cl)
throws IOException
{
if (cl == null || cl == Object.class)
return readObject();
int tag = read();
switch (tag) {
case 'N':
return null;
case 'M':
{
String type = readType();
// hessian/3386
if ("".equals(type)) {
Deserializer reader;
reader = _serializerFactory.getDeserializer(cl);
return reader.readMap(this);
}
else {
Deserializer reader;
reader = _serializerFactory.getObjectDeserializer(type);
return reader.readMap(this);
}
}
case 'V':
{
String type = readType();
int length = readLength();
Deserializer reader;
reader = _serializerFactory.getObjectDeserializer(type);
if (cl != reader.getType() && cl.isAssignableFrom(reader.getType()))
return reader.readList(this, length);
reader = _serializerFactory.getDeserializer(cl);
Object v = reader.readList(this, length);
return v;
}
case 'R':
{
int ref = parseInt();
return _refs.get(ref);
}
case 'r':
{
String type = readType();
String url = readString();
return resolveRemote(type, url);
}
}
_peek = tag;
// hessian/332i vs hessian/3406
//return readObject();
Object value = _serializerFactory.getDeserializer(cl).readObject(this);
return value;
}
/**
* Reads an arbitrary object from the input stream when the type
* is unknown.
*/
public Object readObject()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'T':
return Boolean.valueOf(true);
case 'F':
return Boolean.valueOf(false);
case 'I':
return Integer.valueOf(parseInt());
case 'L':
return Long.valueOf(parseLong());
case 'D':
return Double.valueOf(parseDouble());
case 'd':
return new Date(parseLong());
case 'x':
case 'X': {
_isLastChunk = tag == 'X';
_chunkLength = (read() << 8) + read();
return parseXML();
}
case 's':
case 'S': {
_isLastChunk = tag == 'S';
_chunkLength = (read() << 8) + read();
int data;
_sbuf.setLength(0);
while ((data = parseChar()) >= 0)
_sbuf.append((char) data);
return _sbuf.toString();
}
case 'b':
case 'B': {
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
int data;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while ((data = parseByte()) >= 0)
bos.write(data);
return bos.toByteArray();
}
case 'V': {
String type = readType();
int length = readLength();
return _serializerFactory.readList(this, length, type);
}
case 'M': {
String type = readType();
return _serializerFactory.readMap(this, type);
}
case 'R': {
int ref = parseInt();
return _refs.get(ref);
}
case 'r': {
String type = readType();
String url = readString();
return resolveRemote(type, url);
}
default:
throw error("unknown code for readObject at " + codeName(tag));
}
}
/**
* Reads a remote object.
*/
public Object readRemote()
throws IOException
{
String type = readType();
String url = readString();
return resolveRemote(type, url);
}
/**
* Reads a reference.
*/
public Object readRef()
throws IOException
{
return _refs.get(parseInt());
}
/**
* Reads the start of a list.
*/
public int readListStart()
throws IOException
{
return read();
}
/**
* Reads the start of a list.
*/
public int readMapStart()
throws IOException
{
return read();
}
/**
* Returns true if this is the end of a list or a map.
*/
public boolean isEnd()
throws IOException
{
int code = read();
_peek = code;
return (code < 0 || code == 'z');
}
/**
* Reads the end byte.
*/
public void readEnd()
throws IOException
{
int code = read();
if (code != 'z')
throw error("unknown code at " + codeName(code));
}
/**
* Reads the end byte.
*/
public void readMapEnd()
throws IOException
{
int code = read();
if (code != 'z')
throw error("expected end of map ('z') at " + codeName(code));
}
/**
* Reads the end byte.
*/
public void readListEnd()
throws IOException
{
int code = read();
if (code != 'z')
throw error("expected end of list ('z') at " + codeName(code));
}
/**
* Adds a list/map reference.
*/
public int addRef(Object ref)
{
if (_refs == null)
_refs = new ArrayList();
_refs.add(ref);
return _refs.size() - 1;
}
/**
* Adds a list/map reference.
*/
public void setRef(int i, Object ref)
{
_refs.set(i, ref);
}
/**
* Resets the references for streaming.
*/
public void resetReferences()
{
if (_refs != null)
_refs.clear();
}
/**
* Resolves a remote object.
*/
public Object resolveRemote(String type, String url)
throws IOException
{
HessianRemoteResolver resolver = getRemoteResolver();
if (resolver != null)
return resolver.lookup(type, url);
else
return new HessianRemote(type, url);
}
/**
* Parses a type from the stream.
*
* <pre>
* t b16 b8
* </pre>
*/
public String readType()
throws IOException
{
int code = read();
if (code != 't') {
_peek = code;
return "";
}
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
_sbuf.setLength(0);
int ch;
while ((ch = parseChar()) >= 0)
_sbuf.append((char) ch);
return _sbuf.toString();
}
/**
* Parses the length for an array
*
* <pre>
* l b32 b24 b16 b8
* </pre>
*/
public int readLength()
throws IOException
{
int code = read();
if (code != 'l') {
_peek = code;
return -1;
}
return parseInt();
}
/**
* Parses a 32-bit integer value from the stream.
*
* <pre>
* b32 b24 b16 b8
* </pre>
*/
private int parseInt()
throws IOException
{
int b32 = read();
int b24 = read();
int b16 = read();
int b8 = read();
return (b32 << 24) + (b24 << 16) + (b16 << 8) + b8;
}
/**
* Parses a 64-bit long value from the stream.
*
* <pre>
* b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
private long parseLong()
throws IOException
{
long b64 = read();
long b56 = read();
long b48 = read();
long b40 = read();
long b32 = read();
long b24 = read();
long b16 = read();
long b8 = read();
return ((b64 << 56) +
(b56 << 48) +
(b48 << 40) +
(b40 << 32) +
(b32 << 24) +
(b24 << 16) +
(b16 << 8) +
b8);
}
/**
* Parses a 64-bit double value from the stream.
*
* <pre>
* b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
private double parseDouble()
throws IOException
{
long b64 = read();
long b56 = read();
long b48 = read();
long b40 = read();
long b32 = read();
long b24 = read();
long b16 = read();
long b8 = read();
long bits = ((b64 << 56) +
(b56 << 48) +
(b48 << 40) +
(b40 << 32) +
(b32 << 24) +
(b24 << 16) +
(b16 << 8) +
b8);
return Double.longBitsToDouble(bits);
}
org.w3c.dom.Node parseXML()
throws IOException
{
throw new UnsupportedOperationException();
}
/**
* Reads a character from the underlying stream.
*/
private int parseChar()
throws IOException
{
while (_chunkLength <= 0) {
if (_isLastChunk)
return -1;
int code = read();
switch (code) {
case 's':
case 'x':
_isLastChunk = false;
_chunkLength = (read() << 8) + read();
break;
case 'S':
case 'X':
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
break;
default:
throw expect("string", code);
}
}
_chunkLength--;
return parseUTF8Char();
}
/**
* Parses a single UTF8 character.
*/
private int parseUTF8Char()
throws IOException
{
int ch = read();
if (ch < 0x80)
return ch;
else if ((ch & 0xe0) == 0xc0) {
int ch1 = read();
int v = ((ch & 0x1f) << 6) + (ch1 & 0x3f);
return v;
}
else if ((ch & 0xf0) == 0xe0) {
int ch1 = read();
int ch2 = read();
int v = ((ch & 0x0f) << 12) + ((ch1 & 0x3f) << 6) + (ch2 & 0x3f);
return v;
}
else
throw error("bad utf-8 encoding at " + codeName(ch));
}
/**
* Reads a byte from the underlying stream.
*/
private int parseByte()
throws IOException
{
while (_chunkLength <= 0) {
if (_isLastChunk) {
return -1;
}
int code = read();
switch (code) {
case 'b':
_isLastChunk = false;
_chunkLength = (read() << 8) + read();
break;
case 'B':
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
break;
default:
throw expect("byte[]", code);
}
}
_chunkLength--;
return read();
}
/**
* Reads bytes based on an input stream.
*/
public InputStream readInputStream()
throws IOException
{
int tag = read();
switch (tag) {
case 'N':
return null;
case 'B':
case 'b':
_isLastChunk = tag == 'B';
_chunkLength = (read() << 8) + read();
break;
default:
throw expect("inputStream", tag);
}
return new InputStream() {
boolean _isClosed = false;
public int read()
throws IOException
{
if (_isClosed || _is == null)
return -1;
int ch = parseByte();
if (ch < 0)
_isClosed = true;
return ch;
}
public int read(byte []buffer, int offset, int length)
throws IOException
{
if (_isClosed || _is == null)
return -1;
int len = HessianInput.this.read(buffer, offset, length);
if (len < 0)
_isClosed = true;
return len;
}
public void close()
throws IOException
{
while (read() >= 0) {
}
_isClosed = true;
}
};
}
/**
* Reads bytes from the underlying stream.
*/
int read(byte []buffer, int offset, int length)
throws IOException
{
int readLength = 0;
while (length > 0) {
while (_chunkLength <= 0) {
if (_isLastChunk)
return readLength == 0 ? -1 : readLength;
int code = read();
switch (code) {
case 'b':
_isLastChunk = false;
_chunkLength = (read() << 8) + read();
break;
case 'B':
_isLastChunk = true;
_chunkLength = (read() << 8) + read();
break;
default:
throw expect("byte[]", code);
}
}
int sublen = _chunkLength;
if (length < sublen)
sublen = length;
sublen = _is.read(buffer, offset, sublen);
offset += sublen;
readLength += sublen;
length -= sublen;
_chunkLength -= sublen;
}
return readLength;
}
final int read()
throws IOException
{
if (_peek >= 0) {
int value = _peek;
_peek = -1;
return value;
}
int ch = _is.read();
return ch;
}
public void close()
{
_is = null;
}
public Reader getReader()
{
return null;
}
protected IOException expect(String expect, int ch)
{
return error("expected " + expect + " at " + codeName(ch));
}
protected String codeName(int ch)
{
if (ch < 0)
return "end of file";
else
return "0x" + Integer.toHexString(ch & 0xff) + " (" + (char) + ch + ")";
}
protected IOException error(String message)
{
if (_method != null)
return new HessianProtocolException(_method + ": " + message);
else
return new HessianProtocolException(message);
}
static {
try {
_detailMessageField = Throwable.class.getDeclaredField("detailMessage");
_detailMessageField.setAccessible(true);
} catch (Throwable e) {
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianInput.java | Java | asf20 | 32,299 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.Date;
/**
* Serializing an object for known object types.
*/
public class BasicSerializer extends AbstractSerializer {
public static final int NULL = 0;
public static final int BOOLEAN = NULL + 1;
public static final int BYTE = BOOLEAN + 1;
public static final int SHORT = BYTE + 1;
public static final int INTEGER = SHORT + 1;
public static final int LONG = INTEGER + 1;
public static final int FLOAT = LONG + 1;
public static final int DOUBLE = FLOAT + 1;
public static final int CHARACTER = DOUBLE + 1;
public static final int CHARACTER_OBJECT = CHARACTER + 1;
public static final int STRING = CHARACTER_OBJECT + 1;
public static final int DATE = STRING + 1;
public static final int NUMBER = DATE + 1;
public static final int OBJECT = NUMBER + 1;
public static final int BOOLEAN_ARRAY = OBJECT + 1;
public static final int BYTE_ARRAY = BOOLEAN_ARRAY + 1;
public static final int SHORT_ARRAY = BYTE_ARRAY + 1;
public static final int INTEGER_ARRAY = SHORT_ARRAY + 1;
public static final int LONG_ARRAY = INTEGER_ARRAY + 1;
public static final int FLOAT_ARRAY = LONG_ARRAY + 1;
public static final int DOUBLE_ARRAY = FLOAT_ARRAY + 1;
public static final int CHARACTER_ARRAY = DOUBLE_ARRAY + 1;
public static final int STRING_ARRAY = CHARACTER_ARRAY + 1;
public static final int OBJECT_ARRAY = STRING_ARRAY + 1;
private int code;
public BasicSerializer(int code)
{
this.code = code;
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
switch (code) {
case BOOLEAN:
out.writeBoolean(((Boolean) obj).booleanValue());
break;
case BYTE:
case SHORT:
case INTEGER:
out.writeInt(((Number) obj).intValue());
break;
case LONG:
out.writeLong(((Number) obj).longValue());
break;
case FLOAT:
case DOUBLE:
out.writeDouble(((Number) obj).doubleValue());
break;
case CHARACTER:
case CHARACTER_OBJECT:
out.writeString(String.valueOf(obj));
break;
case STRING:
out.writeString((String) obj);
break;
case DATE:
out.writeUTCDate(((Date) obj).getTime());
break;
case BOOLEAN_ARRAY:
{
if (out.addRef(obj))
return;
boolean []data = (boolean []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[boolean");
for (int i = 0; i < data.length; i++)
out.writeBoolean(data[i]);
if (hasEnd)
out.writeListEnd();
break;
}
case BYTE_ARRAY:
{
byte []data = (byte []) obj;
out.writeBytes(data, 0, data.length);
break;
}
case SHORT_ARRAY:
{
if (out.addRef(obj))
return;
short []data = (short []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[short");
for (int i = 0; i < data.length; i++)
out.writeInt(data[i]);
if (hasEnd)
out.writeListEnd();
break;
}
case INTEGER_ARRAY:
{
if (out.addRef(obj))
return;
int []data = (int []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[int");
for (int i = 0; i < data.length; i++)
out.writeInt(data[i]);
if (hasEnd)
out.writeListEnd();
break;
}
case LONG_ARRAY:
{
if (out.addRef(obj))
return;
long []data = (long []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[long");
for (int i = 0; i < data.length; i++)
out.writeLong(data[i]);
if (hasEnd)
out.writeListEnd();
break;
}
case FLOAT_ARRAY:
{
if (out.addRef(obj))
return;
float []data = (float []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[float");
for (int i = 0; i < data.length; i++)
out.writeDouble(data[i]);
if (hasEnd)
out.writeListEnd();
break;
}
case DOUBLE_ARRAY:
{
if (out.addRef(obj))
return;
double []data = (double []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[double");
for (int i = 0; i < data.length; i++)
out.writeDouble(data[i]);
if (hasEnd)
out.writeListEnd();
break;
}
case STRING_ARRAY:
{
if (out.addRef(obj))
return;
String []data = (String []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[string");
for (int i = 0; i < data.length; i++) {
out.writeString(data[i]);
}
if (hasEnd)
out.writeListEnd();
break;
}
case CHARACTER_ARRAY:
{
char []data = (char []) obj;
out.writeString(data, 0, data.length);
break;
}
case OBJECT_ARRAY:
{
if (out.addRef(obj))
return;
Object []data = (Object []) obj;
boolean hasEnd = out.writeListBegin(data.length, "[object");
for (int i = 0; i < data.length; i++) {
out.writeObject(data[i]);
}
if (hasEnd)
out.writeListEnd();
break;
}
case NULL:
out.writeNull();
break;
default:
throw new RuntimeException(code + " " + String.valueOf(obj.getClass()));
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/BasicSerializer.java | Java | asf20 | 7,628 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.OutputStream;
/**
* Abstract output stream for Hessian requests.
*
* <pre>
* OutputStream os = ...; // from http connection
* AbstractOutput out = new HessianSerializerOutput(os);
* String value;
*
* out.startCall("hello"); // start hello call
* out.writeString("arg1"); // write a string argument
* out.completeCall(); // complete the call
* </pre>
*/
abstract public class AbstractHessianOutput {
// serializer factory
protected SerializerFactory _serializerFactory;
/**
* Sets the serializer factory.
*/
public void setSerializerFactory(SerializerFactory factory)
{
_serializerFactory = factory;
}
/**
* Gets the serializer factory.
*/
public SerializerFactory getSerializerFactory()
{
return _serializerFactory;
}
/**
* Gets the serializer factory.
*/
public final SerializerFactory findSerializerFactory()
{
SerializerFactory factory = _serializerFactory;
if (factory == null)
_serializerFactory = factory = new SerializerFactory();
return factory;
}
/**
* Initialize the output with a new underlying stream.
*/
public void init(OutputStream os)
{
}
/**
* Writes a complete method call.
*/
public void call(String method, Object []args)
throws IOException
{
startCall(method);
if (args != null) {
for (int i = 0; i < args.length; i++)
writeObject(args[i]);
}
completeCall();
}
/**
* Starts the method call:
*
* <code><pre>
* c major minor
* </pre></code>
*
* @param method the method name to call.
*/
abstract public void startCall()
throws IOException;
/**
* Starts the method call:
*
* <code><pre>
* c major minor
* m b16 b8 method-namek
* </pre></code>
*
* @param method the method name to call.
*/
abstract public void startCall(String method)
throws IOException;
/**
* Writes a header name. The header value must immediately follow.
*
* <code><pre>
* H b16 b8 foo <em>value</em>
* </pre></code>
*/
abstract public void writeHeader(String name)
throws IOException;
/**
* Writes the method tag.
*
* <code><pre>
* m b16 b8 method-name
* </pre></code>
*
* @param method the method name to call.
*/
abstract public void writeMethod(String method)
throws IOException;
/**
* Completes the method call:
*
* <code><pre>
* z
* </pre></code>
*/
abstract public void completeCall()
throws IOException;
/**
* Writes a boolean value to the stream. The boolean will be written
* with the following syntax:
*
* <code><pre>
* T
* F
* </pre></code>
*
* @param value the boolean value to write.
*/
abstract public void writeBoolean(boolean value)
throws IOException;
/**
* Writes an integer value to the stream. The integer will be written
* with the following syntax:
*
* <code><pre>
* I b32 b24 b16 b8
* </pre></code>
*
* @param value the integer value to write.
*/
abstract public void writeInt(int value)
throws IOException;
/**
* Writes a long value to the stream. The long will be written
* with the following syntax:
*
* <code><pre>
* L b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param value the long value to write.
*/
abstract public void writeLong(long value)
throws IOException;
/**
* Writes a double value to the stream. The double will be written
* with the following syntax:
*
* <code><pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param value the double value to write.
*/
abstract public void writeDouble(double value)
throws IOException;
/**
* Writes a date to the stream.
*
* <code><pre>
* T b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param time the date in milliseconds from the epoch in UTC
*/
abstract public void writeUTCDate(long time)
throws IOException;
/**
* Writes a null value to the stream.
* The null will be written with the following syntax
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
abstract public void writeNull()
throws IOException;
/**
* Writes a string value to the stream using UTF-8 encoding.
* The string will be written with the following syntax:
*
* <code><pre>
* S b16 b8 string-value
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
abstract public void writeString(String value)
throws IOException;
/**
* Writes a string value to the stream using UTF-8 encoding.
* The string will be written with the following syntax:
*
* <code><pre>
* S b16 b8 string-value
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
abstract public void writeString(char []buffer, int offset, int length)
throws IOException;
/**
* Writes a byte array to the stream.
* The array will be written with the following syntax:
*
* <code><pre>
* B b16 b18 bytes
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
abstract public void writeBytes(byte []buffer)
throws IOException;
/**
* Writes a byte array to the stream.
* The array will be written with the following syntax:
*
* <code><pre>
* B b16 b18 bytes
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
abstract public void writeBytes(byte []buffer, int offset, int length)
throws IOException;
/**
* Writes a byte buffer to the stream.
*/
abstract public void writeByteBufferStart()
throws IOException;
/**
* Writes a byte buffer to the stream.
*
* <code><pre>
* b b16 b18 bytes
* </pre></code>
*
* @param value the string value to write.
*/
abstract public void writeByteBufferPart(byte []buffer,
int offset,
int length)
throws IOException;
/**
* Writes the last chunk of a byte buffer to the stream.
*
* <code><pre>
* b b16 b18 bytes
* </pre></code>
*
* @param value the string value to write.
*/
abstract public void writeByteBufferEnd(byte []buffer,
int offset,
int length)
throws IOException;
/**
* Writes a reference.
*
* <code><pre>
* R b32 b24 b16 b8
* </pre></code>
*
* @param value the integer value to write.
*/
abstract public void writeRef(int value)
throws IOException;
/**
* Removes a reference.
*/
abstract public boolean removeRef(Object obj)
throws IOException;
/**
* Replaces a reference from one object to another.
*/
abstract public boolean replaceRef(Object oldRef, Object newRef)
throws IOException;
/**
* Adds an object to the reference list. If the object already exists,
* writes the reference, otherwise, the caller is responsible for
* the serialization.
*
* <code><pre>
* R b32 b24 b16 b8
* </pre></code>
*
* @param object the object to add as a reference.
*
* @return true if the object has already been written.
*/
abstract public boolean addRef(Object object)
throws IOException;
/**
* Resets the references for streaming.
*/
public void resetReferences()
{
}
/**
* Writes a generic object to the output stream.
*/
abstract public void writeObject(Object object)
throws IOException;
/**
* Writes the list header to the stream. List writers will call
* <code>writeListBegin</code> followed by the list contents and then
* call <code>writeListEnd</code>.
*
* <code><pre>
* <list>
* <type>java.util.ArrayList</type>
* <length>3</length>
* <int>1</int>
* <int>2</int>
* <int>3</int>
* </list>
* </pre></code>
*/
abstract public boolean writeListBegin(int length, String type)
throws IOException;
/**
* Writes the tail of the list to the stream.
*/
abstract public void writeListEnd()
throws IOException;
/**
* Writes the map header to the stream. Map writers will call
* <code>writeMapBegin</code> followed by the map contents and then
* call <code>writeMapEnd</code>.
*
* <code><pre>
* Mt b16 b8 type (<key> <value>)z
* </pre></code>
*/
abstract public void writeMapBegin(String type)
throws IOException;
/**
* Writes the tail of the map to the stream.
*/
abstract public void writeMapEnd()
throws IOException;
/**
* Writes the object header to the stream (for Hessian 2.0), or a
* Map for Hessian 1.0. Object writers will call
* <code>writeObjectBegin</code> followed by the map contents and then
* call <code>writeObjectEnd</code>.
*
* <code><pre>
* Ot b16 b8 type (<key> <value>)* z
* o b32 b24 b16 b8 <value>* z
* </pre></code>
*
* @return true if the object has already been defined.
*/
public int writeObjectBegin(String type)
throws IOException
{
writeMapBegin(type);
return -2;
}
/**
* Writes the end of the class.
*/
public void writeClassFieldLength(int len)
throws IOException
{
}
/**
* Writes the tail of the object to the stream.
*/
public void writeObjectEnd()
throws IOException
{
}
/**
* Writes a remote object reference to the stream. The type is the
* type of the remote interface.
*
* <code><pre>
* 'r' 't' b16 b8 type url
* </pre></code>
*/
abstract public void writeRemote(String type, String url)
throws IOException;
public void startReply()
throws IOException
{
}
public void completeReply()
throws IOException
{
}
public void writeFault(String code, String message, Object detail)
throws IOException
{
}
public void flush()
throws IOException
{
}
public void close()
throws IOException
{
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/AbstractHessianOutput.java | Java | asf20 | 12,655 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
/**
* Marks a type as a handle
*/
public interface HessianHandle {
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianHandle.java | Java | asf20 | 2,338 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.lang.reflect.Constructor;
/**
* Deserializing a string valued object
*/
public class SqlDateDeserializer extends AbstractDeserializer {
private Class _cl;
private Constructor _constructor;
public SqlDateDeserializer(Class cl)
throws NoSuchMethodException
{
_cl = cl;
_constructor = cl.getConstructor(new Class[] { long.class });
}
public Class getType()
{
return _cl;
}
public Object readMap(AbstractHessianInput in)
throws IOException
{
int ref = in.addRef(null);
long initValue = Long.MIN_VALUE;
while (! in.isEnd()) {
String key = in.readString();
if (key.equals("value"))
initValue = in.readUTCDate();
else
in.readString();
}
in.readMapEnd();
Object value = create(initValue);
in.setRef(ref, value);
return value;
}
public Object readObject(AbstractHessianInput in, String []fieldNames)
throws IOException
{
int ref = in.addRef(null);
long initValue = Long.MIN_VALUE;
for (int i = 0; i < fieldNames.length; i++) {
String key = fieldNames[i];
if (key.equals("value"))
initValue = in.readUTCDate();
else
in.readObject();
}
Object value = create(initValue);
in.setRef(ref, value);
return value;
}
private Object create(long initValue)
throws IOException
{
if (initValue == Long.MIN_VALUE)
throw new IOException(_cl.getName() + " expects name.");
try {
return _constructor.newInstance(new Object[] { new Long(initValue) });
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/SqlDateDeserializer.java | Java | asf20 | 3,932 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.OutputStream;
import java.util.HashMap;
/**
* Output stream for Hessian 2 streaming requests.
*/
public class Hessian2StreamingOutput
{
private Hessian2Output _out;
/**
* Creates a new Hessian output stream, initialized with an
* underlying output stream.
*
* @param os the underlying output stream.
*/
public Hessian2StreamingOutput(OutputStream os)
{
_out = new Hessian2Output(os);
}
public void setCloseStreamOnClose(boolean isClose)
{
_out.setCloseStreamOnClose(isClose);
}
public boolean isCloseStreamOnClose()
{
return _out.isCloseStreamOnClose();
}
/**
* Writes any object to the output stream.
*/
public void writeObject(Object object)
throws IOException
{
_out.writeStreamingObject(object);
}
/**
* Flushes the output.
*/
public void flush()
throws IOException
{
_out.flush();
}
/**
* Close the output.
*/
public void close()
throws IOException
{
_out.close();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/Hessian2StreamingOutput.java | Java | asf20 | 3,313 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Deserializing a string valued object
*/
abstract public class ValueDeserializer extends AbstractDeserializer {
public Object readMap(AbstractHessianInput in)
throws IOException
{
String initValue = null;
while (! in.isEnd()) {
String key = in.readString();
if (key.equals("value"))
initValue = in.readString();
else
in.readObject();
}
in.readMapEnd();
return create(initValue);
}
public Object readObject(AbstractHessianInput in, String []fieldNames)
throws IOException
{
String initValue = null;
for (int i = 0; i < fieldNames.length; i++) {
if ("value".equals(fieldNames[i]))
initValue = in.readString();
else
in.readObject();
}
return create(initValue);
}
abstract Object create(String value)
throws IOException;
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/ValueDeserializer.java | Java | asf20 | 3,146 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Serializing an object for known object types.
*/
public class ThrowableSerializer extends JavaSerializer {
public ThrowableSerializer(Class cl)
{
super(cl);
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
Throwable e = (Throwable) obj;
e.getStackTrace();
super.writeObject(obj, out);
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/ThrowableSerializer.java | Java | asf20 | 2,666 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.Reader;
/**
* Abstract base class for Hessian requests. Hessian users should only
* need to use the methods in this class.
*
* <pre>
* AbstractHessianInput in = ...; // get input
* String value;
*
* in.startReply(); // read reply header
* value = in.readString(); // read string value
* in.completeReply(); // read reply footer
* </pre>
*/
abstract public class AbstractHessianInput {
private HessianRemoteResolver resolver;
/**
* Initialize the Hessian stream with the underlying input stream.
*/
public void init(InputStream is)
{
}
/**
* Returns the call's method
*/
abstract public String getMethod();
/**
* Sets the resolver used to lookup remote objects.
*/
public void setRemoteResolver(HessianRemoteResolver resolver)
{
this.resolver = resolver;
}
/**
* Sets the resolver used to lookup remote objects.
*/
public HessianRemoteResolver getRemoteResolver()
{
return resolver;
}
/**
* Sets the serializer factory.
*/
public void setSerializerFactory(SerializerFactory ser)
{
}
/**
* Reads the call
*
* <pre>
* c major minor
* </pre>
*/
abstract public int readCall()
throws IOException;
/**
* For backward compatibility with HessianSkeleton
*/
public void skipOptionalCall()
throws IOException
{
}
/**
* Reads a header, returning null if there are no headers.
*
* <pre>
* H b16 b8 value
* </pre>
*/
abstract public String readHeader()
throws IOException;
/**
* Starts reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* m b16 b8 method
* </pre>
*/
abstract public String readMethod()
throws IOException;
/**
* Starts reading the call, including the headers.
*
* <p>The call expects the following protocol data
*
* <pre>
* c major minor
* m b16 b8 method
* </pre>
*/
abstract public void startCall()
throws IOException;
/**
* Completes reading the call
*
* <p>The call expects the following protocol data
*
* <pre>
* Z
* </pre>
*/
abstract public void completeCall()
throws IOException;
/**
* Reads a reply as an object.
* If the reply has a fault, throws the exception.
*/
abstract public Object readReply(Class expectedClass)
throws Throwable;
/**
* Starts reading the reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* r
* v
* </pre>
*/
abstract public void startReply()
throws Throwable;
/**
* Completes reading the call
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
abstract public void completeReply()
throws IOException;
/**
* Reads a boolean
*
* <pre>
* T
* F
* </pre>
*/
abstract public boolean readBoolean()
throws IOException;
/**
* Reads a null
*
* <pre>
* N
* </pre>
*/
abstract public void readNull()
throws IOException;
/**
* Reads an integer
*
* <pre>
* I b32 b24 b16 b8
* </pre>
*/
abstract public int readInt()
throws IOException;
/**
* Reads a long
*
* <pre>
* L b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
abstract public long readLong()
throws IOException;
/**
* Reads a double.
*
* <pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
abstract public double readDouble()
throws IOException;
/**
* Reads a date.
*
* <pre>
* T b64 b56 b48 b40 b32 b24 b16 b8
* </pre>
*/
abstract public long readUTCDate()
throws IOException;
/**
* Reads a string encoded in UTF-8
*
* <pre>
* s b16 b8 non-final string chunk
* S b16 b8 final string chunk
* </pre>
*/
abstract public String readString()
throws IOException;
/**
* Reads an XML node encoded in UTF-8
*
* <pre>
* x b16 b8 non-final xml chunk
* X b16 b8 final xml chunk
* </pre>
*/
abstract public org.w3c.dom.Node readNode()
throws IOException;
/**
* Starts reading a string. All the characters must be read before
* calling the next method. The actual characters will be read with
* the reader's read() or read(char [], int, int).
*
* <pre>
* s b16 b8 non-final string chunk
* S b16 b8 final string chunk
* </pre>
*/
abstract public Reader getReader()
throws IOException;
/**
* Starts reading a byte array using an input stream. All the bytes
* must be read before calling the following method.
*
* <pre>
* b b16 b8 non-final binary chunk
* B b16 b8 final binary chunk
* </pre>
*/
abstract public InputStream readInputStream()
throws IOException;
/**
* Reads a byte array.
*
* <pre>
* b b16 b8 non-final binary chunk
* B b16 b8 final binary chunk
* </pre>
*/
abstract public byte []readBytes()
throws IOException;
/**
* Reads an arbitrary object from the input stream.
*
* @param expectedClass the expected class if the protocol doesn't supply it.
*/
abstract public Object readObject(Class expectedClass)
throws IOException;
/**
* Reads an arbitrary object from the input stream.
*/
abstract public Object readObject()
throws IOException;
/**
* Reads a remote object reference to the stream. The type is the
* type of the remote interface.
*
* <code><pre>
* 'r' 't' b16 b8 type url
* </pre></code>
*/
abstract public Object readRemote()
throws IOException;
/**
* Reads a reference
*
* <pre>
* R b32 b24 b16 b8
* </pre>
*/
abstract public Object readRef()
throws IOException;
/**
* Adds an object reference.
*/
abstract public int addRef(Object obj)
throws IOException;
/**
* Sets an object reference.
*/
abstract public void setRef(int i, Object obj)
throws IOException;
/**
* Resets the references for streaming.
*/
public void resetReferences()
{
}
/**
* Reads the start of a list
*/
abstract public int readListStart()
throws IOException;
/**
* Reads the length of a list.
*/
abstract public int readLength()
throws IOException;
/**
* Reads the start of a map
*/
abstract public int readMapStart()
throws IOException;
/**
* Reads an object type.
*/
abstract public String readType()
throws IOException;
/**
* Returns true if the data has ended.
*/
abstract public boolean isEnd()
throws IOException;
/**
* Read the end byte
*/
abstract public void readEnd()
throws IOException;
/**
* Read the end byte
*/
abstract public void readMapEnd()
throws IOException;
/**
* Read the end byte
*/
abstract public void readListEnd()
throws IOException;
public void close()
throws IOException
{
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/AbstractHessianInput.java | Java | asf20 | 9,282 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
/**
* Serializing an object for known object types.
*/
public class ObjectDeserializer extends AbstractDeserializer {
private Class _cl;
public ObjectDeserializer(Class cl)
{
_cl = cl;
}
public Class getType()
{
return _cl;
}
public Object readObject(AbstractHessianInput in)
throws IOException
{
return in.readObject();
}
public Object readObject(AbstractHessianInput in, String []fieldNames)
throws IOException
{
throw new UnsupportedOperationException(String.valueOf(this));
}
public Object readList(AbstractHessianInput in, int length)
throws IOException
{
throw new UnsupportedOperationException(String.valueOf(this));
}
public Object readLengthList(AbstractHessianInput in, int length)
throws IOException
{
throw new UnsupportedOperationException(String.valueOf(this));
}
@Override
public String toString()
{
return getClass().getSimpleName() + "[" + _cl + "]";
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/ObjectDeserializer.java | Java | asf20 | 3,325 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.Vector;
/**
* Deserializing a JDK 1.2 Collection.
*/
public class EnumerationDeserializer extends AbstractListDeserializer {
private static EnumerationDeserializer _deserializer;
public static EnumerationDeserializer create()
{
if (_deserializer == null)
_deserializer = new EnumerationDeserializer();
return _deserializer;
}
public Object readList(AbstractHessianInput in, int length)
throws IOException
{
Vector list = new Vector();
in.addRef(list);
while (! in.isEnd())
list.add(in.readObject());
in.readEnd();
return list.elements();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/EnumerationDeserializer.java | Java | asf20 | 2,926 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
/**
* Exception for faults when the fault doesn't return a java exception.
* This exception is required for MicroHessianInput.
*/
public class HessianServiceException extends Exception {
private String code;
private Object detail;
/**
* Zero-arg constructor.
*/
public HessianServiceException()
{
}
/**
* Create the exception.
*/
public HessianServiceException(String message, String code, Object detail)
{
super(message);
this.code = code;
this.detail = detail;
}
/**
* Returns the code.
*/
public String getCode()
{
return code;
}
/**
* Returns the detail.
*/
public Object getDetail()
{
return detail;
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianServiceException.java | Java | asf20 | 2,963 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Serializing a remote object.
*/
public class RemoteSerializer extends AbstractSerializer {
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (obj instanceof HessianRemoteObject) {
HessianRemoteObject remote = (HessianRemoteObject) obj;
out.writeRemote(remote.getHessianType(), remote.getHessianURL());
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/RemoteSerializer.java | Java | asf20 | 2,680 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Exception for faults when the fault doesn't return a java exception.
* This exception is required for MicroHessianInput.
*/
public class HessianProtocolException extends IOException {
private Throwable rootCause;
/**
* Zero-arg constructor.
*/
public HessianProtocolException()
{
}
/**
* Create the exception.
*/
public HessianProtocolException(String message)
{
super(message);
}
/**
* Create the exception.
*/
public HessianProtocolException(String message, Throwable rootCause)
{
super(message);
this.rootCause = rootCause;
}
/**
* Create the exception.
*/
public HessianProtocolException(Throwable rootCause)
{
super(String.valueOf(rootCause));
this.rootCause = rootCause;
}
/**
* Returns the underlying cause.
*/
public Throwable getRootCause()
{
return rootCause;
}
/**
* Returns the underlying cause.
*/
public Throwable getCause()
{
return getRootCause();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianProtocolException.java | Java | asf20 | 3,302 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/**
* Serializing a JDK 1.2 java.util.Map.
*/
public class MapSerializer extends AbstractSerializer {
private boolean _isSendJavaType = true;
/**
* Set true if the java type of the collection should be sent.
*/
public void setSendJavaType(boolean sendJavaType)
{
_isSendJavaType = sendJavaType;
}
/**
* Return true if the java type of the collection should be sent.
*/
public boolean getSendJavaType()
{
return _isSendJavaType;
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (out.addRef(obj))
return;
Map map = (Map) obj;
Class cl = obj.getClass();
if (cl.equals(HashMap.class)
|| ! _isSendJavaType
|| ! (obj instanceof java.io.Serializable))
out.writeMapBegin(null);
else
out.writeMapBegin(obj.getClass().getName());
Iterator iter = map.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry entry = (Map.Entry) iter.next();
out.writeObject(entry.getKey());
out.writeObject(entry.getValue());
}
out.writeMapEnd();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/MapSerializer.java | Java | asf20 | 3,474 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.Calendar;
/**
* Serializing a calendar.
*/
public class CalendarSerializer extends AbstractSerializer {
private static CalendarSerializer SERIALIZER = new CalendarSerializer();
public static CalendarSerializer create()
{
return SERIALIZER;
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (obj == null)
out.writeNull();
else {
Calendar cal = (Calendar) obj;
out.writeObject(new CalendarHandle(cal.getClass(),
cal.getTimeInMillis()));
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/CalendarSerializer.java | Java | asf20 | 2,858 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
/**
* Handle for a calendar object.
*/
public class CalendarHandle implements java.io.Serializable, HessianHandle {
private Class type;
private Date date;
public CalendarHandle()
{
}
public CalendarHandle(Class type, long time)
{
if (! GregorianCalendar.class.equals(type))
this.type = type;
this.date = new Date(time);
}
private Object readResolve()
{
try {
Calendar cal;
if (this.type != null)
cal = (Calendar) this.type.newInstance();
else
cal = new GregorianCalendar();
cal.setTimeInMillis(this.date.getTime());
return cal;
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/CalendarHandle.java | Java | asf20 | 3,106 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
public interface Hessian2Constants
{
public static final int INT_DIRECT_MIN = -0x10;
public static final int INT_DIRECT_MAX = 0x2f;
public static final int INT_ZERO = 0x90;
public static final int INT_BYTE_MIN = -0x800;
public static final int INT_BYTE_MAX = 0x7ff;
public static final int INT_BYTE_ZERO = 0xc8;
public static final int INT_SHORT_MIN = -0x40000;
public static final int INT_SHORT_MAX = 0x3ffff;
public static final int INT_SHORT_ZERO = 0xd4;
public static final long LONG_DIRECT_MIN = -0x08;
public static final long LONG_DIRECT_MAX = 0x0f;
public static final int LONG_ZERO = 0xe0;
public static final long LONG_BYTE_MIN = -0x800;
public static final long LONG_BYTE_MAX = 0x7ff;
public static final int LONG_BYTE_ZERO = 0xf8;
public static final int LONG_SHORT_MIN = -0x40000;
public static final int LONG_SHORT_MAX = 0x3ffff;
public static final int LONG_SHORT_ZERO = 0x3c;
public static final int STRING_DIRECT_MAX = 0x1f;
public static final int STRING_DIRECT = 0x00;
public static final int BYTES_DIRECT_MAX = 0x0f;
public static final int BYTES_DIRECT = 0x20;
// 0x30-0x37 is reserved
public static final int LONG_INT = 0x77;
public static final int DOUBLE_ZERO = 0x67;
public static final int DOUBLE_ONE = 0x68;
public static final int DOUBLE_BYTE = 0x69;
public static final int DOUBLE_SHORT = 0x6a;
public static final int DOUBLE_FLOAT = 0x6b;
public static final int LENGTH_BYTE = 0x6e;
public static final int LIST_FIXED = 0x76; // 'v'
public static final int REF_BYTE = 0x4a;
public static final int REF_SHORT = 0x4b;
public static final int TYPE_REF = 0x75;
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/Hessian2Constants.java | Java | asf20 | 3,939 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Serializing a remote object.
*/
public class ClassSerializer extends AbstractSerializer {
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
Class cl = (Class) obj;
if (cl == null) {
out.writeNull();
}
else if (out.addRef(obj)) {
return;
}
else {
int ref = out.writeObjectBegin("java.lang.Class");
if (ref < -1) {
out.writeString("name");
out.writeString(cl.getName());
out.writeMapEnd();
}
else {
if (ref == -1) {
out.writeInt(1);
out.writeString("name");
out.writeObjectBegin("java.lang.Class");
}
out.writeString(cl.getName());
}
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/ClassSerializer.java | Java | asf20 | 2,974 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.*;
import java.util.HashMap;
/**
* Deserializing a JDK 1.4 StackTraceElement
*/
public class StackTraceElementDeserializer extends JavaDeserializer {
public StackTraceElementDeserializer()
{
super(StackTraceElement.class);
}
@Override
protected Object instantiate()
throws Exception
{
return new StackTraceElement("", "", "", 0);
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/StackTraceElementDeserializer.java | Java | asf20 | 2,646 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
/**
* Factory for returning serialization methods.
*/
abstract public class AbstractSerializerFactory {
/**
* Returns the serializer for a class.
*
* @param cl the class of the object that needs to be serialized.
*
* @return a serializer object for the serialization.
*/
abstract public Serializer getSerializer(Class cl)
throws HessianProtocolException;
/**
* Returns the deserializer for a class.
*
* @param cl the class of the object that needs to be deserialized.
*
* @return a deserializer object for the serialization.
*/
abstract public Deserializer getDeserializer(Class cl)
throws HessianProtocolException;
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/AbstractSerializerFactory.java | Java | asf20 | 2,939 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* Serializing an object for known object types.
*/
public class JavaSerializer extends AbstractSerializer
{
private static final Logger log = Logger.getLogger(JavaSerializer.class.getName());
private static Map<Class<?>, ArrayList<Field>> fieldsCache = new HashMap<Class<?>, ArrayList<Field>>();
private static Map<Class<?>, ArrayList<FieldSerializer>> fieldSerializerCache = new HashMap<Class<?>, ArrayList<FieldSerializer>>();
private Object _writeReplaceFactory;
private Method _writeReplace;
private Class<?> _type;
public JavaSerializer(Class<?> cl)
{
_type = cl;
introspectWriteReplace(cl);
if (_writeReplace != null)
_writeReplace.setAccessible(true);
if (!fieldsCache.containsKey(cl)) {
final ArrayList<Field> primitiveFields = new ArrayList<Field>();
final ArrayList<Field> compoundFields = new ArrayList<Field>();
final ArrayList<FieldSerializer> fieldSerializers = new ArrayList<FieldSerializer>();
for (; cl != null; cl = cl.getSuperclass()) {
final Field []fields = cl.getDeclaredFields();
for (int i = 0; i < fields.length; i++) {
Field field = fields[i];
if (Modifier.isTransient(field.getModifiers()) || Modifier.isStatic(field.getModifiers()))
continue;
field.setAccessible(true);
if (field.getType().isPrimitive() || (field.getType().getName().startsWith("java.lang.") && ! field.getType().equals(Object.class)))
primitiveFields.add(field);
else
compoundFields.add(field);
}
}
final ArrayList<Field> result = new ArrayList<Field>();
result.addAll(primitiveFields);
result.addAll(compoundFields);
fieldsCache.put(_type, result);
fieldSerializerCache.put(_type, fieldSerializers);
for (int i = 0; i < result.size(); i++) {
fieldSerializers.add(getFieldSerializer(result.get(i).getType()));
}
}
}
private void introspectWriteReplace(Class cl)
{
try {
ClassLoader loader = Thread.currentThread().getContextClassLoader();
String className = cl.getName() + "HessianSerializer";
Class serializerClass = Class.forName(className, false, loader);
Object serializerObject = serializerClass.newInstance();
Method writeReplace = getWriteReplace(serializerClass, cl);
if (writeReplace != null) {
_writeReplaceFactory = serializerObject;
_writeReplace = writeReplace;
return;
}
} catch (ClassNotFoundException e) {
} catch (Exception e) {
log.log(Level.FINER, e.toString(), e);
}
_writeReplace = getWriteReplace(cl);
}
/**
* Returns the writeReplace method
*/
protected static Method getWriteReplace(Class<?> cl)
{
try {
return cl.getMethod("writeReplace", new Class[0]);
} catch (Exception e) {}
return null;
}
/**
* Returns the writeReplace method
*/
protected Method getWriteReplace(Class<?> cl, Class<?> param)
{
try {
return cl.getMethod("writeReplace", new Class[] { param });
} catch (Exception e) {}
return null;
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (out.addRef(obj)) {
return;
}
final Class<?> cl = obj.getClass();
try {
if (_writeReplace != null) {
Object repl;
if (_writeReplaceFactory != null)
repl = _writeReplace.invoke(_writeReplaceFactory, obj);
else
repl = _writeReplace.invoke(obj);
out.removeRef(obj);
out.writeObject(repl);
out.replaceRef(repl, obj);
return;
}
} catch (RuntimeException e) {
throw e;
} catch (Exception e) {
// log.log(Level.FINE, e.toString(), e);
throw new RuntimeException(e);
}
int ref = out.writeObjectBegin(cl.getName());
if (ref < -1) {
writeObject10(obj, out);
}
else {
if (ref == -1) {
writeDefinition20(out);
out.writeObjectBegin(cl.getName());
}
writeInstance(obj, out);
}
}
private void writeObject10(Object obj, AbstractHessianOutput out)
throws IOException
{
final ArrayList<Field> fields = fieldsCache.get(_type);
final ArrayList<FieldSerializer> fieldSerializers = fieldSerializerCache.get(_type);
for (int i = 0; i < fields.size(); i++) {
final Field field = fields.get(i);
out.writeString(field.getName());
fieldSerializers.get(i).serialize(out, obj, field);
}
out.writeMapEnd();
}
private void writeDefinition20(AbstractHessianOutput out)
throws IOException
{
final ArrayList<Field> fields = fieldsCache.get(_type);
out.writeClassFieldLength(fields.size());
for (int i = 0; i < fields.size(); i++) {
final Field field = fields.get(i);
out.writeString(field.getName());
}
}
public void writeInstance(Object obj, AbstractHessianOutput out)
throws IOException
{
final ArrayList<Field> fields = fieldsCache.get(_type);
final ArrayList<FieldSerializer> fieldSerializers = fieldSerializerCache.get(_type);
for (int i = 0; i < fields.size(); i++) {
final Field field = fields.get(i);
fieldSerializers.get(i).serialize(out, obj, field);
}
}
private static FieldSerializer getFieldSerializer(Class<?> type)
{
if (int.class.equals(type)
|| byte.class.equals(type)
|| short.class.equals(type)
|| int.class.equals(type)) {
return IntFieldSerializer.SER;
}
else if (long.class.equals(type)) {
return LongFieldSerializer.SER;
}
else if (double.class.equals(type) ||
float.class.equals(type)) {
return DoubleFieldSerializer.SER;
}
else if (boolean.class.equals(type)) {
return BooleanFieldSerializer.SER;
}
else if (String.class.equals(type)) {
return StringFieldSerializer.SER;
}
else if (java.util.Date.class.equals(type)
|| java.sql.Date.class.equals(type)
|| java.sql.Timestamp.class.equals(type)
|| java.sql.Time.class.equals(type)) {
return DateFieldSerializer.SER;
}
else
return FieldSerializer.SER;
}
static class FieldSerializer {
static final FieldSerializer SER = new FieldSerializer();
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
Object value = null;
try {
value = field.get(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
try {
out.writeObject(value);
} catch (RuntimeException e) {
throw new RuntimeException(e.getMessage() + "\n Java field: " + field,
e);
} catch (IOException e) {
throw new IOExceptionWrapper(e.getMessage() + "\n Java field: " + field,
e);
}
}
}
static class BooleanFieldSerializer extends FieldSerializer {
static final FieldSerializer SER = new BooleanFieldSerializer();
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
boolean value = false;
try {
value = field.getBoolean(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeBoolean(value);
}
}
static class IntFieldSerializer extends FieldSerializer {
static final FieldSerializer SER = new IntFieldSerializer();
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
int value = 0;
try {
value = field.getInt(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeInt(value);
}
}
static class LongFieldSerializer extends FieldSerializer {
static final FieldSerializer SER = new LongFieldSerializer();
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
long value = 0;
try {
value = field.getLong(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeLong(value);
}
}
static class DoubleFieldSerializer extends FieldSerializer {
static final FieldSerializer SER = new DoubleFieldSerializer();
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
double value = 0;
try {
value = field.getDouble(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeDouble(value);
}
}
static class StringFieldSerializer extends FieldSerializer {
static final FieldSerializer SER = new StringFieldSerializer();
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
String value = null;
try {
value = (String) field.get(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
out.writeString(value);
}
}
static class DateFieldSerializer extends FieldSerializer {
static final FieldSerializer SER = new DateFieldSerializer();
void serialize(AbstractHessianOutput out, Object obj, Field field)
throws IOException
{
java.util.Date value = null;
try {
value = (java.util.Date) field.get(obj);
} catch (IllegalAccessException e) {
log.log(Level.FINE, e.toString(), e);
}
if (value != null) out.writeUTCDate(value.getTime()); else out.writeNull();
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/JavaSerializer.java | Java | asf20 | 12,047 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.util.logging.*;
import java.io.*;
public class HessianInputFactory
{
public static final Logger log
= Logger.getLogger(HessianInputFactory.class.getName());
private SerializerFactory _serializerFactory;
public void setSerializerFactory(SerializerFactory factory)
{
_serializerFactory = factory;
}
public SerializerFactory getSerializerFactory()
{
return _serializerFactory;
}
public AbstractHessianInput open(InputStream is)
throws IOException
{
int code = is.read();
int major = is.read();
int minor = is.read();
switch (code) {
case 'c':
case 'C':
case 'r':
case 'R':
if (major >= 2) {
AbstractHessianInput in = new Hessian2Input(is);
in.setSerializerFactory(_serializerFactory);
return in;
}
else {
AbstractHessianInput in = new HessianInput(is);
in.setSerializerFactory(_serializerFactory);
return in;
}
default:
throw new IOException((char) code + " is an unknown Hessian message code.");
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianInputFactory.java | Java | asf20 | 3,301 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.OutputStream;
import java.io.Writer;
import java.io.PrintWriter;
import java.util.logging.Logger;
import java.util.logging.Level;
/**
* Debugging output stream for Hessian requests.
*/
public class HessianDebugOutputStream extends OutputStream
{
private OutputStream _os;
private HessianDebugState _state;
/**
* Creates an uninitialized Hessian input stream.
*/
public HessianDebugOutputStream(OutputStream os, PrintWriter dbg)
{
_os = os;
_state = new HessianDebugState(dbg);
}
/**
* Creates an uninitialized Hessian input stream.
*/
public HessianDebugOutputStream(OutputStream os, Logger log, Level level)
{
this(os, new PrintWriter(new LogWriter(log, level)));
}
/**
* Writes a character.
*/
public void write(int ch)
throws IOException
{
ch = ch & 0xff;
_os.write(ch);
_state.next(ch);
}
public void flush()
throws IOException
{
_os.flush();
}
/**
* closes the stream.
*/
public void close()
throws IOException
{
OutputStream os = _os;
_os = null;
if (os != null)
os.close();
_state.println();
}
static class LogWriter extends Writer {
private Logger _log;
private Level _level;
private StringBuilder _sb = new StringBuilder();
LogWriter(Logger log, Level level)
{
_log = log;
_level = level;
}
public void write(char ch)
{
if (ch == '\n' && _sb.length() > 0) {
_log.log(_level, _sb.toString());
_sb.setLength(0);
}
else
_sb.append((char) ch);
}
public void write(char []buffer, int offset, int length)
{
for (int i = 0; i < length; i++) {
char ch = buffer[offset + i];
if (ch == '\n' && _sb.length() > 0) {
_log.log(_level, _sb.toString());
_sb.setLength(0);
}
else
_sb.append((char) ch);
}
}
public void flush()
{
}
public void close()
{
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianDebugOutputStream.java | Java | asf20 | 4,256 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.Locale;
/**
* Serializing a locale.
*/
public class LocaleSerializer extends AbstractSerializer {
private static LocaleSerializer SERIALIZER = new LocaleSerializer();
public static LocaleSerializer create()
{
return SERIALIZER;
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (obj == null)
out.writeNull();
else {
Locale locale = (Locale) obj;
out.writeObject(new LocaleHandle(locale.toString()));
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/LocaleSerializer.java | Java | asf20 | 2,817 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.HashMap;
/**
* Deserializing a JDK 1.2 Class.
*/
public class ClassDeserializer extends AbstractMapDeserializer {
private static final HashMap<String,Class> _primClasses
= new HashMap<String,Class>();
public ClassDeserializer()
{
}
public Class getType()
{
return Class.class;
}
public Object readMap(AbstractHessianInput in)
throws IOException
{
int ref = in.addRef(null);
String name = null;
while (! in.isEnd()) {
String key = in.readString();
if (key.equals("name"))
name = in.readString();
else
in.readObject();
}
in.readMapEnd();
Object value = create(name);
in.setRef(ref, value);
return value;
}
public Object readObject(AbstractHessianInput in, String []fieldNames)
throws IOException
{
int ref = in.addRef(null);
String name = null;
for (int i = 0; i < fieldNames.length; i++) {
if ("name".equals(fieldNames[i]))
name = in.readString();
else
in.readObject();
}
Object value = create(name);
in.setRef(ref, value);
return value;
}
Object create(String name)
throws IOException
{
if (name == null)
throw new IOException("Serialized Class expects name.");
Class cl = _primClasses.get(name);
if (cl != null)
return cl;
ClassLoader loader = Thread.currentThread().getContextClassLoader();
try {
if (loader != null)
return Class.forName(name, false, loader);
else
return Class.forName(name);
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
static {
_primClasses.put("void", void.class);
_primClasses.put("boolean", boolean.class);
_primClasses.put("java.lang.Boolean", Boolean.class);
_primClasses.put("byte", byte.class);
_primClasses.put("java.lang.Byte", Byte.class);
_primClasses.put("char", char.class);
_primClasses.put("java.lang.Character", Character.class);
_primClasses.put("short", short.class);
_primClasses.put("java.lang.Short", Short.class);
_primClasses.put("int", int.class);
_primClasses.put("java.lang.Integer", Integer.class);
_primClasses.put("long", long.class);
_primClasses.put("java.lang.Long", Long.class);
_primClasses.put("float", float.class);
_primClasses.put("java.lang.Float", Float.class);
_primClasses.put("double", double.class);
_primClasses.put("java.lang.Double", Double.class);
_primClasses.put("java.lang.String", String.class);
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/ClassDeserializer.java | Java | asf20 | 4,859 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
/**
* Factory for returning serialization methods.
*/
public class BeanSerializerFactory extends SerializerFactory {
/**
* Returns the default serializer for a class that isn't matched
* directly. Application can override this method to produce
* bean-style serialization instead of field serialization.
*
* @param cl the class of the object that needs to be serialized.
*
* @return a serializer object for the serialization.
*/
protected Serializer getDefaultSerializer(Class cl)
{
return new BeanSerializer(cl);
}
/**
* Returns the default deserializer for a class that isn't matched
* directly. Application can override this method to produce
* bean-style serialization instead of field serialization.
*
* @param cl the class of the object that needs to be serialized.
*
* @return a serializer object for the serialization.
*/
protected Deserializer getDefaultDeserializer(Class cl)
{
return new BeanDeserializer(cl);
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/BeanSerializerFactory.java | Java | asf20 | 3,270 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.Iterator;
/**
* Serializing a JDK 1.2 Iterator.
*/
public class IteratorSerializer extends AbstractSerializer {
private static IteratorSerializer _serializer;
public static IteratorSerializer create()
{
if (_serializer == null)
_serializer = new IteratorSerializer();
return _serializer;
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
Iterator iter = (Iterator) obj;
boolean hasEnd = out.writeListBegin(-1, null);
while (iter.hasNext()) {
Object value = iter.next();
out.writeObject(value);
}
if (hasEnd)
out.writeListEnd();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/IteratorSerializer.java | Java | asf20 | 2,962 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.*;
/**
* Factory class for wrapping and unwrapping hessian streams.
*/
abstract public class HessianEnvelope {
/**
* Wrap the Hessian output stream in an envelope.
*/
abstract public Hessian2Output wrap(Hessian2Output out)
throws IOException;
/**
* Unwrap the Hessian input stream with this envelope. It is an
* error if the actual envelope does not match the expected envelope
* class.
*/
abstract public Hessian2Input unwrap(Hessian2Input in)
throws IOException;
/**
* Unwrap the envelope after having read the envelope code ('E') and
* the envelope method. Called by the EnvelopeFactory for dynamic
* reading of the envelopes.
*/
abstract public Hessian2Input unwrapHeaders(Hessian2Input in)
throws IOException;
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianEnvelope.java | Java | asf20 | 3,060 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.HashMap;
/**
* Serializing an object for known object types.
*/
public class BeanDeserializer extends AbstractMapDeserializer {
private Class _type;
private HashMap _methodMap;
private Method _readResolve;
private Constructor _constructor;
private Object []_constructorArgs;
public BeanDeserializer(Class cl)
{
_type = cl;
_methodMap = getMethodMap(cl);
_readResolve = getReadResolve(cl);
Constructor []constructors = cl.getConstructors();
int bestLength = Integer.MAX_VALUE;
for (int i = 0; i < constructors.length; i++) {
if (constructors[i].getParameterTypes().length < bestLength) {
_constructor = constructors[i];
bestLength = _constructor.getParameterTypes().length;
}
}
if (_constructor != null) {
_constructor.setAccessible(true);
Class []params = _constructor.getParameterTypes();
_constructorArgs = new Object[params.length];
for (int i = 0; i < params.length; i++) {
_constructorArgs[i] = getParamArg(params[i]);
}
}
}
public Class getType()
{
return _type;
}
public Object readMap(AbstractHessianInput in)
throws IOException
{
try {
Object obj = instantiate();
return readMap(in, obj);
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
public Object readMap(AbstractHessianInput in, Object obj)
throws IOException
{
try {
int ref = in.addRef(obj);
while (! in.isEnd()) {
Object key = in.readObject();
Method method = (Method) _methodMap.get(key);
if (method != null) {
Object value = in.readObject(method.getParameterTypes()[0]);
method.invoke(obj, new Object[] {value });
}
else {
Object value = in.readObject();
}
}
in.readMapEnd();
Object resolve = resolve(obj);
if (obj != resolve)
in.setRef(ref, resolve);
return resolve;
} catch (IOException e) {
throw e;
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
private Object resolve(Object obj)
{
// if there's a readResolve method, call it
try {
if (_readResolve != null)
return _readResolve.invoke(obj, new Object[0]);
} catch (Exception e) {
}
return obj;
}
protected Object instantiate()
throws Exception
{
return _constructor.newInstance(_constructorArgs);
}
/**
* Returns the readResolve method
*/
protected Method getReadResolve(Class cl)
{
for (; cl != null; cl = cl.getSuperclass()) {
Method []methods = cl.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (method.getName().equals("readResolve") &&
method.getParameterTypes().length == 0)
return method;
}
}
return null;
}
/**
* Creates a map of the classes fields.
*/
protected HashMap getMethodMap(Class cl)
{
HashMap methodMap = new HashMap();
for (; cl != null; cl = cl.getSuperclass()) {
Method []methods = cl.getDeclaredMethods();
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (Modifier.isStatic(method.getModifiers()))
continue;
String name = method.getName();
if (! name.startsWith("set"))
continue;
Class []paramTypes = method.getParameterTypes();
if (paramTypes.length != 1)
continue;
if (! method.getReturnType().equals(void.class))
continue;
if (findGetter(methods, name, paramTypes[0]) == null)
continue;
// XXX: could parameterize the handler to only deal with public
try {
method.setAccessible(true);
} catch (Throwable e) {
e.printStackTrace();
}
name = name.substring(3);
int j = 0;
for (; j < name.length() && Character.isUpperCase(name.charAt(j)); j++) {
}
if (j == 1)
name = name.substring(0, j).toLowerCase() + name.substring(j);
else if (j > 1)
name = name.substring(0, j - 1).toLowerCase() + name.substring(j - 1);
methodMap.put(name, method);
}
}
return methodMap;
}
/**
* Finds any matching setter.
*/
private Method findGetter(Method []methods, String setterName, Class arg)
{
String getterName = "get" + setterName.substring(3);
for (int i = 0; i < methods.length; i++) {
Method method = methods[i];
if (! method.getName().equals(getterName))
continue;
if (! method.getReturnType().equals(arg))
continue;
Class []params = method.getParameterTypes();
if (params.length == 0)
return method;
}
return null;
}
/**
* Creates a map of the classes fields.
*/
protected static Object getParamArg(Class cl)
{
if (! cl.isPrimitive())
return null;
else if (boolean.class.equals(cl))
return Boolean.FALSE;
else if (byte.class.equals(cl))
return Byte.valueOf((byte) 0);
else if (short.class.equals(cl))
return Short.valueOf((short) 0);
else if (char.class.equals(cl))
return Character.valueOf((char) 0);
else if (int.class.equals(cl))
return Integer.valueOf(0);
else if (long.class.equals(cl))
return Long.valueOf(0);
else if (float.class.equals(cl))
return Double.valueOf(0);
else if (double.class.equals(cl))
return Double.valueOf(0);
else
throw new UnsupportedOperationException();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/BeanDeserializer.java | Java | asf20 | 7,903 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.util.ArrayList;
/**
* Debugging input stream for Hessian requests.
*/
public class HessianDebugState implements Hessian2Constants
{
private PrintWriter _dbg;
private State _state;
private ArrayList<State> _stateStack = new ArrayList<State>();
private ArrayList<ObjectDef> _objectDefList
= new ArrayList<ObjectDef>();
private ArrayList<String> _typeDefList
= new ArrayList<String>();
private int _refId;
private boolean _isNewline = true;
private boolean _isObject = false;
private int _column;
/**
* Creates an uninitialized Hessian input stream.
*/
public HessianDebugState(PrintWriter dbg)
{
_dbg = dbg;
_state = new InitialState();
}
/**
* Reads a character.
*/
public void next(int ch)
throws IOException
{
_state = _state.next(ch);
}
void pushStack(State state)
{
_stateStack.add(state);
}
State popStack()
{
return _stateStack.remove(_stateStack.size() - 1);
}
void println()
{
if (! _isNewline) {
_dbg.println();
_dbg.flush();
}
_isNewline = true;
_column = 0;
}
abstract class State {
State _next;
State()
{
}
State(State next)
{
_next = next;
}
abstract State next(int ch);
boolean isShift(Object value)
{
return false;
}
State shift(Object value)
{
return this;
}
int depth()
{
if (_next != null)
return _next.depth();
else
return 0;
}
void printIndent(int depth)
{
if (_isNewline) {
for (int i = _column; i < depth() + depth; i++) {
_dbg.print(" ");
_column++;
}
}
}
void print(String string)
{
print(0, string);
}
void print(int depth, String string)
{
printIndent(depth);
_dbg.print(string);
_isNewline = false;
_isObject = false;
int p = string.lastIndexOf('\n');
if (p > 0)
_column = string.length() - p - 1;
else
_column += string.length();
}
void println(String string)
{
println(0, string);
}
void println(int depth, String string)
{
printIndent(depth);
_dbg.println(string);
_dbg.flush();
_isNewline = true;
_isObject = false;
_column = 0;
}
void println()
{
if (! _isNewline) {
_dbg.println();
_dbg.flush();
}
_isNewline = true;
_isObject = false;
_column = 0;
}
void printObject(String string)
{
if (_isObject)
println();
printIndent(0);
_dbg.print(string);
_dbg.flush();
_column += string.length();
_isNewline = false;
_isObject = true;
}
protected State nextObject(int ch)
{
switch (ch) {
case -1:
println();
return this;
case 'N':
if (isShift(null))
return shift(null);
else {
printObject("null");
return this;
}
case 'T':
if (isShift(Boolean.TRUE))
return shift(Boolean.TRUE);
else {
printObject("true");
return this;
}
case 'F':
if (isShift(Boolean.FALSE))
return shift(Boolean.FALSE);
else {
printObject("false");
return this;
}
case 0x80: case 0x81: case 0x82: case 0x83:
case 0x84: case 0x85: case 0x86: case 0x87:
case 0x88: case 0x89: case 0x8a: case 0x8b:
case 0x8c: case 0x8d: case 0x8e: case 0x8f:
case 0x90: case 0x91: case 0x92: case 0x93:
case 0x94: case 0x95: case 0x96: case 0x97:
case 0x98: case 0x99: case 0x9a: case 0x9b:
case 0x9c: case 0x9d: case 0x9e: case 0x9f:
case 0xa0: case 0xa1: case 0xa2: case 0xa3:
case 0xa4: case 0xa5: case 0xa6: case 0xa7:
case 0xa8: case 0xa9: case 0xaa: case 0xab:
case 0xac: case 0xad: case 0xae: case 0xaf:
case 0xb0: case 0xb1: case 0xb2: case 0xb3:
case 0xb4: case 0xb5: case 0xb6: case 0xb7:
case 0xb8: case 0xb9: case 0xba: case 0xbb:
case 0xbc: case 0xbd: case 0xbe: case 0xbf:
{
Integer value = new Integer(ch - 0x90);
if (isShift(value))
return shift(value);
else {
printObject(value.toString());
return this;
}
}
case 0xc0: case 0xc1: case 0xc2: case 0xc3:
case 0xc4: case 0xc5: case 0xc6: case 0xc7:
case 0xc8: case 0xc9: case 0xca: case 0xcb:
case 0xcc: case 0xcd: case 0xce: case 0xcf:
return new IntegerState(this, "int", ch - 0xc8, 3);
case 0xd0: case 0xd1: case 0xd2: case 0xd3:
case 0xd4: case 0xd5: case 0xd6: case 0xd7:
return new IntegerState(this, "int", ch - 0xd4, 2);
case 'I':
return new IntegerState(this, "int");
case 0xd8: case 0xd9: case 0xda: case 0xdb:
case 0xdc: case 0xdd: case 0xde: case 0xdf:
case 0xe0: case 0xe1: case 0xe2: case 0xe3:
case 0xe4: case 0xe5: case 0xe6: case 0xe7:
case 0xe8: case 0xe9: case 0xea: case 0xeb:
case 0xec: case 0xed: case 0xee: case 0xef:
{
Long value = new Long(ch - 0xe0);
if (isShift(value))
return shift(value);
else {
printObject(value.toString() + "L");
return this;
}
}
case 0xf0: case 0xf1: case 0xf2: case 0xf3:
case 0xf4: case 0xf5: case 0xf6: case 0xf7:
case 0xf8: case 0xf9: case 0xfa: case 0xfb:
case 0xfc: case 0xfd: case 0xfe: case 0xff:
return new LongState(this, "long", ch - 0xf8, 7);
case 0x38: case 0x39: case 0x3a: case 0x3b:
case 0x3c: case 0x3d: case 0x3e: case 0x3f:
return new LongState(this, "long", ch - 0x3c, 6);
case 0x77:
return new LongState(this, "long", 0, 4);
case 'L':
return new LongState(this, "long");
case 0x67: case 0x68:
{
Double value = new Double(ch - 0x67);
if (isShift(value))
return shift(value);
else {
printObject(value.toString());
return this;
}
}
case 0x69:
return new DoubleIntegerState(this, 3);
case 0x6a:
return new DoubleIntegerState(this, 2);
case 0x6b:
return new FloatState(this);
case 'D':
return new DoubleState(this);
case 0x4a:
return new RefState(this, "Ref", 0, 3);
case 0x4b:
return new RefState(this, "Ref", 0, 2);
case 'R':
return new RefState(this, "Ref");
case 'r':
return new RemoteState(this);
case 'd':
return new DateState(this);
case 0x00:
{
String value = "\"\"";
if (isShift(value))
return shift(value);
else {
printObject(value.toString());
return this;
}
}
case 0x01: case 0x02: case 0x03:
case 0x04: case 0x05: case 0x06: case 0x07:
case 0x08: case 0x09: case 0x0a: case 0x0b:
case 0x0c: case 0x0d: case 0x0e: case 0x0f:
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
return new StringState(this, 'S', ch);
case 'S': case 'X':
return new StringState(this, 'S', true);
case 's': case 'x':
return new StringState(this, 'S', false);
case 0x20:
{
String value = "binary(0)";
if (isShift(value))
return shift(value);
else {
printObject(value.toString());
return this;
}
}
case 0x21: case 0x22: case 0x23:
case 0x24: case 0x25: case 0x26: case 0x27:
case 0x28: case 0x29: case 0x2a: case 0x2b:
case 0x2c: case 0x2d: case 0x2e: case 0x2f:
return new BinaryState(this, 'B', ch - 0x20);
case 'B':
return new BinaryState(this, 'B', true);
case 'b':
return new BinaryState(this, 'B', false);
case 'M':
return new MapState(this, _refId++);
case 'V':
return new ListState(this, _refId++);
case 'v':
return new CompactListState(this, _refId++);
case 'O':
return new ObjectDefState(this);
case 'o':
return new ObjectState(this, _refId++);
case 'P':
return new StreamingState(this, true);
case 'p':
return new StreamingState(this, false);
default:
return this;
}
}
}
class InitialState extends State {
State next(int ch)
{
println();
if (ch == 'r') {
return new ReplyState(this);
}
else if (ch == 'c') {
return new CallState(this);
}
else
return nextObject(ch);
}
}
class IntegerState extends State {
String _typeCode;
int _length;
int _value;
IntegerState(State next, String typeCode)
{
super(next);
_typeCode = typeCode;
}
IntegerState(State next, String typeCode, int value, int length)
{
super(next);
_typeCode = typeCode;
_value = value;
_length = length;
}
State next(int ch)
{
_value = 256 * _value + (ch & 0xff);
if (++_length == 4) {
Integer value = new Integer(_value);
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value.toString());
return _next;
}
}
else
return this;
}
}
class LongState extends State {
String _typeCode;
int _length;
long _value;
LongState(State next, String typeCode)
{
super(next);
_typeCode = typeCode;
}
LongState(State next, String typeCode, long value, int length)
{
super(next);
_typeCode = typeCode;
_value = value;
_length = length;
}
State next(int ch)
{
_value = 256 * _value + (ch & 0xff);
if (++_length == 8) {
Long value = new Long(_value);
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value.toString() + "L");
return _next;
}
}
else
return this;
}
}
class DoubleIntegerState extends State {
int _length;
int _value;
boolean _isFirst = true;
DoubleIntegerState(State next, int length)
{
super(next);
_length = length;
}
State next(int ch)
{
if (_isFirst)
_value = (byte) ch;
else
_value = 256 * _value + (ch & 0xff);
_isFirst = false;
if (++_length == 4) {
Double value = new Double(_value);
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value.toString());
return _next;
}
}
else
return this;
}
}
class RefState extends State {
String _typeCode;
int _length;
int _value;
RefState(State next, String typeCode)
{
super(next);
_typeCode = typeCode;
}
RefState(State next, String typeCode, int value, int length)
{
super(next);
_typeCode = typeCode;
_value = value;
_length = length;
}
State next(int ch)
{
_value = 256 * _value + (ch & 0xff);
if (++_length == 4) {
Integer value = new Integer(_value);
if (_next.isShift(value))
return _next.shift(value);
else {
printObject("ref(#" + value + ")");
return _next;
}
}
else
return this;
}
}
class DateState extends State {
int _length;
long _value;
DateState(State next)
{
super(next);
}
State next(int ch)
{
_value = 256 * _value + (ch & 0xff);
if (++_length == 8) {
java.util.Date value = new java.util.Date(_value);
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value.toString());
return _next;
}
}
else
return this;
}
}
class DoubleState extends State {
int _length;
long _value;
DoubleState(State next)
{
super(next);
}
State next(int ch)
{
_value = 256 * _value + (ch & 0xff);
if (++_length == 8) {
Double value = Double.longBitsToDouble(_value);
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value.toString());
return _next;
}
}
else
return this;
}
}
class FloatState extends State {
int _length;
int _value;
FloatState(State next)
{
super(next);
}
State next(int ch)
{
_value = 256 * _value + (ch & 0xff);
if (++_length == 4) {
Double value = (double) Float.intBitsToFloat(_value);
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value.toString() + "F");
return _next;
}
}
else
return this;
}
}
class StringState extends State {
private static final int TOP = 0;
private static final int UTF_2_1 = 1;
private static final int UTF_3_1 = 2;
private static final int UTF_3_2 = 3;
char _typeCode;
StringBuilder _value = new StringBuilder();
int _lengthIndex;
int _length;
boolean _isLastChunk;
int _utfState;
char _ch;
StringState(State next, char typeCode, boolean isLastChunk)
{
super(next);
_typeCode = typeCode;
_isLastChunk = isLastChunk;
}
StringState(State next, char typeCode, int length)
{
super(next);
_typeCode = typeCode;
_isLastChunk = true;
_length = length;
_lengthIndex = 2;
}
State next(int ch)
{
if (_lengthIndex < 2) {
_length = 256 * _length + (ch & 0xff);
if (++_lengthIndex == 2 && _length == 0 && _isLastChunk) {
if (_next.isShift(_value.toString()))
return _next.shift(_value.toString());
else {
printObject("\"" + _value + "\"");
return _next;
}
}
else
return this;
}
else if (_length == 0) {
if (ch == 's' || ch == 'x') {
_isLastChunk = false;
_lengthIndex = 0;
return this;
}
else if (ch == 'S' || ch == 'X') {
_isLastChunk = true;
_lengthIndex = 0;
return this;
}
else if (ch == 0x00) {
if (_next.isShift(_value.toString()))
return _next.shift(_value.toString());
else {
printObject("\"" + _value + "\"");
return _next;
}
}
else if (0x00 <= ch && ch < 0x20) {
_isLastChunk = true;
_lengthIndex = 2;
_length = ch & 0xff;
return this;
}
else {
println(String.valueOf((char) ch) + ": unexpected character");
return _next;
}
}
switch (_utfState) {
case TOP:
if (ch < 0x80) {
_length--;
_value.append((char) ch);
}
else if (ch < 0xe0) {
_ch = (char) ((ch & 0x1f) << 6);
_utfState = UTF_2_1;
}
else {
_ch = (char) ((ch & 0xf) << 12);
_utfState = UTF_3_1;
}
break;
case UTF_2_1:
case UTF_3_2:
_ch += ch & 0x3f;
_value.append(_ch);
_length--;
_utfState = TOP;
break;
case UTF_3_1:
_ch += (char) ((ch & 0x3f) << 6);
_utfState = UTF_3_2;
break;
}
if (_length == 0 && _isLastChunk) {
if (_next.isShift(_value.toString()))
return _next.shift(_value.toString());
else {
printObject("\"" + _value + "\"");
return _next;
}
}
else
return this;
}
}
class BinaryState extends State {
char _typeCode;
int _totalLength;
int _lengthIndex;
int _length;
boolean _isLastChunk;
BinaryState(State next, char typeCode, boolean isLastChunk)
{
super(next);
_typeCode = typeCode;
_isLastChunk = isLastChunk;
}
BinaryState(State next, char typeCode, int length)
{
super(next);
_typeCode = typeCode;
_isLastChunk = true;
_length = length;
_lengthIndex = 2;
}
State next(int ch)
{
if (_lengthIndex < 2) {
_length = 256 * _length + (ch & 0xff);
if (++_lengthIndex == 2 && _length == 0 && _isLastChunk) {
String value = "binary(" + _totalLength + ")";
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value);
return _next;
}
}
else
return this;
}
else if (_length == 0) {
if (ch == 'b') {
_isLastChunk = false;
_lengthIndex = 0;
return this;
}
else if (ch == 'B') {
_isLastChunk = true;
_lengthIndex = 0;
return this;
}
else if (ch == 0x20) {
String value = "binary(" + _totalLength + ")";
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value);
return _next;
}
}
else if (0x20 <=ch && ch < 0x30) {
_isLastChunk = true;
_lengthIndex = 2;
_length = (ch & 0xff) - 0x20;
return this;
}
else {
println(String.valueOf((char) ch) + ": unexpected character");
return _next;
}
}
_length--;
_totalLength++;
if (_length == 0 && _isLastChunk) {
String value = "binary(" + _totalLength + ")";
if (_next.isShift(value))
return _next.shift(value);
else {
printObject(value);
return _next;
}
}
else
return this;
}
}
class MapState extends State {
private static final int TYPE = 0;
private static final int KEY = 1;
private static final int VALUE = 2;
private int _refId;
private int _state;
private int _valueDepth;
private boolean _hasData;
MapState(State next, int refId)
{
super(next);
_refId = refId;
_state = TYPE;
}
@Override
boolean isShift(Object value)
{
return _state == TYPE;
}
@Override
State shift(Object type)
{
if (_state == TYPE) {
if (type instanceof String) {
_typeDefList.add((String) type);
}
else if (type instanceof Integer) {
int iValue = (Integer) type;
if (iValue >= 0 && iValue < _typeDefList.size())
type = _typeDefList.get(iValue);
}
printObject("map " + type + "(#" + _refId + ")");
_state = VALUE;
return this;
}
else
throw new IllegalStateException();
}
@Override
int depth()
{
if (_state == TYPE)
return _next.depth();
else if (_state == KEY)
return _next.depth() + 2;
else
return _valueDepth;
}
State next(int ch)
{
switch (_state) {
case TYPE:
if (ch == 't') {
return new StringState(this, 't', true);
}
else if (ch == 0x75) {
return new IndirectState(this);
}
else if (ch == 'z') {
printObject("map (#" + _refId + ")");
return _next;
}
else {
printObject("map (#" + _refId + ")");
_state = KEY;
return nextObject(ch);
}
case VALUE:
if (ch == 'z') {
if (_hasData)
println();
return _next;
}
else {
if (_hasData)
println();
_hasData = true;
_state = KEY;
return nextObject(ch);
}
case KEY:
print(" => ");
_isObject = false;
_valueDepth = _column;
_state = VALUE;
return nextObject(ch);
default:
throw new IllegalStateException();
}
}
}
class ObjectDefState extends State {
private static final int TYPE = 1;
private static final int COUNT = 2;
private static final int FIELD = 3;
private static final int COMPLETE = 4;
private int _refId;
private int _state;
private boolean _hasData;
private int _count;
private String _type;
private ArrayList<String> _fields = new ArrayList<String>();
ObjectDefState(State next)
{
super(next);
_state = TYPE;
}
@Override
boolean isShift(Object value)
{
return true;
}
@Override
State shift(Object object)
{
if (_state == TYPE) {
_type = (String) object;
print("/* defun " + _type + " [");
_objectDefList.add(new ObjectDef(_type, _fields));
_state = COUNT;
}
else if (_state == COUNT) {
_count = (Integer) object;
_state = FIELD;
}
else if (_state == FIELD) {
String field = (String) object;
_count--;
_fields.add(field);
if (_fields.size() == 1)
print(field);
else
print(", " + field);
}
else {
throw new UnsupportedOperationException();
}
return this;
}
@Override
int depth()
{
if (_state <= TYPE)
return _next.depth();
else
return _next.depth() + 2;
}
State next(int ch)
{
switch (_state) {
case TYPE:
return nextObject(ch);
case COUNT:
return nextObject(ch);
case FIELD:
if (_count == 0) {
println("] */");
_next.printIndent(0);
return _next.nextObject(ch);
}
else
return nextObject(ch);
default:
throw new IllegalStateException();
}
}
}
class ObjectState extends State {
private static final int TYPE = 0;
private static final int FIELD = 1;
private int _refId;
private int _state;
private ObjectDef _def;
private int _count;
private int _fieldDepth;
ObjectState(State next, int refId)
{
super(next);
_refId = refId;
_state = TYPE;
}
@Override
boolean isShift(Object value)
{
if (_state == TYPE)
return true;
else
return false;
}
@Override
State shift(Object object)
{
if (_state == TYPE) {
int def = (Integer) object;
_def = _objectDefList.get(def);
println("object " + _def.getType() + " (#" + _refId + ")");
_state = FIELD;
if (_def.getFields().size() == 0)
return _next;
}
return this;
}
@Override
int depth()
{
if (_state <= TYPE)
return _next.depth();
else
return _fieldDepth;
}
State next(int ch)
{
switch (_state) {
case TYPE:
return nextObject(ch);
case FIELD:
if (_def.getFields().size() <= _count)
return _next.next(ch);
_fieldDepth = _next.depth() + 2;
println();
print(_def.getFields().get(_count++) + ": ");
_fieldDepth = _column;
_isObject = false;
return nextObject(ch);
default:
throw new IllegalStateException();
}
}
}
class ListState extends State {
private static final int TYPE = 0;
private static final int LENGTH = 1;
private static final int VALUE = 2;
private int _refId;
private int _state;
private boolean _hasData;
private int _count;
private int _valueDepth;
ListState(State next, int refId)
{
super(next);
_refId = refId;
_state = TYPE;
}
@Override
boolean isShift(Object value)
{
return _state == TYPE || _state == LENGTH;
}
@Override
State shift(Object object)
{
if (_state == TYPE) {
Object type = object;
if (type instanceof String) {
_typeDefList.add((String) type);
}
else if (object instanceof Integer) {
int index = (Integer) object;
if (index >= 0 && index < _typeDefList.size())
type = _typeDefList.get(index);
}
printObject("list " + type + "(#" + _refId + ")");
_state = LENGTH;
return this;
}
else if (_state == LENGTH) {
_state = VALUE;
return this;
}
else
return this;
}
@Override
int depth()
{
if (_state <= LENGTH)
return _next.depth();
else if (_state == VALUE)
return _valueDepth;
else
return _next.depth() + 2;
}
State next(int ch)
{
switch (_state) {
case TYPE:
if (ch == 't') {
return new StringState(this, 't', true);
}
else if (ch == TYPE_REF) {
return new IndirectState(this);
}
else if (ch == 'l') {
printObject("list (#" + _refId + ")");
_state = LENGTH;
return new IntegerState(this, "length");
}
else if (ch == LENGTH_BYTE) {
printObject("list (#" + _refId + ")");
_state = LENGTH;
return new IntegerState(this, "length", 0, 3);
}
else if (ch == 'z') {
printObject("list (#" + _refId + ")");
return _next;
}
else {
printObject("list (#" + _refId + ")");
_state = VALUE;
_valueDepth = _next.depth() + 2;
println();
printObject(_count++ + ": ");
_valueDepth = _column;
_isObject = false;
return nextObject(ch);
}
case LENGTH:
if (ch == 'z') {
return _next;
}
else if (ch == 'l') {
return new IntegerState(this, "length");
}
else if (ch == LENGTH_BYTE) {
return new IntegerState(this, "length", 0, 3);
}
else {
_state = VALUE;
_valueDepth = _next.depth() + 2;
println();
printObject(_count++ + ": ");
_valueDepth = _column;
_isObject = false;
return nextObject(ch);
}
case VALUE:
if (ch == 'z') {
if (_count > 0)
println();
return _next;
}
else {
_valueDepth = _next.depth() + 2;
println();
printObject(_count++ + ": ");
_valueDepth = _column;
_isObject = false;
return nextObject(ch);
}
default:
throw new IllegalStateException();
}
}
}
class CompactListState extends State {
private static final int TYPE = 0;
private static final int LENGTH = 1;
private static final int VALUE = 2;
private int _refId;
private int _state;
private boolean _hasData;
private int _length;
private int _count;
private int _valueDepth;
CompactListState(State next, int refId)
{
super(next);
_refId = refId;
_state = TYPE;
}
@Override
boolean isShift(Object value)
{
return _state == TYPE || _state == LENGTH;
}
@Override
State shift(Object object)
{
if (_state == TYPE) {
Object type = object;
if (object instanceof Integer) {
int index = (Integer) object;
if (index >= 0 && index < _typeDefList.size())
type = _typeDefList.get(index);
}
printObject("list " + type + "(#" + _refId + ")");
_state = LENGTH;
return this;
}
else if (_state == LENGTH) {
_length = (Integer) object;
_state = VALUE;
if (_length == 0)
return _next;
else
return this;
}
else
return this;
}
@Override
int depth()
{
if (_state <= LENGTH)
return _next.depth();
else if (_state == VALUE)
return _valueDepth;
else
return _next.depth() + 2;
}
State next(int ch)
{
switch (_state) {
case TYPE:
return nextObject(ch);
case LENGTH:
return nextObject(ch);
case VALUE:
if (_length <= _count)
return _next.next(ch);
else {
_valueDepth = _next.depth() + 2;
println();
printObject(_count++ + ": ");
_valueDepth = _column;
_isObject = false;
return nextObject(ch);
}
default:
throw new IllegalStateException();
}
}
}
class CallState extends State {
private static final int MAJOR = 0;
private static final int MINOR = 1;
private static final int HEADER = 2;
private static final int METHOD = 3;
private static final int VALUE = 4;
private static final int ARG = 5;
private int _state;
private int _major;
private int _minor;
CallState(State next)
{
super(next);
}
int depth()
{
return _next.depth() + 2;
}
State next(int ch)
{
switch (_state) {
case MAJOR:
_major = ch;
_state = MINOR;
return this;
case MINOR:
_minor = ch;
_state = HEADER;
println(-2, "call " + _major + "." + _minor);
return this;
case HEADER:
if (ch == 'H') {
println();
print("header ");
_isObject = false;
_state = VALUE;
return new StringState(this, 'H', true);
}
else if (ch == 'm') {
println();
print("method ");
_isObject = false;
_state = ARG;
return new StringState(this, 'm', true);
}
else {
println((char) ch + ": unexpected char");
return popStack();
}
case VALUE:
print(" => ");
_isObject = false;
_state = HEADER;
return nextObject(ch);
case ARG:
if (ch == 'z')
return _next;
else
return nextObject(ch);
default:
throw new IllegalStateException();
}
}
}
class ReplyState extends State {
private static final int MAJOR = 0;
private static final int MINOR = 1;
private static final int HEADER = 2;
private static final int VALUE = 3;
private static final int END = 4;
private int _state;
private int _major;
private int _minor;
ReplyState(State next)
{
_next = next;
}
int depth()
{
return _next.depth() + 2;
}
State next(int ch)
{
switch (_state) {
case MAJOR:
if (ch == 't' || ch == 'S')
return new RemoteState(this).next(ch);
_major = ch;
_state = MINOR;
return this;
case MINOR:
_minor = ch;
_state = HEADER;
println(-2, "reply " + _major + "." + _minor);
return this;
case HEADER:
if (ch == 'H') {
_state = VALUE;
return new StringState(this, 'H', true);
}
else if (ch == 'f') {
print("fault ");
_isObject = false;
_state = END;
return new MapState(this, 0);
}
else {
_state = END;
return nextObject(ch);
}
case VALUE:
_state = HEADER;
return nextObject(ch);
case END:
println();
if (ch == 'z') {
return _next;
}
else
return _next.next(ch);
default:
throw new IllegalStateException();
}
}
}
class IndirectState extends State {
IndirectState(State next)
{
super(next);
}
boolean isShift(Object object)
{
return _next.isShift(object);
}
State shift(Object object)
{
return _next.shift(object);
}
State next(int ch)
{
return nextObject(ch);
}
}
class RemoteState extends State {
private static final int TYPE = 0;
private static final int VALUE = 1;
private static final int END = 2;
private int _state;
private int _major;
private int _minor;
RemoteState(State next)
{
super(next);
}
State next(int ch)
{
switch (_state) {
case TYPE:
println(-1, "remote");
if (ch == 't') {
_state = VALUE;
return new StringState(this, 't', false);
}
else {
_state = END;
return nextObject(ch);
}
case VALUE:
_state = END;
return _next.nextObject(ch);
case END:
return _next.next(ch);
default:
throw new IllegalStateException();
}
}
}
class StreamingState extends State {
private int _digit;
private int _length;
private boolean _isLast;
private boolean _isFirst = true;
private State _childState;
StreamingState(State next, boolean isLast)
{
super(next);
_isLast = isLast;
_childState = new InitialState();
}
State next(int ch)
{
if (_digit < 2) {
_length = 256 * _length + ch;
_digit++;
if (_digit == 2 && _length == 0 && _isLast) {
_refId = 0;
return _next;
}
else {
if (_digit == 2)
println(-1, "packet-start(" + _length + ")");
return this;
}
}
else if (_length == 0) {
_isLast = (ch == 'P');
_digit = 0;
return this;
}
_childState = _childState.next(ch);
_length--;
if (_length == 0 && _isLast) {
println(-1, "");
println(-1, "packet-end");
_refId = 0;
return _next;
}
else
return this;
}
}
static class ObjectDef {
private String _type;
private ArrayList<String> _fields;
ObjectDef(String type, ArrayList<String> fields)
{
_type = type;
_fields = fields;
}
String getType()
{
return _type;
}
ArrayList<String> getFields()
{
return _fields;
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianDebugState.java | Java | asf20 | 33,354 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.InputStream;
/**
* Serializing a stream object.
*/
public class InputStreamSerializer extends AbstractSerializer {
public InputStreamSerializer()
{
}
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
InputStream is = (InputStream) obj;
if (is == null)
out.writeNull();
else {
byte []buf = new byte[1024];
int len;
while ((len = is.read(buf, 0, buf.length)) > 0) {
out.writeByteBufferPart(buf, 0, len);
}
out.writeByteBufferEnd(buf, 0, 0);
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/InputStreamSerializer.java | Java | asf20 | 2,872 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
/**
* Serializing an object for known object types.
*/
public class BasicDeserializer extends AbstractDeserializer {
public static final int NULL = BasicSerializer.NULL;
public static final int BOOLEAN = BasicSerializer.BOOLEAN;
public static final int BYTE = BasicSerializer.BYTE;
public static final int SHORT = BasicSerializer.SHORT;
public static final int INTEGER = BasicSerializer.INTEGER;
public static final int LONG = BasicSerializer.LONG;
public static final int FLOAT = BasicSerializer.FLOAT;
public static final int DOUBLE = BasicSerializer.DOUBLE;
public static final int CHARACTER = BasicSerializer.CHARACTER;
public static final int CHARACTER_OBJECT = BasicSerializer.CHARACTER_OBJECT;
public static final int STRING = BasicSerializer.STRING;
public static final int DATE = BasicSerializer.DATE;
public static final int NUMBER = BasicSerializer.NUMBER;
public static final int OBJECT = BasicSerializer.OBJECT;
public static final int BOOLEAN_ARRAY = BasicSerializer.BOOLEAN_ARRAY;
public static final int BYTE_ARRAY = BasicSerializer.BYTE_ARRAY;
public static final int SHORT_ARRAY = BasicSerializer.SHORT_ARRAY;
public static final int INTEGER_ARRAY = BasicSerializer.INTEGER_ARRAY;
public static final int LONG_ARRAY = BasicSerializer.LONG_ARRAY;
public static final int FLOAT_ARRAY = BasicSerializer.FLOAT_ARRAY;
public static final int DOUBLE_ARRAY = BasicSerializer.DOUBLE_ARRAY;
public static final int CHARACTER_ARRAY = BasicSerializer.CHARACTER_ARRAY;
public static final int STRING_ARRAY = BasicSerializer.STRING_ARRAY;
public static final int OBJECT_ARRAY = BasicSerializer.OBJECT_ARRAY;
private int _code;
public BasicDeserializer(int code)
{
_code = code;
}
public Class getType()
{
switch (_code) {
case NULL:
return void.class;
case BOOLEAN:
return Boolean.class;
case BYTE:
return Byte.class;
case SHORT:
return Short.class;
case INTEGER:
return Integer.class;
case LONG:
return Long.class;
case FLOAT:
return Float.class;
case DOUBLE:
return Double.class;
case CHARACTER:
return Character.class;
case CHARACTER_OBJECT:
return Character.class;
case STRING:
return String.class;
case DATE:
return Date.class;
case NUMBER:
return Number.class;
case OBJECT:
return Object.class;
case BOOLEAN_ARRAY:
return boolean[].class;
case BYTE_ARRAY:
return byte[].class;
case SHORT_ARRAY:
return short[].class;
case INTEGER_ARRAY:
return int[].class;
case LONG_ARRAY:
return long[].class;
case FLOAT_ARRAY:
return float[].class;
case DOUBLE_ARRAY:
return double[].class;
case CHARACTER_ARRAY:
return char[].class;
case STRING_ARRAY:
return String[].class;
case OBJECT_ARRAY:
return Object[].class;
default:
throw new UnsupportedOperationException();
}
}
public Object readObject(AbstractHessianInput in)
throws IOException
{
switch (_code) {
case NULL:
// hessian/3490
in.readObject();
return null;
case BOOLEAN:
return Boolean.valueOf(in.readBoolean());
case BYTE:
return Byte.valueOf((byte) in.readInt());
case SHORT:
return Short.valueOf((short) in.readInt());
case INTEGER:
return Integer.valueOf(in.readInt());
case LONG:
return Long.valueOf(in.readLong());
case FLOAT:
return Float.valueOf((float) in.readDouble());
case DOUBLE:
return Double.valueOf(in.readDouble());
case STRING:
return in.readString();
case OBJECT:
return in.readObject();
case CHARACTER:
{
String s = in.readString();
if (s == null || s.equals(""))
return Character.valueOf((char) 0);
else
return Character.valueOf(s.charAt(0));
}
case CHARACTER_OBJECT:
{
String s = in.readString();
if (s == null || s.equals(""))
return null;
else
return Character.valueOf(s.charAt(0));
}
case DATE:
return new Date(in.readUTCDate());
case NUMBER:
return in.readObject();
case BYTE_ARRAY:
return in.readBytes();
case CHARACTER_ARRAY:
{
String s = in.readString();
if (s == null)
return null;
else {
int len = s.length();
char []chars = new char[len];
s.getChars(0, len, chars, 0);
return chars;
}
}
case BOOLEAN_ARRAY:
case SHORT_ARRAY:
case INTEGER_ARRAY:
case LONG_ARRAY:
case FLOAT_ARRAY:
case DOUBLE_ARRAY:
case STRING_ARRAY:
{
int code = in.readListStart();
switch (code) {
case 'N':
return null;
case 0x10: case 0x11: case 0x12: case 0x13:
case 0x14: case 0x15: case 0x16: case 0x17:
case 0x18: case 0x19: case 0x1a: case 0x1b:
case 0x1c: case 0x1d: case 0x1e: case 0x1f:
int length = code - 0x10;
in.readInt();
return readLengthList(in, length);
default:
String type = in.readType();
length = in.readLength();
return readList(in, length);
}
}
default:
throw new UnsupportedOperationException();
}
}
public Object readList(AbstractHessianInput in, int length)
throws IOException
{
switch (_code) {
case BOOLEAN_ARRAY: {
if (length >= 0) {
boolean []data = new boolean[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readBoolean();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
while (! in.isEnd())
list.add(Boolean.valueOf(in.readBoolean()));
in.readEnd();
boolean []data = new boolean[list.size()];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = ((Boolean) list.get(i)).booleanValue();
return data;
}
}
case SHORT_ARRAY: {
if (length >= 0) {
short []data = new short[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = (short) in.readInt();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
while (! in.isEnd())
list.add(Short.valueOf((short) in.readInt()));
in.readEnd();
short []data = new short[list.size()];
for (int i = 0; i < data.length; i++)
data[i] = ((Short) list.get(i)).shortValue();
in.addRef(data);
return data;
}
}
case INTEGER_ARRAY: {
if (length >= 0) {
int []data = new int[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readInt();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
while (! in.isEnd())
list.add(Integer.valueOf(in.readInt()));
in.readEnd();
int []data = new int[list.size()];
for (int i = 0; i < data.length; i++)
data[i] = ((Integer) list.get(i)).intValue();
in.addRef(data);
return data;
}
}
case LONG_ARRAY: {
if (length >= 0) {
long []data = new long[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readLong();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
while (! in.isEnd())
list.add(Long.valueOf(in.readLong()));
in.readEnd();
long []data = new long[list.size()];
for (int i = 0; i < data.length; i++)
data[i] = ((Long) list.get(i)).longValue();
in.addRef(data);
return data;
}
}
case FLOAT_ARRAY: {
if (length >= 0) {
float []data = new float[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = (float) in.readDouble();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
while (! in.isEnd())
list.add(new Float(in.readDouble()));
in.readEnd();
float []data = new float[list.size()];
for (int i = 0; i < data.length; i++)
data[i] = ((Float) list.get(i)).floatValue();
in.addRef(data);
return data;
}
}
case DOUBLE_ARRAY: {
if (length >= 0) {
double []data = new double[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readDouble();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
while (! in.isEnd())
list.add(new Double(in.readDouble()));
in.readEnd();
double []data = new double[list.size()];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = ((Double) list.get(i)).intValue();
in.readEnd();
return data;
}
}
case STRING_ARRAY: {
if (length >= 0) {
String []data = new String[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readString();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
while (! in.isEnd())
list.add(in.readString());
in.readEnd();
String []data = new String[list.size()];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = (String) list.get(i);
in.readEnd();
return data;
}
}
case OBJECT_ARRAY: {
if (length >= 0) {
Object []data = new Object[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readObject();
in.readEnd();
return data;
}
else {
ArrayList list = new ArrayList();
in.addRef(list); // XXX: potential issues here
while (! in.isEnd())
list.add(in.readObject());
in.readEnd();
Object []data = new Object[list.size()];
for (int i = 0; i < data.length; i++)
data[i] = (Object) list.get(i);
return data;
}
}
default:
throw new UnsupportedOperationException(String.valueOf(this));
}
}
public Object readLengthList(AbstractHessianInput in, int length)
throws IOException
{
switch (_code) {
case BOOLEAN_ARRAY: {
boolean []data = new boolean[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readBoolean();
return data;
}
case SHORT_ARRAY: {
short []data = new short[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = (short) in.readInt();
return data;
}
case INTEGER_ARRAY: {
int []data = new int[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readInt();
return data;
}
case FLOAT_ARRAY: {
float []data = new float[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = (float) in.readDouble();
return data;
}
case DOUBLE_ARRAY: {
double []data = new double[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readDouble();
return data;
}
case STRING_ARRAY: {
String []data = new String[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readString();
return data;
}
case OBJECT_ARRAY: {
Object []data = new Object[length];
in.addRef(data);
for (int i = 0; i < data.length; i++)
data[i] = in.readObject();
return data;
}
default:
throw new UnsupportedOperationException(String.valueOf(this));
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/BasicDeserializer.java | Java | asf20 | 14,648 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.logging.*;
/**
* Serializing an object.
*/
abstract public class AbstractSerializer implements Serializer {
protected static final Logger log
= Logger.getLogger(AbstractSerializer.class.getName());
abstract public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException;
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/AbstractSerializer.java | Java | asf20 | 2,622 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
/**
* Interface for any hessian remote object.
*/
public interface HessianRemoteObject {
public String getHessianType();
public String getHessianURL();
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianRemoteObject.java | Java | asf20 | 2,427 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.util.HashMap;
/**
* Factory for returning serialization methods.
*/
public class ExtSerializerFactory extends AbstractSerializerFactory {
private HashMap _serializerMap = new HashMap();
private HashMap _deserializerMap = new HashMap();
/**
* Adds a serializer.
*
* @param cl the class of the serializer
* @param serializer the serializer
*/
public void addSerializer(Class cl, Serializer serializer)
{
_serializerMap.put(cl, serializer);
}
/**
* Adds a deserializer.
*
* @param cl the class of the deserializer
* @param deserializer the deserializer
*/
public void addDeserializer(Class cl, Deserializer deserializer)
{
_deserializerMap.put(cl, deserializer);
}
/**
* Returns the serializer for a class.
*
* @param cl the class of the object that needs to be serialized.
*
* @return a serializer object for the serialization.
*/
public Serializer getSerializer(Class cl)
throws HessianProtocolException
{
return (Serializer) _serializerMap.get(cl);
}
/**
* Returns the deserializer for a class.
*
* @param cl the class of the object that needs to be deserialized.
*
* @return a deserializer object for the serialization.
*/
public Deserializer getDeserializer(Class cl)
throws HessianProtocolException
{
return (Deserializer) _deserializerMap.get(cl);
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/ExtSerializerFactory.java | Java | asf20 | 3,671 |
/*
* Copyright (c) 2001-2008 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.io.OutputStream;
import java.util.IdentityHashMap;
/**
* Output stream for Hessian requests, compatible with microedition
* Java. It only uses classes and types available in JDK.
*
* <p>Since HessianOutput does not depend on any classes other than
* in the JDK, it can be extracted independently into a smaller package.
*
* <p>HessianOutput is unbuffered, so any client needs to provide
* its own buffering.
*
* <pre>
* OutputStream os = ...; // from http connection
* HessianOutput out = new HessianOutput(os);
* String value;
*
* out.startCall("hello"); // start hello call
* out.writeString("arg1"); // write a string argument
* out.completeCall(); // complete the call
* </pre>
*/
public class HessianOutput extends AbstractHessianOutput {
// the output stream/
protected OutputStream os;
// map of references
private IdentityHashMap _refs;
private int _version = 1;
/**
* Creates a new Hessian output stream, initialized with an
* underlying output stream.
*
* @param os the underlying output stream.
*/
public HessianOutput(OutputStream os)
{
init(os);
}
/**
* Creates an uninitialized Hessian output stream.
*/
public HessianOutput()
{
}
/**
* Initializes the output
*/
public void init(OutputStream os)
{
this.os = os;
_refs = null;
if (_serializerFactory == null)
_serializerFactory = new SerializerFactory();
}
/**
* Sets the client's version.
*/
public void setVersion(int version)
{
_version = version;
}
/**
* Writes a complete method call.
*/
public void call(String method, Object []args)
throws IOException
{
startCall(method);
if (args != null) {
for (int i = 0; i < args.length; i++)
writeObject(args[i]);
}
completeCall();
}
/**
* Starts the method call. Clients would use <code>startCall</code>
* instead of <code>call</code> if they wanted finer control over
* writing the arguments, or needed to write headers.
*
* <code><pre>
* c major minor
* m b16 b8 method-name
* </pre></code>
*
* @param method the method name to call.
*/
public void startCall(String method)
throws IOException
{
os.write('c');
os.write(_version);
os.write(0);
os.write('m');
int len = method.length();
os.write(len >> 8);
os.write(len);
printString(method, 0, len);
}
/**
* Writes the call tag. This would be followed by the
* headers and the method tag.
*
* <code><pre>
* c major minor
* </pre></code>
*
* @param method the method name to call.
*/
public void startCall()
throws IOException
{
os.write('c');
os.write(0);
os.write(1);
}
/**
* Writes the method tag.
*
* <code><pre>
* m b16 b8 method-name
* </pre></code>
*
* @param method the method name to call.
*/
public void writeMethod(String method)
throws IOException
{
os.write('m');
int len = method.length();
os.write(len >> 8);
os.write(len);
printString(method, 0, len);
}
/**
* Completes.
*
* <code><pre>
* z
* </pre></code>
*/
public void completeCall()
throws IOException
{
os.write('z');
}
/**
* Starts the reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* r
* </pre>
*/
public void startReply()
throws IOException
{
os.write('r');
os.write(1);
os.write(0);
}
/**
* Completes reading the reply
*
* <p>A successful completion will have a single value:
*
* <pre>
* z
* </pre>
*/
public void completeReply()
throws IOException
{
os.write('z');
}
/**
* Writes a header name. The header value must immediately follow.
*
* <code><pre>
* H b16 b8 foo <em>value</em>
* </pre></code>
*/
public void writeHeader(String name)
throws IOException
{
int len = name.length();
os.write('H');
os.write(len >> 8);
os.write(len);
printString(name);
}
/**
* Writes a fault. The fault will be written
* as a descriptive string followed by an object:
*
* <code><pre>
* f
* <string>code
* <string>the fault code
*
* <string>message
* <string>the fault mesage
*
* <string>detail
* mt\x00\xnnjavax.ejb.FinderException
* ...
* z
* z
* </pre></code>
*
* @param code the fault code, a three digit
*/
public void writeFault(String code, String message, Object detail)
throws IOException
{
os.write('f');
writeString("code");
writeString(code);
writeString("message");
writeString(message);
if (detail != null) {
writeString("detail");
writeObject(detail);
}
os.write('z');
}
/**
* Writes any object to the output stream.
*/
public void writeObject(Object object)
throws IOException
{
if (object == null) {
writeNull();
return;
}
Serializer serializer;
serializer = _serializerFactory.getSerializer(object.getClass());
serializer.writeObject(object, this);
}
/**
* Writes the list header to the stream. List writers will call
* <code>writeListBegin</code> followed by the list contents and then
* call <code>writeListEnd</code>.
*
* <code><pre>
* V
* t b16 b8 type
* l b32 b24 b16 b8
* </pre></code>
*/
public boolean writeListBegin(int length, String type)
throws IOException
{
os.write('V');
if (type != null) {
os.write('t');
printLenString(type);
}
if (length >= 0) {
os.write('l');
os.write(length >> 24);
os.write(length >> 16);
os.write(length >> 8);
os.write(length);
}
return true;
}
/**
* Writes the tail of the list to the stream.
*/
public void writeListEnd()
throws IOException
{
os.write('z');
}
/**
* Writes the map header to the stream. Map writers will call
* <code>writeMapBegin</code> followed by the map contents and then
* call <code>writeMapEnd</code>.
*
* <code><pre>
* Mt b16 b8 (<key> <value>)z
* </pre></code>
*/
public void writeMapBegin(String type)
throws IOException
{
os.write('M');
os.write('t');
printLenString(type);
}
/**
* Writes the tail of the map to the stream.
*/
public void writeMapEnd()
throws IOException
{
os.write('z');
}
/**
* Writes a remote object reference to the stream. The type is the
* type of the remote interface.
*
* <code><pre>
* 'r' 't' b16 b8 type url
* </pre></code>
*/
public void writeRemote(String type, String url)
throws IOException
{
os.write('r');
os.write('t');
printLenString(type);
os.write('S');
printLenString(url);
}
/**
* Writes a boolean value to the stream. The boolean will be written
* with the following syntax:
*
* <code><pre>
* T
* F
* </pre></code>
*
* @param value the boolean value to write.
*/
public void writeBoolean(boolean value)
throws IOException
{
if (value)
os.write('T');
else
os.write('F');
}
/**
* Writes an integer value to the stream. The integer will be written
* with the following syntax:
*
* <code><pre>
* I b32 b24 b16 b8
* </pre></code>
*
* @param value the integer value to write.
*/
public void writeInt(int value)
throws IOException
{
os.write('I');
os.write(value >> 24);
os.write(value >> 16);
os.write(value >> 8);
os.write(value);
}
/**
* Writes a long value to the stream. The long will be written
* with the following syntax:
*
* <code><pre>
* L b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param value the long value to write.
*/
public void writeLong(long value)
throws IOException
{
os.write('L');
os.write((byte) (value >> 56));
os.write((byte) (value >> 48));
os.write((byte) (value >> 40));
os.write((byte) (value >> 32));
os.write((byte) (value >> 24));
os.write((byte) (value >> 16));
os.write((byte) (value >> 8));
os.write((byte) (value));
}
/**
* Writes a double value to the stream. The double will be written
* with the following syntax:
*
* <code><pre>
* D b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param value the double value to write.
*/
public void writeDouble(double value)
throws IOException
{
long bits = Double.doubleToLongBits(value);
os.write('D');
os.write((byte) (bits >> 56));
os.write((byte) (bits >> 48));
os.write((byte) (bits >> 40));
os.write((byte) (bits >> 32));
os.write((byte) (bits >> 24));
os.write((byte) (bits >> 16));
os.write((byte) (bits >> 8));
os.write((byte) (bits));
}
/**
* Writes a date to the stream.
*
* <code><pre>
* T b64 b56 b48 b40 b32 b24 b16 b8
* </pre></code>
*
* @param time the date in milliseconds from the epoch in UTC
*/
public void writeUTCDate(long time)
throws IOException
{
os.write('d');
os.write((byte) (time >> 56));
os.write((byte) (time >> 48));
os.write((byte) (time >> 40));
os.write((byte) (time >> 32));
os.write((byte) (time >> 24));
os.write((byte) (time >> 16));
os.write((byte) (time >> 8));
os.write((byte) (time));
}
/**
* Writes a null value to the stream.
* The null will be written with the following syntax
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeNull()
throws IOException
{
os.write('N');
}
/**
* Writes a string value to the stream using UTF-8 encoding.
* The string will be written with the following syntax:
*
* <code><pre>
* S b16 b8 string-value
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeString(String value)
throws IOException
{
if (value == null) {
os.write('N');
}
else {
int length = value.length();
int offset = 0;
while (length > 0x8000) {
int sublen = 0x8000;
// chunk can't end in high surrogate
char tail = value.charAt(offset + sublen - 1);
if (0xd800 <= tail && tail <= 0xdbff)
sublen--;
os.write('s');
os.write(sublen >> 8);
os.write(sublen);
printString(value, offset, sublen);
length -= sublen;
offset += sublen;
}
os.write('S');
os.write(length >> 8);
os.write(length);
printString(value, offset, length);
}
}
/**
* Writes a string value to the stream using UTF-8 encoding.
* The string will be written with the following syntax:
*
* <code><pre>
* S b16 b8 string-value
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeString(char []buffer, int offset, int length)
throws IOException
{
if (buffer == null) {
os.write('N');
}
else {
while (length > 0x8000) {
int sublen = 0x8000;
// chunk can't end in high surrogate
char tail = buffer[offset + sublen - 1];
if (0xd800 <= tail && tail <= 0xdbff)
sublen--;
os.write('s');
os.write(sublen >> 8);
os.write(sublen);
printString(buffer, offset, sublen);
length -= sublen;
offset += sublen;
}
os.write('S');
os.write(length >> 8);
os.write(length);
printString(buffer, offset, length);
}
}
/**
* Writes a byte array to the stream.
* The array will be written with the following syntax:
*
* <code><pre>
* B b16 b18 bytes
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeBytes(byte []buffer)
throws IOException
{
if (buffer == null)
os.write('N');
else
writeBytes(buffer, 0, buffer.length);
}
/**
* Writes a byte array to the stream.
* The array will be written with the following syntax:
*
* <code><pre>
* B b16 b18 bytes
* </pre></code>
*
* If the value is null, it will be written as
*
* <code><pre>
* N
* </pre></code>
*
* @param value the string value to write.
*/
public void writeBytes(byte []buffer, int offset, int length)
throws IOException
{
if (buffer == null) {
os.write('N');
}
else {
while (length > 0x8000) {
int sublen = 0x8000;
os.write('b');
os.write(sublen >> 8);
os.write(sublen);
os.write(buffer, offset, sublen);
length -= sublen;
offset += sublen;
}
os.write('B');
os.write(length >> 8);
os.write(length);
os.write(buffer, offset, length);
}
}
/**
* Writes a byte buffer to the stream.
*
* <code><pre>
* </pre></code>
*/
public void writeByteBufferStart()
throws IOException
{
}
/**
* Writes a byte buffer to the stream.
*
* <code><pre>
* b b16 b18 bytes
* </pre></code>
*/
public void writeByteBufferPart(byte []buffer, int offset, int length)
throws IOException
{
while (length > 0) {
int sublen = length;
if (0x8000 < sublen)
sublen = 0x8000;
os.write('b');
os.write(sublen >> 8);
os.write(sublen);
os.write(buffer, offset, sublen);
length -= sublen;
offset += sublen;
}
}
/**
* Writes a byte buffer to the stream.
*
* <code><pre>
* b b16 b18 bytes
* </pre></code>
*/
public void writeByteBufferEnd(byte []buffer, int offset, int length)
throws IOException
{
writeBytes(buffer, offset, length);
}
/**
* Writes a reference.
*
* <code><pre>
* R b32 b24 b16 b8
* </pre></code>
*
* @param value the integer value to write.
*/
public void writeRef(int value)
throws IOException
{
os.write('R');
os.write(value >> 24);
os.write(value >> 16);
os.write(value >> 8);
os.write(value);
}
/**
* Writes a placeholder.
*
* <code><pre>
* P
* </pre></code>
*/
public void writePlaceholder()
throws IOException
{
os.write('P');
}
/**
* If the object has already been written, just write its ref.
*
* @return true if we're writing a ref.
*/
public boolean addRef(Object object)
throws IOException
{
if (_refs == null)
_refs = new IdentityHashMap();
Integer ref = (Integer) _refs.get(object);
if (ref != null) {
int value = ref.intValue();
writeRef(value);
return true;
}
else {
_refs.put(object, new Integer(_refs.size()));
return false;
}
}
/**
* Resets the references for streaming.
*/
public void resetReferences()
{
if (_refs != null)
_refs.clear();
}
/**
* Removes a reference.
*/
public boolean removeRef(Object obj)
throws IOException
{
if (_refs != null) {
_refs.remove(obj);
return true;
}
else
return false;
}
/**
* Replaces a reference from one object to another.
*/
public boolean replaceRef(Object oldRef, Object newRef)
throws IOException
{
Integer value = (Integer) _refs.remove(oldRef);
if (value != null) {
_refs.put(newRef, value);
return true;
}
else
return false;
}
/**
* Prints a string to the stream, encoded as UTF-8 with preceeding length
*
* @param v the string to print.
*/
public void printLenString(String v)
throws IOException
{
if (v == null) {
os.write(0);
os.write(0);
}
else {
int len = v.length();
os.write(len >> 8);
os.write(len);
printString(v, 0, len);
}
}
/**
* Prints a string to the stream, encoded as UTF-8
*
* @param v the string to print.
*/
public void printString(String v)
throws IOException
{
printString(v, 0, v.length());
}
/**
* Prints a string to the stream, encoded as UTF-8
*
* @param v the string to print.
*/
public void printString(String v, int offset, int length)
throws IOException
{
for (int i = 0; i < length; i++) {
char ch = v.charAt(i + offset);
if (ch < 0x80)
os.write(ch);
else if (ch < 0x800) {
os.write(0xc0 + ((ch >> 6) & 0x1f));
os.write(0x80 + (ch & 0x3f));
}
else {
os.write(0xe0 + ((ch >> 12) & 0xf));
os.write(0x80 + ((ch >> 6) & 0x3f));
os.write(0x80 + (ch & 0x3f));
}
}
}
/**
* Prints a string to the stream, encoded as UTF-8
*
* @param v the string to print.
*/
public void printString(char []v, int offset, int length)
throws IOException
{
for (int i = 0; i < length; i++) {
char ch = v[i + offset];
if (ch < 0x80)
os.write(ch);
else if (ch < 0x800) {
os.write(0xc0 + ((ch >> 6) & 0x1f));
os.write(0x80 + (ch & 0x3f));
}
else {
os.write(0xe0 + ((ch >> 12) & 0xf));
os.write(0x80 + ((ch >> 6) & 0x3f));
os.write(0x80 + (ch & 0x3f));
}
}
}
public void flush()
throws IOException
{
if (this.os != null)
this.os.flush();
}
public void close()
throws IOException
{
if (this.os != null)
this.os.flush();
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianOutput.java | Java | asf20 | 20,116 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Serializing a Java array.
*/
public class ArraySerializer extends AbstractSerializer {
public void writeObject(Object obj, AbstractHessianOutput out)
throws IOException
{
if (out.addRef(obj))
return;
Object []array = (Object []) obj;
boolean hasEnd = out.writeListBegin(array.length,
getArrayType(obj.getClass()));
for (int i = 0; i < array.length; i++)
out.writeObject(array[i]);
if (hasEnd)
out.writeListEnd();
}
/**
* Returns the <type> name for a <list>.
*/
private String getArrayType(Class cl)
{
if (cl.isArray())
return '[' + getArrayType(cl.getComponentType());
String name = cl.getName();
if (name.equals("java.lang.String"))
return "string";
else if (name.equals("java.lang.Object"))
return "object";
else if (name.equals("java.util.Date"))
return "date";
else
return name;
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/ArraySerializer.java | Java | asf20 | 3,226 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
import java.util.*;
import java.lang.reflect.*;
/**
* Deserializing a JDK 1.2 Map.
*/
public class MapDeserializer extends AbstractMapDeserializer {
private Class _type;
private Constructor _ctor;
public MapDeserializer(Class type)
{
if (type == null)
type = HashMap.class;
_type = type;
Constructor []ctors = type.getConstructors();
for (int i = 0; i < ctors.length; i++) {
if (ctors[i].getParameterTypes().length == 0)
_ctor = ctors[i];
}
if (_ctor == null) {
try {
_ctor = HashMap.class.getConstructor(new Class[0]);
} catch (Exception e) {
throw new IllegalStateException(e);
}
}
}
public Class getType()
{
if (_type != null)
return _type;
else
return HashMap.class;
}
public Object readMap(AbstractHessianInput in)
throws IOException
{
Map map;
if (_type == null)
map = new HashMap();
else if (_type.equals(Map.class))
map = new HashMap();
else if (_type.equals(SortedMap.class))
map = new TreeMap();
else {
try {
map = (Map) _ctor.newInstance();
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
in.addRef(map);
while (! in.isEnd()) {
map.put(in.readObject(), in.readObject());
}
in.readEnd();
return map;
}
@Override
public Object readObject(AbstractHessianInput in,
String []fieldNames)
throws IOException
{
Map map = createMap();
int ref = in.addRef(map);
for (int i = 0; i < fieldNames.length; i++) {
String name = fieldNames[i];
map.put(name, in.readObject());
}
return map;
}
private Map createMap()
throws IOException
{
if (_type == null)
return new HashMap();
else if (_type.equals(Map.class))
return new HashMap();
else if (_type.equals(SortedMap.class))
return new TreeMap();
else {
try {
return (Map) _ctor.newInstance();
} catch (Exception e) {
throw new IOExceptionWrapper(e);
}
}
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/MapDeserializer.java | Java | asf20 | 4,394 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
import java.io.IOException;
/**
* Looks up remote objects. The default just returns a HessianRemote object.
*/
public interface HessianRemoteResolver {
/**
* Looks up a proxy object.
*/
public Object lookup(String type, String url)
throws IOException;
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianRemoteResolver.java | Java | asf20 | 2,539 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.hessian.io;
/**
* Encapsulates a remote address when no stub is available, e.g. for
* Java MicroEdition.
*/
public class HessianRemote {
private String type;
private String url;
/**
* Creates a new Hessian remote object.
*
* @param type the remote stub interface
* @param url the remote url
*/
public HessianRemote(String type, String url)
{
this.type = type;
this.url = url;
}
/**
* Creates an uninitialized Hessian remote.
*/
public HessianRemote()
{
}
/**
* Returns the remote api class name.
*/
public String getType()
{
return type;
}
/**
* Returns the remote URL.
*/
public String getURL()
{
return url;
}
/**
* Sets the remote URL.
*/
public void setURL(String url)
{
this.url = url;
}
/**
* Defines the hashcode.
*/
public int hashCode()
{
return url.hashCode();
}
/**
* Defines equality
*/
public boolean equals(Object obj)
{
if (! (obj instanceof HessianRemote))
return false;
HessianRemote remote = (HessianRemote) obj;
return url.equals(remote.url);
}
/**
* Readable version of the remote.
*/
public String toString()
{
return "[HessianRemote " + url + "]";
}
}
| zzgfly-hessdroid | src/com/caucho/hessian/io/HessianRemote.java | Java | asf20 | 3,513 |
/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Burlap", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.services.client;
/**
* Factory for creating client stubs. The returned stub will
* call the remote object for all methods.
*
* <pre>
* URL url = new URL("http://localhost:8080/ejb/hello");
* HelloHome hello = (HelloHome) factory.create(HelloHome.class, url);
* </pre>
*
* After creation, the stub can be like a regular Java class. Because
* it makes remote calls, it can throw more exceptions than a Java class.
* In particular, it may throw protocol exceptions.
*/
public interface ServiceProxyFactory {
/**
* Creates a new proxy with the specified URL. The returned object
* is a proxy with the interface specified by api.
*
* <pre>
* String url = "http://localhost:8080/ejb/hello");
* HelloHome hello = (HelloHome) factory.create(HelloHome.class, url);
* </pre>
*
* @param api the interface the proxy class needs to implement
* @param url the URL where the client object is located.
*
* @return a proxy to the object with the specified interface.
* @throws java.net.MalformedURLException in case url to remote interface is invalid
*/
public <T>T create(Class<T> api, String url)
throws java.net.MalformedURLException;
}
| zzgfly-hessdroid | src/com/caucho/services/client/ServiceProxyFactory.java | Java | asf20 | 3,442 |
/*
* Copyright (c) 2001-2004 Caucho Technology, Inc. All rights reserved.
*
* The Apache Software License, Version 1.1
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Caucho Technology (http://www.caucho.com/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "Hessian", "Resin", and "Caucho" must not be used to
* endorse or promote products derived from this software without prior
* written permission. For written permission, please contact
* info@caucho.com.
*
* 5. Products derived from this software may not be called "Resin"
* nor may "Resin" appear in their names without prior written
* permission of Caucho Technology.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL CAUCHO TECHNOLOGY OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY,
* OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT
* OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
* BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
* WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE
* OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN
* IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* @author Scott Ferguson
*/
package com.caucho.services.server;
import java.io.InputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
/**
* Proxy class for Hessian services.
*/
abstract public class AbstractSkeleton {
private Class _apiClass;
private Class _homeClass;
private Class _objectClass;
private HashMap _methodMap = new HashMap();
/**
* Create a new hessian skeleton.
*
* @param apiClass the API interface
*/
protected AbstractSkeleton(Class apiClass)
{
_apiClass = apiClass;
Method []methodList = apiClass.getMethods();
for (int i = 0; i < methodList.length; i++) {
Method method = methodList[i];
if (_methodMap.get(method.getName()) == null)
_methodMap.put(method.getName(), methodList[i]);
Class []param = method.getParameterTypes();
String mangledName = method.getName() + "__" + param.length;
_methodMap.put(mangledName, methodList[i]);
_methodMap.put(mangleName(method, false), methodList[i]);
}
}
/**
* Returns the API class of the current object.
*/
public String getAPIClassName()
{
return _apiClass.getName();
}
/**
* Returns the API class of the factory/home.
*/
public String getHomeClassName()
{
if (_homeClass != null)
return _homeClass.getName();
else
return getAPIClassName();
}
/**
* Sets the home API class.
*/
public void setHomeClass(Class homeAPI)
{
_homeClass = homeAPI;
}
/**
* Returns the API class of the object URLs
*/
public String getObjectClassName()
{
if (_objectClass != null)
return _objectClass.getName();
else
return getAPIClassName();
}
/**
* Sets the object API class.
*/
public void setObjectClass(Class objectAPI)
{
_objectClass = objectAPI;
}
/**
* Returns the method by the mangled name.
*
* @param mangledName the name passed by the protocol
*/
protected Method getMethod(String mangledName)
{
return (Method) _methodMap.get(mangledName);
}
/**
* Creates a unique mangled method name based on the method name and
* the method parameters.
*
* @param method the method to mangle
* @param isFull if true, mangle the full classname
*
* @return a mangled string.
*/
public static String mangleName(Method method, boolean isFull)
{
StringBuffer sb = new StringBuffer();
sb.append(method.getName());
Class []params = method.getParameterTypes();
for (int i = 0; i < params.length; i++) {
sb.append('_');
sb.append(mangleClass(params[i], isFull));
}
return sb.toString();
}
/**
* Mangles a classname.
*/
public static String mangleClass(Class cl, boolean isFull)
{
String name = cl.getName();
if (name.equals("boolean") || name.equals("java.lang.Boolean"))
return "boolean";
else if (name.equals("int") || name.equals("java.lang.Integer")
|| name.equals("short") || name.equals("java.lang.Short")
|| name.equals("byte") || name.equals("java.lang.Byte"))
return "int";
else if (name.equals("long") || name.equals("java.lang.Long"))
return "long";
else if (name.equals("float") || name.equals("java.lang.Float")
|| name.equals("double") || name.equals("java.lang.Double"))
return "double";
else if (name.equals("java.lang.String")
|| name.equals("com.caucho.util.CharBuffer")
|| name.equals("char") || name.equals("java.lang.Character")
|| name.equals("java.io.Reader"))
return "string";
else if (name.equals("java.util.Date")
|| name.equals("com.caucho.util.QDate"))
return "date";
else if (InputStream.class.isAssignableFrom(cl)
|| name.equals("[B"))
return "binary";
else if (cl.isArray()) {
return "[" + mangleClass(cl.getComponentType(), isFull);
}
else if (name.equals("org.w3c.dom.Node")
|| name.equals("org.w3c.dom.Element")
|| name.equals("org.w3c.dom.Document"))
return "xml";
else if (isFull)
return name;
else {
int p = name.lastIndexOf('.');
if (p > 0)
return name.substring(p + 1);
else
return name;
}
}
public String toString()
{
return getClass().getSimpleName() + "[" + _apiClass.getName() + "]";
}
}
| zzgfly-hessdroid | src/com/caucho/services/server/AbstractSkeleton.java | Java | asf20 | 6,562 |
/*
* Copyright (C) 2009 hessdroid@gmail.com
*
* Licensed 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.
*/
package com.ast.util;
/**
* Parses Set-Cookie HTTP response header and returns the corresponding {@link Cookie} which can be
* used for storing cookie information in java collections.
* <p/>
* <a href="http://www.ietf.org/rfc/rfc2109">RFC 2109</a>
*
* @author hessdroid@gmail.com
*/
public class CookieParser {
/**
* Abstract representation of an HTTP cookie.
*/
public static class Cookie {
public String host;
public String value; // cookie string without the leading intro: "Set-Cookie: "
public String expires;
public String path;
public String domain;
public String sessionId;
public boolean secure;
}
/**
* Parses the given <tt>setCookieString</tt> from an HTTP response and creates a {@link Cookie} from it.
* The {@link Cookie} can be used by clients to send cookie on subsequent requests.
*
* @param host <code>String</code> cookie host
* @param setCookieString <code>String</code> complete cookie string
* @return a {@link Cookie} that was created from the given <tt>setCookieString</tt>
*/
public static Cookie parse(String host, String setCookieString) {
if (host == null) throw new IllegalArgumentException("Parameter \"host\" must not be null");
if (setCookieString == null)
throw new IllegalArgumentException("Parameter \"setCookieString\" must not be null");
Cookie result = new Cookie();
// split the cookie string on any semicolon or space(s)
String[] fields = setCookieString.split(";\\s*");
result.host = host;
// ignore leading cookie intro
result.value = fields[0].startsWith("Set-Cookie: ") ? fields[0].substring(12) : fields[0];
if (result.value.startsWith("JSESSIONID=")) {
result.sessionId = result.value.substring(11);
}
// Parse each field
for (int j = 1; j < fields.length; j++) {
if ("secure".equalsIgnoreCase(fields[j])) {
result.secure = true;
} else if (fields[j].indexOf('=') > 0) {
String[] f = fields[j].split("=");
if ("expires".equalsIgnoreCase(f[0])) {
result.expires = f[1];
} else if ("domain".equalsIgnoreCase(f[0])) {
result.domain = f[1];
} else if ("path".equalsIgnoreCase(f[0])) {
result.path = f[1];
}
}
}
return result;
}
}
| zzgfly-hessdroid | src/com/ast/util/CookieParser.java | Java | asf20 | 3,151 |
#include <security/pam_appl.h>
#include <security/pam_misc.h>
#include <security/pam_modules.h>
#include <stdio.h>
/* 文件pamtest.c
此程序从命令行接收一个用户名作为参数,然后对这个用户名进行auth和account验证.
*/
// 定义一个pam_conv结构,用于与pam通信
static struct pam_conv conv = {
misc_conv,
NULL
};
// 主函数
int main(int argc, char *argv[])
{
pam_handle_t *pamh=NULL;
int retval;
const char *user="nobody";
const char *s1=NULL;
if(argc == 2)
user = argv[1];
else
exit(1);
if(argc > 2) {
fprintf(stderr, "Usage: pamtest0 [username]\n");
exit(1);
}
printf("user: %s\n",user);
retval = 0;
//调用pamtest配置文件
retval = pam_start("pamtest", user, &conv, &pamh);
if (retval == PAM_SUCCESS)
//进行auth类型认证
retval = pam_authenticate(pamh, 0); /* is user really user? */
else {
//如果认证出错,pam_strerror将输出错误信息.
printf("pam_authenticate(): %d\n",retval);
s1=pam_strerror( pamh, retval);
printf("%s\n",s1);
}
if (retval == PAM_SUCCESS)
//进行account类型认证
retval = pam_acct_mgmt(pamh, 0); /* permitted access? */
else {
printf("pam_acct_mgmt() : %d\n",retval);
s1=pam_strerror( pamh, retval);
printf("%s\n",s1);
}
/* This is where we have been authorized or not. */
if (retval == PAM_SUCCESS) {
fprintf(stdout, "Authenticated\n");
} else {
fprintf(stdout, "Not Authenticated\n");
}
if (pam_end(pamh,retval) != PAM_SUCCESS) { /* close Linux-PAM */
pamh = NULL;
fprintf(stderr, "pamtest0: failed to release authenticator\n");
exit(1);
}
return ( retval == PAM_SUCCESS ? 0:1 ); /* indicate success */
}
//END
| zzy-code-test | linux/pam/pamtest.c | C | gpl2 | 1,694 |
all:
cc -o pamtest pamtest.c -lpam -lpam_misc -ldl
| zzy-code-test | linux/pam/makefile | Makefile | gpl2 | 53 |
#!/usr/bin/env python
# ant_spider.py
#
SCREEN_SIZE = (640, 480)
NEST_POSITION = (320, 240)
ANT_COUNT = 20
NEST_SIZE = 100.
import pygame, os, sys
from pygame.locals import *
from random import randint, choice
from gameobjects.vector2 import Vector2
class State(object):
def __init__(self, name):
self.name = name
def do_actions(self):
pass
def check_conditions(self):
pass
def entry_actions(self):
pass
def exit_actions(self):
pass
class StateMachine(object):
def __init__(self):
self.states = {}
self.active_state = None
def add_state(self, state):
self.states[state.name] = state
def think(self):
if self.active_state is None:
return
self.active_state.do_actions()
new_state_name = self.active_state.check_conditions()
if new_state_name is not None:
self.set_state(new_state_name)
def set_state(self, new_state_name):
if self.active_state is not None:
self.active_state.exit_actions()
self.active_state = self.states[new_state_name]
self.active_state.entry_actions()
class World(object):
def __init__(self):
self.entities = {}
self.entity_id = 0
self.background = pygame.surface.Surface(SCREEN_SIZE).convert()
self.background.fill((255, 255, 255))
pygame.draw.circle(self.background, (200, 255, 200), NEST_POSITION, int(NEST_SIZE))
def add_entity(self, entity):
self.entities[self.entity_id] = entity
entity.id = self.entity_id
self.entity_id += 1
def remove_entity(self, entity):
del self.entities[entity.id]
def get(self, entity_id):
if entity_id in self.entities:
return self.entities[entity_id]
else:
return None
def process(self, time_passed):
time_passed_seconds = time_passed / 1000.0
for entity in self.entities.values():
entity.process(time_passed_seconds)
def render(self, surface):
surface.blit(self.background, (0, 0))
for entity in self.entities.itervalues():
entity.render(surface)
def get_close_entity(self, name, location, range=100.):
location = Vector2(*location)
for entity in self.entities.itervalues():
if entity.name == name:
distance = location.get_distance_to(entity.location)
if distance < range:
return entity
return None
class GameEntity(object):
def __init__(self, world, name, image):
self.world = world
self.name = name
self.image = image
self.location = Vector2(0, 0)
self.destination = Vector2(0, 0)
self.speed = 0.
self.brain = StateMachine()
self.id = 0
def render(self, surface):
x, y = self.location
w, h = self.image.get_size()
surface.blit(self.image, (x-w/2, y-h/2))
def process(self, time_passed):
self.brain.think()
if self.speed > 0. and self.location != self.destination:
vec_to_destination = self.destination - self.location
distance_to_destination = vec_to_destination.get_length()
heading = vec_to_destination.get_normalized()
travel_distance = min(distance_to_destination, time_passed * self.speed)
self.location += travel_distance * heading
class Leaf(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "leaf", image)
class Spider(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "spider", image)
self.dead_image = pygame.transform.flip(image, 0, 1)
self.health = 25
self.speed = 50. + randint(-20, 20)
def bitten(self):
self.health -= 1
if self.health <= 0:
self.speed = 0.
self.image = self.dead_image
self.speed = 140.
def render(self, surface):
GameEntity.render(self, surface)
x, y = self.location
w, h = self.image.get_size()
bar_x = x - 12
bar_y = y + h/2
surface.fill( (255, 0, 0), (bar_x, bar_y, 25, 4))
surface.fill( (0, 255, 0), (bar_x, bar_y, self.health, 4))
def process(self, time_passed):
x, y = self.location
if x > SCREEN_SIZE[0] + 2:
self.world.remove_entity(self)
return
GameEntity.process(self, time_passed)
class Ant(GameEntity):
def __init__(self, world, image):
GameEntity.__init__(self, world, "ant", image)
exploring_state = AntStateExploring(self)
seeking_state = AntStateSeeking(self)
delivering_state = AntStateDelivering(self)
hunting_state = AntStateHunting(self)
self.brain.add_state(exploring_state)
self.brain.add_state(seeking_state)
self.brain.add_state(delivering_state)
self.brain.add_state(hunting_state)
self.carry_image = None
def carry(self, image):
self.carry_image = image
def drop(self, surface):
if self.carry_image:
x, y = self.location
w, h = self.carry_image.get_size()
surface.blit(self.carry_image, (x-w, y-h/2))
self.carry_image = None
def render(self, surface):
GameEntity.render(self, surface)
if self.carry_image:
x, y = self.location
w, h = self.carry_image.get_size()
surface.blit(self.carry_image, (x-w, y-h/2))
class AntStateExploring(State):
def __init__(self, ant):
State.__init__(self, "exploring")
self.ant = ant
def random_destination(self):
w, h = SCREEN_SIZE
self.ant.destination = Vector2(randint(0, w), randint(0, h))
def do_actions(self):
if randint(1, 20) == 1:
self.random_destination()
def check_conditions(self):
leaf = self.ant.world.get_close_entity("leaf", self.ant.location)
if leaf is not None:
self.ant.leaf_id = leaf.id
return "seeking"
spider = self.ant.world.get_close_entity("spider", NEST_POSITION, NEST_SIZE)
if spider is not None:
if self.ant.location.get_distance_to(spider.location) < 100.:
self.ant.spider_id = spider.id
return "hunting"
return None
def entry_actions(self):
self.ant.speed = 120. + randint(-30, 30)
self.random_destination()
class AntStateSeeking(State):
def __init__(self, ant):
State.__init__(self, "seeking")
self.ant = ant
self.leaf_id = None
def check_conditions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is None:
return "exploring"
if self.ant.location.get_distance_to(leaf.location) < 5.0:
self.ant.carry(leaf.image)
self.ant.world.remove_entity(leaf)
return "delivering"
return None
def entry_actions(self):
leaf = self.ant.world.get(self.ant.leaf_id)
if leaf is not None:
self.ant.destination = leaf.location
self.ant.speed = 160. + randint(-20, 20)
class AntStateDelivering(State):
def __init__(self, ant):
State.__init__(self, "delivering")
self.ant = ant
def check_conditions(self):
if Vector2(*NEST_POSITION).get_distance_to(self.ant.location) < NEST_SIZE:
if (randint(1, 10) == 1):
self.ant.drop(self.ant.world.background)
return "exploring"
return None
def entry_actions(self):
self.ant.speed = 60.
random_offset = Vector2(randint(-20, 20), randint(-20, 20))
self.ant.destination = Vector2(*NEST_POSITION) + random_offset
class AntStateHunting(State):
def __init__(self, ant):
State.__init__(self, "hunting")
self.ant = ant
self.got_kill = False
def do_actions(self):
spider = self.ant.world.get(self.ant.spider_id)
if spider is None:
return
self.ant.destination = spider.location
if self.ant.location.get_distance_to(spider.location) < 15.:
if randint(1, 5) == 1:
spider.bitten()
if spider.health <= 0:
self.ant.carry(spider.image)
self.ant.world.remove_entity(spider)
self.got_kill = True
def check_conditions(self):
if self.got_kill:
return "delivering"
spider = self.ant.world.get(self.ant.spider_id)
if spider is None:
return "exploring"
if spider.location.get_distance_to(NEST_POSITION) > NEST_SIZE * 3:
return "exploring"
return None
def entry_actions(self):
self.speed = 160. + randint(0, 50)
def exit_actions(self):
self.got_kill = False
def run():
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
world = World()
w, h = SCREEN_SIZE
clock = pygame.time.Clock()
ant_image = pygame.image.load(os.path.join(os.path.split(os.path.abspath(__file__))[0], "jpg/ant.png")).convert_alpha()
leaf_image = pygame.image.load(os.path.join(os.path.split(os.path.abspath(__file__))[0], "jpg/leaf.png")).convert_alpha()
spider_image = pygame.image.load(os.path.join(os.path.split(os.path.abspath(__file__))[0], "jpg/spider.png")).convert_alpha()
for ant_no in xrange(ANT_COUNT):
ant = Ant(world, ant_image)
ant.location = Vector2(randint(0, w), randint(0, h))
ant.brain.set_state("exploring")
world.add_entity(ant)
while True:
for event in pygame.event.get():
if event.type == QUIT:
return
time_passed = clock.tick(30)
#
if randint(1, 10) == 1:
leaf = Leaf(world, leaf_image)
leaf.location = Vector2(randint(0, w), randint(0, h))
world.add_entity(leaf)
#
if randint(1, 100) == 1:
spider = Spider(world, spider_image)
spider.location = Vector2(-50, randint(0, h))
spider.destination = Vector2(w+50, randint(0, h))
world.add_entity(spider)
#process
world.process(time_passed)
#render
world.render(screen)
pygame.display.update()
if __name__ == "__main__":
run()
| zzy-code-test | python/ant_spider/ant_spider.py | Python | gpl2 | 8,978 |
#!/usr/bin/env python
import pygame, os#, sys
from pygame.locals import *
from gameobjects.vector2 import Vector2
from random import randint #, choice
SCREEN_SIZE=(800, 600)
MAIN_DIR=os.path.split(os.path.abspath(__file__))[0]
image_background = "image/back.png"
image_sunflower = "image/sunflower.png"
image_beanshooter = "image/bean_shooter.png"
image_bean_bullet = "image/bean_bullet.png"
image_zombie_dancer = "image/zombie_buckethead.png"
MAP_ARRAY_COL=20
MAP_ARRAY_ROW=20
ARRAY_COL_SIZE=100
ARRAY_ROW_SIZE=100
def load_image(file, width=None, number=None):
''' load image list from image list file '''
surface = pygame.image.load(file).convert_alpha()
if width == None:
return surface
height = surface.get_height()
return [
surface.subsurface(
Rect((i * width, 0), (width, height))
) for i in xrange(number)
]
class World(object):
''' world '''
def __init__(self):
self.entities = {}
self.entity_id = 0
self.map_status = [
[0 for x in range(MAP_ARRAY_COL)]
for y in range(MAP_ARRAY_ROW)
]
self.background = pygame.image.load(os.path.join(MAIN_DIR, image_background)).convert()
self.select_entity = None
def add_entity(self, entity):
self.entities[self.entity_id] = entity
entity.id = self.entity_id
self.entity_id += 1
def remove_entity(self, entity):
del self.entities[entity.id]
def get(self, entity_id):
if entity_id in self.entities:
return self.entities[entity_id]
else:
return None
def process(self, time_passed):
''' '''
time_passed_seconds = time_passed
for entity in self.entities.values():
entity.process(time_passed_seconds)
def render(self, surface):
''''''
# render background
surface.blit(self.background, (0, 0) )
# render entities
for entity in self.entities.itervalues():
entity.render(surface)
if self.select_entity != None:
self.select_entity.render(surface)
def get_near_entity(self, location, range=100.):
''' get near entity which distan less than range'''
location = Vector2(*location)
for entity in self.entities.itervalues():
# if entity.name == name:
distance = location.get_distance_to(entity.location)
if distance < range:
return entity
return None
def get_map_status_ab(self, position_xy):
x, y= position_xy
if x % ARRAY_COL_SIZE > ARRAY_COL_SIZE/2:
a = x/ ARRAY_COL_SIZE + 1
else :
a = x/ARRAY_COL_SIZE
if y % ARRAY_ROW_SIZE > ARRAY_ROW_SIZE/2:
b = y/ARRAY_ROW_SIZE + 1
else :
b = y/ARRAY_ROW_SIZE
return (a, b)
def get_map_status_xy(self, position_ab):
a, b = position_ab
return (a*ARRAY_COL_SIZE, b*ARRAY_ROW_SIZE)
class GameZone():
def __init__(self, world):
pass
class ToolBoxZone():
''' '''
_locate = (0,10)
_tool_num = 10
def __init__(self, world):
self.world = world
self.tool_count = 0
self.tools = {}
self.location = self._locate
self.image = pygame.load_image().convert()
pass
def render(self, surface):
''''''
surface.blit(self.image, self.location)
for tool in self.tools.itervalues():
tool.render(surface)
def add_tool_item(self, tool_item):
''''''
self.tools[tool_item.name] = tool_item
self.tool_count+=1
def del_tool_item(self, tool_item):
''''''
del self.tools[tool_item.name]
class ToolItem():
''''''
_image_rect = (64, 64)
def __init__(self, tool_box_zone, name, image_file, id):
self.tool_box_zone = tool_box_zone
self.name = name
self.image = pygame.image.load(image_file).convert()
self.id = id
def render(self, surface):
surface.blit(self.image, self.location)
class Entity(pygame.sprite.Sprite):
''' game entity '''
images = []
def __init__(self, world, name):
self.world = world
self.name = name
self.id = world.entity_id
self.image = None
self.location = Vector2(0, 0)
self.destination = Vector2(0, 0)
self.speed = 0.
# self.brain = StateMachine()
def think(self):
pass
def walk(self, time_passed):
if self.speed > 0. and self.location != self.destination:
vec_to_destination = self.destination - self.location
distance_to_destination = vec_to_destination.get_length()
heading = vec_to_destination.get_normalized()
travel_distance = min(distance_to_destination, int(time_passed/ 1000.0 * self.speed))
self.location += travel_distance * heading
def update(self, time_passed):
''''''
pass
def process(self, time_passed):
''' process '''
self.think()
self.update(time_passed)
if self.speed > 0. :
self.walk(time_passed)
def locate(self):
''' locate entity in a world postion '''
''' check '''
entity = self.world.get_near_entity(self.location)
if entity != None:
return False
''' '''
self.location = Vector2(self.world.get_map_status_xy(self.world.get_map_status_ab(self.location)))
return True
def render(self, surface):
x, y = self.location
w, h = self.image.get_size()
surface.blit(self.image, (x-w/2, y-h/2))
class Bullet(Entity):
'''Bullet'''
_rate = 80
_width = 82
_height = 77
_image_num = 1
_life = 100
_speed = 62
images = []
''' game entity '''
def __init__(self, world, name, image_file_name):
Entity.__init__(self, world, name)
self.order = 0
pygame.sprite.Sprite.__init__(self)
self.image = pygame.image.load(os.path.join(MAIN_DIR, image_file_name)).convert_alpha()
self.rect = Rect(0, 0, self._width, self._height)
self.life = self._life
self.passed_time = 0
self.speed = self._speed
class BeanBullet(Bullet):
def __init__(self, world):
Bullet.__init__(self, world, "BeanBullet", image_bean_bullet)
class Zombie(Entity):
'''Zombie'''
_rate = 80
_width = 67
_height = 116
_image_num = 1
_life = 100
_speed = 57
images = []
def __init__(self, world, name, image_file_name):
Entity.__init__(self, world, name)
self.order = 0
pygame.sprite.Sprite.__init__(self)
if len(self.images) == 0:
self.images = load_image(os.path.join(MAIN_DIR, image_file_name), self._width, self._image_num)
self.image = self.images[self.order]
self.image = pygame.image.load(os.path.join(MAIN_DIR, image_file_name)).convert_alpha()
self.rect = Rect(0, 0, self._width, self._height)
self.life = self._life
self.passed_time = 0
self.speed = self._speed
def process(self, time_passed):
# self.brain.think()
self.passed_time += time_passed
self.order = int(( self.passed_time / self._rate ) % self._image_num )
if self.order == 0 and self.passed_time > self._rate:
self.passed_time = 0
self.image = self.images[self.order]
Entity.process(self, time_passed)
class DancerZombie(Zombie):
def __init__(self, world):
Zombie.__init__(self, world, "DancerZombie", image_zombie_dancer)
class Plant(Entity):
''' SunFlower '''
_rate = 10
_width = 70
_height = 70
_image_num = 1
_life = 100
images = []
def __init__(self, world, name, image_file):
pygame.sprite.Sprite.__init__(self)
Entity.__init__(self, world, name)
self.order = 0
if len(self.images) == 0:
self.images = load_image(os.path.join(MAIN_DIR, image_file), self._width, self._image_num)
self.image = self.images[self.order]
self.rect = Rect(0, 0, self._width, self._height)
self.life = self._life
self.passed_time = 0
def process(self, passed_time):
self.passed_time += passed_time
self.order = int(( self.passed_time / self._rate ) % self._image_num)
if self.order == 0 and self.passed_time > self._rate:
self.passed_time = 0
self.image = self.images[self.order]
Entity.process(self, passed_time)
class BeanShooter(Plant):
''' BeanShooter '''
_rate = 80
_width = 70
_height = 70
_image_num = 1
_life = 100
images = []
def __init__(self, world):
self.update_shoot = False
self.shoot_time = 0.
Plant.__init__(self, world, "BeanShooter" , image_beanshooter)
def process(self, passed_time):
if self.update_shoot == True:
self.shoot(passed_time)
Plant.process(self, passed_time)
def shoot(self, passed_time):
self.shoot_time += passed_time
if self.shoot_time > 3000 :
self.shoot_time = 0
bean_bullet = BeanBullet(self.world)
bean_bullet.location = Vector2(self.location[0]+30, self.location[1]-20)
bean_bullet.destination = Vector2(SCREEN_SIZE[0], self.location[1])
self.world.add_entity(bean_bullet)
class SunFlower(Plant):
''' SunFlower '''
_rate = 80
_width = 82
_height = 77
_image_num = 18
_life = 100
images = []
def __init__(self, world):
Plant.__init__(self, world, "SunFlower", image_sunflower)
def run():
''' run '''
pygame.init()
screen = pygame.display.set_mode(SCREEN_SIZE, 0, 32)
world = World()
clock = pygame.time.Clock()
w, h = SCREEN_SIZE
while True:
for event in pygame.event.get():
if event.type == QUIT:
exit()
elif event.type == MOUSEBUTTONDOWN:
world.select_entity = BeanShooter(world)
world.select_entity.location = Vector2(event.pos)
elif event.type == MOUSEMOTION:
if world.select_entity != None:
world.select_entity.location = Vector2(event.pos)
elif event.type == MOUSEBUTTONUP:
if world.select_entity != None:
if world.select_entity.name == "BeanShooter":
world.select_entity.locate()
world.select_entity.update_shoot = True
world.add_entity(world.select_entity)
world.select_entity = None
time_passed = clock.tick(30)
if randint(1, 100) == 1:
dancerZombie = DancerZombie(world)
locate_h = randint(0, h)
dancerZombie.location = Vector2(w, locate_h)
dancerZombie.locate()
dancerZombie.destination = Vector2(0, dancerZombie.location[1])
world.add_entity(dancerZombie)
#process
world.process(time_passed)
#render
world.render(screen)
pygame.display.update()
if __name__ == "__main__":
run()
| zzy-code-test | python/plantvszombie/plantvszombie.py | Python | gpl2 | 9,783 |
"""
Simulation of a rotating 3D Cube
Developed by Leonel Machava <leonelmachava@gmail.com>
http://codeNtronix.com
"""
import sys, math, pygame
from pygame.locals import *
from operator import itemgetter
COL_RED=(255,0,0)
COL_GREEN=(0,255,0)
COL_BLUE=(0,0,255)
COL_YELLOW=(255,255,0)
COL_PINK=(255,0,255)
COL_UNKNOW=(0,255,255)
COL_BLACK=(0,0,0)
class Point3D:
def __init__(self, x = 0, y = 0, z = 0):
self.x, self.y, self.z = float(x), float(y), float(z)
def rotateX(self, angle):
""" Rotates the point around the X axis by the given angle in degrees. """
rad = angle * math.pi / 180
cosa = math.cos(rad)
sina = math.sin(rad)
y = self.y * cosa - self.z * sina
z = self.y * sina + self.z * cosa
return Point3D(self.x, y, z)
def rotateY(self, angle):
""" Rotates the point around the Y axis by the given angle in degrees. """
rad = angle * math.pi / 180
cosa = math.cos(rad)
sina = math.sin(rad)
z = self.z * cosa - self.x * sina
x = self.z * sina + self.x * cosa
return Point3D(x, self.y, z)
def rotateZ(self, angle):
""" Rotates the point around the Z axis by the given angle in degrees. """
rad = angle * math.pi / 180
cosa = math.cos(rad)
sina = math.sin(rad)
x = self.x * cosa - self.y * sina
y = self.x * sina + self.y * cosa
return Point3D(x, y, self.z)
def project(self, win_width, win_height, fov, viewer_distance):
""" Transforms this 3D point to 2D using a perspective projection. """
factor = fov / (viewer_distance + self.z)
x = self.x * factor + win_width / 2
y = -self.y * factor + win_height / 2
return Point3D(x, y, self.z)
class Face:
def __init__(self, points, color):
self.points = points
self.color = color
def avg_z(self):
return ( self.points[0].z +
self.points[1].z +
self.points[2].z +
self.points[3].z
) / 4.0
def display(self, game):
pointlist = [(self.points[0].x, self.points[0].y),
(self.points[1].x, self.points[1].y),
(self.points[2].x, self.points[2].y),
(self.points[3].x, self.points[3].y),
(self.points[0].x, self.points[0].y)]
pygame.draw.polygon(game.screen, self.color,pointlist)
pygame.draw.lines(game.screen, COL_BLACK, True, pointlist, 1)
def angle_reg(angle):
if(angle < 0):
return angle+360
elif (angle >=360):
return angle-360
else:
return angle
class Cube:
"""
cube unit block
"""
vert_index = [
(-1, 1, -1), (1,1,-1),(1,-1,-1),(-1,-1,-1),
(-1, 1, 1), (1,1,1),(1,-1,1),(-1,-1,1)
]
# indices to the vertices list defined above.
face_vert = [
(1,5,6,2),(4,0,3,7),(0,4,5,1),
(3,2,6,7),(0,1,2,3),(5,4,7,6)
]
# Define colors for each face
face_colors = [
COL_RED, COL_GREEN, COL_BLUE,
COL_YELLOW, COL_PINK, COL_UNKNOW
]
def __init__(self,point,size=0.5):
self.point = point
self.angle = [0,0,0]
self.vertices = []
for vert in Cube.vert_index:
self.vertices.append(Point3D(point.x+vert[0]*size,
point.y+vert[1]*size,
point.z+vert[2]*size ))
self.face_color = zip(Cube.face_vert, Cube.face_colors)
def rotate(self, angle):
self.angle = [ x+y for x,y in zip(self.angle, angle)]
def getCurPoint(self):
return self.point.rotateX(self.angle[0]).rotateY(self.angle[1]).rotateZ(self.angle[2])
def update(self, mc):
t = []
draw_list = mc.game.draw_list
for v in self.vertices:
r = v.rotateX(self.angle[0]).rotateY(self.angle[1]).rotateZ(self.angle[2])
# Transform the point from 3D to 2D
p = r.project(640, 480, 400, 8)
# Put the point in the list of transformed vertices
t.append(p)
for fc in self.face_color:
f = fc[0]
c = fc[1]
f_points = [ t[f[0]], t[f[1]], t[f[2]], t[f[3]] ]
face = Face(f_points, c)
draw_list.append(face)
class MagicCube:
""""""
def_pos = (0,0,0)
def __init__(self, game, pos=def_pos):
self.pos = pos
self.game = game
self.cube_list = []
for x in range(-1, 2):
for y in range(-1, 2):
for z in range(-1,2):
cube = Cube(Point3D(self.pos[0]+x,
self.pos[1]+y,
self.pos[2]+z))
self.cube_list.append(cube)
# for pos in MagicCube.cube_pos:
# cube = Cube(Point3D(pos[0],pos[1],pos[2]))
def RotateCubes(self, which, direct):
cube_list = []
for cube in self.cube_list:
point = cube.getCurPoint()
if(which == "L1" and int(point.y) == -1):
cube_list.append(cube)
elif(which == "L2" and int(point.y) == 0):
cube_list.append(cube)
elif(which == "L3" and int(point.y) == 1):
cube_list.append(cube)
elif(which == "R1" and int(point.x) == -1):
cube_list.append(cube)
elif(which == "R2" and int(point.x) == 0):
cube_list.append(cube)
elif(which == "R3" and int(point.x) == 1):
cube_list.append(cube)
elif(which == "F1" and int(point.z) == -1):
cube_list.append(cube)
elif(which == "F2" and int(point.z) == 0):
cube_list.append(cube)
elif(which == "F3" and int(point.z) == 1):
cube_list.append(cube)
angle = 0
while angle < 90:
for cube in cube_list:
if direct == "LEFT":
cube.rotate((0,2,0))
elif direct == "RIGHT":
cube.rotate((0,-2,0))
elif direct == "UP":
cube.rotate((2,0,0))
elif direct == "DOWN":
cube.rotate((-2,0,0))
elif direct == "FRONT":
cube.rotate((0,0,-2))
elif direct == "BACK":
cube.rotate((0,0,2))
angle += 2
def update(self):
"""
"""
#self.draw_list = []
for cube in self.cube_list:
cube.update(self)
class Game:
"' '"
def __init__(self, win_width = 640, win_height = 480):
pygame.init()
pygame.display.set_caption("Magic Cube")
self.screen = pygame.display.set_mode((win_width, win_height))
self.draw_list = []
self.clock = pygame.time.Clock()
self.items = []
self.items.append(MagicCube(self))
# self.items.append(MagicCube(self, (-1,0,0)))
def update(self):
"""
"""
self.draw_list = []
self.screen.fill((0,0,0))
for item in self.items:
item.update()
avg_z = []
i = 0
for f in self.draw_list:
avg_z.append([i,f.avg_z()])
i = i + 1
for tmp in sorted(avg_z,key=itemgetter(1),reverse=True):
self.draw_list[tmp[0]].display(self)
self.clock.tick(10)
pygame.display.flip()
def run(self):
"""
"""
while 1:
self.update()
for event in pygame.event.get():
if event.type == pygame.QUIT:
pygame.quit()
sys.exit()
pressed_keys = pygame.key.get_pressed()
if pressed_keys[K_LEFT]:
self.items[0].RotateCubes("L1", "LEFT")
elif pressed_keys[K_RIGHT]:
self.items[0].RotateCubes("L1", "RIGHT")
elif pressed_keys[K_UP]:
self.items[0].RotateCubes("R1", "UP")
elif pressed_keys[K_DOWN]:
self.items[0].RotateCubes("R2", "DOWN")
elif pressed_keys[K_a]:
self.items[0].RotateCubes("F1", "FRONT")
elif pressed_keys[K_d]:
self.items[0].RotateCubes("F2", "BACK")
if __name__ == "__main__":
Game().run()
| zzy-code-test | python/rotating_cube/rotating_cube.py | Python | gpl2 | 6,835 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
function lineTo2(ctx, x0, y0, x1, y1, len) {
var x2, y2, a, b, p, xt,
a2, b2, c2;
if (x0 == x1) {
x2 = x0;
y2 = y1 > y0 ? y0 + len : y0 - len;
} else if (y0 == y1) {
y2 = y0;
x2 = x1 > x0 ? x0 + len : x0 - len;
} else {
// 解一元二次方程
a = (y0 - y1) / (x0 - x1);
b = y0 - x0 * a;
a2 = a * a + 1;
b2 = 2 * (a * (b - y0) - x0);
c2 = Math.pow(b - y0, 2) + x0 * x0 - Math.pow(len, 2);
p = Math.pow(b2, 2) - 4 * a2 * c2;
if (p < 0) {
// TD.log("ERROR: [a, b, len] = [" + ([a, b, len]).join(", ") + "]");
return [0, 0];
}
p = Math.sqrt(p);
xt = (-b2 + p) / (2 * a2);
if ((x1 - x0 > 0 && xt - x0 > 0) ||
(x1 - x0 < 0 && xt - x0 < 0)) {
x2 = xt;
y2 = a * x2 + b;
} else {
x2 = (-b2 - p) / (2 * a2);
y2 = a * x2 + b;
}
}
ctx.lineCap = "round";
ctx.moveTo(x0, y0);
ctx.lineTo(x2, y2);
return [x2, y2];
}
var renderFunctions = {
"cannon": function (b, ctx, map, gs, gs2) {
var target_position = b.getTargetPosition();
ctx.fillStyle = "#393";
ctx.strokeStyle = "#000";
ctx.beginPath();
ctx.lineWidth = 1;
ctx.arc(b.cx, b.cy, gs2 - 5, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(b.cx, b.cy);
b.muzzle = lineTo2(ctx, b.cx, b.cy, target_position[0], target_position[1], gs2);
ctx.closePath();
// ctx.fill();
ctx.stroke();
ctx.lineWidth = 1;
ctx.fillStyle = "#060";
ctx.beginPath();
ctx.arc(b.cx, b.cy, 7, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#cec";
ctx.beginPath();
ctx.arc(b.cx + 2, b.cy - 2, 3, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
},
"LMG": function (b, ctx, map, gs, gs2) {
var target_position = b.getTargetPosition();
ctx.fillStyle = "#36f";
ctx.strokeStyle = "#000";
ctx.beginPath();
ctx.lineWidth = 1;
ctx.arc(b.cx, b.cy, 7, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.lineWidth = 2;
ctx.beginPath();
ctx.moveTo(b.cx, b.cy);
b.muzzle = lineTo2(ctx, b.cx, b.cy, target_position[0], target_position[1], gs2);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.lineWidth = 1;
ctx.fillStyle = "#66c";
ctx.beginPath();
ctx.arc(b.cx, b.cy, 5, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#ccf";
ctx.beginPath();
ctx.arc(b.cx + 1, b.cy - 1, 2, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
},
"HMG": function (b, ctx, map, gs, gs2) {
var target_position = b.getTargetPosition();
ctx.fillStyle = "#933";
ctx.strokeStyle = "#000";
ctx.beginPath();
ctx.lineWidth = 1;
ctx.arc(b.cx, b.cy, gs2 - 2, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.lineWidth = 5;
ctx.beginPath();
ctx.moveTo(b.cx, b.cy);
b.muzzle = lineTo2(ctx, b.cx, b.cy, target_position[0], target_position[1], gs2);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.lineWidth = 1;
ctx.fillStyle = "#630";
ctx.beginPath();
ctx.arc(b.cx, b.cy, gs2 - 5, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#960";
ctx.beginPath();
ctx.arc(b.cx + 1, b.cy - 1, 8, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "#fcc";
ctx.beginPath();
ctx.arc(b.cx + 3, b.cy - 3, 4, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
},
"wall": function (b, ctx, map, gs, gs2) {
ctx.lineWidth = 1;
ctx.fillStyle = "#666";
ctx.strokeStyle = "#000";
ctx.fillRect(b.cx - gs2 + 1, b.cy - gs2 + 1, gs - 1, gs - 1);
ctx.beginPath();
ctx.moveTo(b.cx - gs2 + 0.5, b.cy - gs2 + 0.5);
ctx.lineTo(b.cx - gs2 + 0.5, b.cy + gs2 + 0.5);
ctx.lineTo(b.cx + gs2 + 0.5, b.cy + gs2 + 0.5);
ctx.lineTo(b.cx + gs2 + 0.5, b.cy - gs2 + 0.5);
ctx.lineTo(b.cx - gs2 + 0.5, b.cy - gs2 + 0.5);
ctx.moveTo(b.cx - gs2 + 0.5, b.cy + gs2 + 0.5);
ctx.lineTo(b.cx + gs2 + 0.5, b.cy - gs2 + 0.5);
ctx.moveTo(b.cx - gs2 + 0.5, b.cy - gs2 + 0.5);
ctx.lineTo(b.cx + gs2 + 0.5, b.cy + gs2 + 0.5);
ctx.closePath();
ctx.stroke();
},
"laser_gun": function (b, ctx/*, map, gs, gs2*/) {
// var target_position = b.getTargetPosition();
ctx.fillStyle = "#f00";
ctx.strokeStyle = "#000";
ctx.beginPath();
ctx.lineWidth = 1;
// ctx.arc(b.cx, b.cy, gs2 - 5, 0, Math.PI * 2, true);
ctx.moveTo(b.cx, b.cy - 10);
ctx.lineTo(b.cx - 8.66, b.cy + 5);
ctx.lineTo(b.cx + 8.66, b.cy + 5);
ctx.lineTo(b.cx, b.cy - 10);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#60f";
ctx.beginPath();
ctx.arc(b.cx, b.cy, 7, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.fillStyle = "#000";
ctx.beginPath();
ctx.arc(b.cx, b.cy, 3, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.fillStyle = "#666";
ctx.beginPath();
ctx.arc(b.cx + 1, b.cy - 1, 1, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.lineWidth = 3;
ctx.beginPath();
ctx.moveTo(b.cx, b.cy);
// b.muzzle = lineTo2(ctx, b.cx, b.cy, target_position[0], target_position[1], gs2);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
};
TD.renderBuilding = function (building) {
var ctx = TD.ctx,
map = building.map,
gs = TD.grid_size,
gs2 = TD.grid_size / 2;
(renderFunctions[building.type] || renderFunctions["wall"])(
building, ctx, map, gs, gs2
);
}
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-render-buildings.js | JavaScript | gpl2 | 6,025 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
/**
* 本文件定义了建筑的参数、属性
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
/**
* 默认的升级规则
* @param old_level {Number}
* @param old_value {Number}
* @return new_value {Number}
*/
TD.default_upgrade_rule = function (old_level, old_value) {
return old_value * 1.2;
};
/**
* 取得建筑的默认属性
* @param building_type {String} 建筑类型
*/
TD.getDefaultBuildingAttributes = function (building_type) {
var building_attributes = {
// 路障
"wall": {
damage: 0,
range: 0,
speed: 0,
bullet_speed: 0,
life: 100,
shield: 500,
cost: 5
},
// 炮台
"cannon": {
damage: 12,
range: 4,
max_range: 8,
speed: 2,
bullet_speed: 6,
life: 100,
shield: 100,
cost: 300,
_upgrade_rule_damage: function (old_level, old_value) {
return old_value * (old_level <= 10 ? 1.2 : 1.3);
}
},
// 轻机枪
"LMG": {
damage: 5,
range: 5,
max_range: 10,
speed: 3,
bullet_speed: 6,
life: 100,
shield: 50,
cost: 100
},
// 重机枪
"HMG": {
damage: 30,
range: 3,
max_range: 5,
speed: 3,
bullet_speed: 5,
life: 100,
shield: 200,
cost: 800,
_upgrade_rule_damage: function (old_level, old_value) {
return old_value * 1.3;
}
},
// 激光枪
"laser_gun": {
damage: 25,
range: 6,
max_range: 10,
speed: 20,
// bullet_speed: 10, // laser_gun 的 bullet_speed 属性没有用
life: 100,
shield: 100,
cost: 2000
}
};
return building_attributes[building_type] || {};
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-cfg-buildings.js | JavaScript | gpl2 | 1,892 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
/**
* 使用 A* 算法(Dijkstra算法?)寻找从 (x1, y1) 到 (x2, y2) 最短的路线
*
*/
TD.FindWay = function (w, h, x1, y1, x2, y2, f_passable) {
this.m = [];
this.w = w;
this.h = h;
this.x1 = x1;
this.y1 = y1;
this.x2 = x2;
this.y2 = y2;
this.way = [];
this.len = this.w * this.h;
this.is_blocked = this.is_arrived = false;
this.fPassable = typeof f_passable == "function" ? f_passable : function () {
return true;
};
this._init();
};
TD.FindWay.prototype = {
_init: function () {
if (this.x1 == this.x2 && this.y1 == this.y2) {
// 如果输入的坐标已经是终点了
this.is_arrived = true;
this.way = [
[this.x1, this.y1]
];
return;
}
for (var i = 0; i < this.len; i ++)
this.m[i] = -2; // -2 表示未探索过,-1 表示不可到达
this.x = this.x1;
this.y = this.y1;
this.distance = 0;
this.current = [
[this.x, this.y]
]; // 当前一步探索的格子
this.setVal(this.x, this.y, 0);
while (this.next()) {}
},
getVal: function (x, y) {
var p = y * this.w + x;
return p < this.len ? this.m[p] : -1;
},
setVal: function (x, y, v) {
var p = y * this.w + x;
if (p > this.len) return false;
this.m[p] = v;
},
/**
* 得到指定坐标的邻居,即从指定坐标出发,1 步之内可以到达的格子
* 目前返回的是指定格子的上、下、左、右四个邻格
* @param x {Number}
* @param y {Number}
*/
getNeighborsOf: function (x, y) {
var nbs = [];
if (y > 0) nbs.push([x, y - 1]);
if (x < this.w - 1) nbs.push([x + 1, y]);
if (y < this.h - 1) nbs.push([x, y + 1]);
if (x > 0) nbs.push([x - 1, y]);
return nbs;
},
/**
* 取得当前一步可到达的 n 个格子的所有邻格
*/
getAllNeighbors: function () {
var nbs = [], nb1, i, c, l = this.current.length;
for (i = 0; i < l; i ++) {
c = this.current[i];
nb1 = this.getNeighborsOf(c[0], c[1]);
nbs = nbs.concat(nb1);
}
return nbs;
},
/**
* 从终点倒推,寻找从起点到终点最近的路径
* 此处的实现是,从终点开始,从当前格子的邻格中寻找值最低(且大于 0)的格子,
* 直到到达起点。
* 这个实现需要反复地寻找邻格,有时邻格中有多个格子的值都为最低,这时就从中
* 随机选取一个。还有一种实现方式是在一开始的遍历中,给每一个到达过的格子添加
* 一个值,指向它的来时的格子(父格子)。
*/
findWay: function () {
var x = this.x2,
y = this.y2,
nb, max_len = this.len,
nbs_len,
nbs, i, l, v, min_v = -1,
closest_nbs;
while ((x != this.x1 || y != this.y1) && min_v != 0 &&
this.way.length < max_len) {
this.way.unshift([x, y]);
nbs = this.getNeighborsOf(x, y);
nbs_len = nbs.length;
closest_nbs = [];
// 在邻格中寻找最小的 v
min_v = -1;
for (i = 0; i < nbs_len; i ++) {
v = this.getVal(nbs[i][0], nbs[i][1]);
if (v < 0) continue;
if (min_v < 0 || min_v > v)
min_v = v;
}
// 找出所有 v 最小的邻格
for (i = 0; i < nbs_len; i ++) {
nb = nbs[i];
if (min_v == this.getVal(nb[0], nb[1])) {
closest_nbs.push(nb);
}
}
// 从 v 最小的邻格中随机选取一个作为当前格子
l = closest_nbs.length;
i = l > 1 ? Math.floor(Math.random() * l) : 0;
nb = closest_nbs[i];
x = nb[0];
y = nb[1];
}
},
/**
* 到达终点
*/
arrive: function () {
this.current = [];
this.is_arrived = true;
this.findWay();
},
/**
* 道路被阻塞
*/
blocked: function () {
this.current = [];
this.is_blocked = true;
},
/**
* 下一次迭代
* @return {Boolean} 如果返回值为 true ,表示未到达终点,并且道路
* 未被阻塞,可以继续迭代;否则表示不必继续迭代
*/
next: function () {
var neighbors = this.getAllNeighbors(), nb,
l = neighbors.length,
valid_neighbors = [],
x, y,
i, v;
this.distance ++;
for (i = 0; i < l; i ++) {
nb = neighbors[i];
x = nb[0];
y = nb[1];
if (this.getVal(x, y) != -2) continue; // 当前格子已探索过
//grid = this.map.getGrid(x, y);
//if (!grid) continue;
if (this.fPassable(x, y)) {
// 可通过
/**
* 从起点到当前格子的耗费
* 这儿只是简单地把从起点到当前格子需要走几步作为耗费
* 比较复杂的情况下,可能还需要考虑不同的路面耗费也会不同,
* 比如沼泽地的耗费比平地要多。不过现在的版本中路况没有这么复杂,
* 先不考虑。
*/
v = this.distance;
valid_neighbors.push(nb);
} else {
// 不可通过或有建筑挡着
v = -1;
}
this.setVal(x, y, v);
if (x == this.x2 && y == this.y2) {
this.arrive();
return false;
}
}
if (valid_neighbors.length == 0) {
this.blocked();
return false
}
this.current = valid_neighbors;
return true;
}
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-walk.js | JavaScript | gpl2 | 5,578 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
/** 默认关卡
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
// main stage 初始化方法
var _stage_main_init = function () {
var act = new TD.Act(this, "act-1"),
scene = new TD.Scene(act, "scene-1"),
cfg = TD.getDefaultStageData("scene_endless");
this.config = cfg.config;
TD.life = this.config.life;
TD.money = this.config.money;
TD.score = this.config.score;
TD.difficulty = this.config.difficulty;
TD.wave_damage = this.config.wave_damage;
// make map
var map = new TD.Map("main-map", TD.lang.mix({
scene: scene,
is_main_map: true,
step_level: 1,
render_level: 2
}, cfg.map));
map.addToScene(scene, 1, 2, map.grids);
scene.map = map;
// make panel
scene.panel = new TD.Panel("panel", TD.lang.mix({
scene: scene,
main_map: map,
step_level: 1,
render_level: 7
}, cfg.panel));
this.newWave = cfg.newWave;
this.map = map;
this.wait_new_wave = this.config.wait_new_wave;
},
_stage_main_step2 = function () {
//TD.log(this.current_act.current_scene.wave);
var scene = this.current_act.current_scene,
wave = scene.wave;
if ((wave == 0 && !this.map.has_weapon) || scene.state != 1) {
return;
}
if (this.map.monsters.length == 0) {
if (wave > 0 && this.wait_new_wave == this.config.wait_new_wave - 1) {
// 一波怪物刚刚走完
// 奖励生命值
var wave_reward = 0;
if (wave % 10 == 0) {
wave_reward = 10;
} else if (wave % 5 == 0) {
wave_reward = 5;
}
if (TD.life + wave_reward > 100) {
wave_reward = 100 - TD.life;
}
if (wave_reward > 0) {
TD.recover(wave_reward);
}
}
if (this.wait_new_wave > 0) {
this.wait_new_wave --;
return;
}
this.wait_new_wave = this.config.wait_new_wave;
wave ++;
scene.wave = wave;
this.newWave({
map: this.map,
wave: wave
});
}
};
TD.getDefaultStageData = function (k) {
var data = {
stage_main: {
width: 640, // px
height: 560,
init: _stage_main_init,
step2: _stage_main_step2
},
scene_endless: {
// scene 1
map: {
grid_x: 16,
grid_y: 16,
x: TD.padding,
y: TD.padding,
entrance: [0, 0],
exit: [15, 15],
grids_cfg: [
{
pos: [3, 3],
//building: "cannon",
passable_flag: 0
},
{
pos: [7, 15],
build_flag: 0
},
{
pos: [4, 12],
building: "wall"
},
{
pos: [4, 13],
building: "wall"
//}, {
//pos: [11, 9],
//building: "cannon"
//}, {
//pos: [5, 2],
//building: "HMG"
//}, {
//pos: [14, 9],
//building: "LMG"
//}, {
//pos: [3, 14],
//building: "LMG"
}
]
},
panel: {
x: TD.padding * 2 + TD.grid_size * 16,
y: TD.padding,
map: {
grid_x: 3,
grid_y: 3,
x: 0,
y: 110,
grids_cfg: [
{
pos: [0, 0],
building: "cannon"
},
{
pos: [1, 0],
building: "LMG"
},
{
pos: [2, 0],
building: "HMG"
},
{
pos: [0, 1],
building: "laser_gun"
},
{
pos: [2, 2],
building: "wall"
}
]
}
},
config: {
endless: true,
wait_new_wave: TD.exp_fps * 3, // 经过多少 step 后再开始新的一波
difficulty: 1.0, // 难度系数
wave: 0,
max_wave: -1,
wave_damage: 0, // 当前一波怪物造成了多少点生命值的伤害
max_monsters_per_wave: 100, // 每一波最多多少怪物
money: 500,
score: 0, // 开局时的积分
life: 100,
waves: [ // 这儿只定义了前 10 波怪物,从第 11 波开始自动生成
[],
// 第一个参数是没有用的(第 0 波)
// 第一波
[
[1, 0] // 1 个 0 类怪物
],
// 第二波
[
[1, 0], // 1 个 0 类怪物
[1, 1] // 1 个 1 类怪物
],
// wave 3
[
[2, 0], // 2 个 0 类怪物
[1, 1] // 1 个 1 类怪物
],
// wave 4
[
[2, 0],
[1, 1]
],
// wave 5
[
[3, 0],
[2, 1]
],
// wave 6
[
[4, 0],
[2, 1]
],
// wave 7
[
[5, 0],
[3, 1],
[1, 2]
],
// wave 8
[
[6, 0],
[4, 1],
[1, 2]
],
// wave 9
[
[7, 0],
[3, 1],
[2, 2]
],
// wave 10
[
[8, 0],
[4, 1],
[3, 2]
]
]
},
/**
* 生成第 n 波怪物的方法
*/
newWave: function (cfg) {
cfg = cfg || {};
var map = cfg.map,
wave = cfg.wave || 1,
//difficulty = TD.difficulty || 1.0,
wave_damage = TD.wave_damage || 0;
// 自动调整难度系数
if (wave == 1) {
//pass
} else if (wave_damage == 0) {
// 没有造成伤害
if (wave < 5) {
TD.difficulty *= 1.05;
} else if (TD.difficulty > 30) {
TD.difficulty *= 1.1;
} else {
TD.difficulty *= 1.2;
}
} else if (TD.wave_damage >= 50) {
TD.difficulty *= 0.6;
} else if (TD.wave_damage >= 30) {
TD.difficulty *= 0.7;
} else if (TD.wave_damage >= 20) {
TD.difficulty *= 0.8;
} else if (TD.wave_damage >= 10) {
TD.difficulty *= 0.9;
} else {
// 造成了 10 点以内的伤害
if (wave >= 10)
TD.difficulty *= 1.05;
}
if (TD.difficulty < 1) TD.difficulty = 1;
TD.log("wave " + wave + ", last wave damage = " + wave_damage + ", difficulty = " + TD.difficulty);
//map.addMonsters(100, 7);
//map.addMonsters2([[10, 7], [5, 0], [5, 5]]);
//
var wave_data = this.config.waves[wave] ||
// 自动生成怪物
TD.makeMonsters(Math.min(
Math.floor(Math.pow(wave, 1.1)),
this.config.max_monsters_per_wave
));
map.addMonsters2(wave_data);
TD.wave_damage = 0;
}
} // end of scene_endless
};
return data[k] || {};
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-data-stage-1.js | JavaScript | gpl2 | 6,617 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
var _TD = {
a: [],
init: function (td_board, is_debug) {
delete this.init; // 一旦初始化运行,即删除这个入口引用,防止初始化方法被再次调用
var i, TD = {
version: "0.1.16", // 版本命名规范参考:http://semver.org/
is_debug: !!is_debug,
is_paused: true,
width: 16, // 横向多少个格子
height: 16, // 纵向多少个格子
show_monster_life: true, // 是否显示怪物的生命值
fps: 0,
exp_fps: 24, // 期望的 fps
exp_fps_half: 12,
exp_fps_quarter: 6,
exp_fps_eighth: 4,
stage_data: {},
defaultSettings: function () {
return {
step_time: 36, // 每一次 step 循环之间相隔多少毫秒
grid_size: 32, // px
padding: 10, // px
global_speed: 0.1 // 全局速度系数
};
},
/**
* 初始化
* @param ob_board
*/
init: function (ob_board/*, ob_info*/) {
this.obj_board = TD.lang.$e(ob_board);
this.canvas = this.obj_board.getElementsByTagName("canvas")[0];
//this.obj_info = TD.lang.$e(ob_info);
if (!this.canvas.getContext) return; // 不支持 canvas
this.ctx = this.canvas.getContext("2d");
this.monster_type_count = TD.getDefaultMonsterAttributes(); // 一共有多少种怪物
this.iframe = 0; // 当前播放到第几帧了
this.last_iframe_time = (new Date()).getTime();
this.fps = 0;
this.start();
},
/**
* 开始游戏,或重新开始游戏
*/
start: function () {
clearTimeout(this._st);
TD.log("Start!");
var _this = this;
this._exp_fps_0 = this.exp_fps - 0.4; // 下限
this._exp_fps_1 = this.exp_fps + 0.4; // 上限
this.mode = "normal"; // mode 分为 normail(普通模式)及 build(建造模式)两种
this.eventManager.clear(); // 清除事件管理器中监听的事件
this.lang.mix(this, this.defaultSettings());
this.stage = new TD.Stage("stage-main", TD.getDefaultStageData("stage_main"));
this.canvas.setAttribute("width", this.stage.width);
this.canvas.setAttribute("height", this.stage.height);
this.canvas.onmousemove = function (e) {
var xy = _this.getEventXY.call(_this, e);
_this.hover(xy[0], xy[1]);
};
this.canvas.onclick = function (e) {
var xy = _this.getEventXY.call(_this, e);
_this.click(xy[0], xy[1]);
};
this.is_paused = false;
this.stage.start();
this.step();
return this;
},
/**
* 作弊方法
* @param cheat_code
*
* 用例:
* 1、增加 100 万金钱:javascript:_TD.cheat="money+";void(0);
* 2、难度增倍:javascript:_TD.cheat="difficulty+";void(0);
* 3、难度减半:javascript:_TD.cheat="difficulty-";void(0);
* 4、生命值恢复:javascript:_TD.cheat="life+";void(0);
* 5、生命值降为最低:javascript:_TD.cheat="life-";void(0);
*/
checkCheat: function (cheat_code) {
switch (cheat_code) {
case "money+":
this.money += 1000000;
this.log("cheat success!");
break;
case "life+":
this.life = 100;
this.log("cheat success!");
break;
case "life-":
this.life = 1;
this.log("cheat success!");
break;
case "difficulty+":
this.difficulty *= 2;
this.log("cheat success! difficulty = " + this.difficulty);
break;
case "difficulty-":
this.difficulty /= 2;
this.log("cheat success! difficulty = " + this.difficulty);
break;
}
},
/**
* 主循环方法
*/
step: function () {
if (this.is_debug && _TD && _TD.cheat) {
// 检查作弊代码
this.checkCheat(_TD.cheat);
_TD.cheat = "";
}
if (this.is_paused) return;
this.iframe ++; // 当前总第多少帧
if (this.iframe % 50 == 0) {
// 计算 fps
var t = (new Date()).getTime(),
step_time = this.step_time;
this.fps = Math.round(500000 / (t - this.last_iframe_time)) / 10;
this.last_iframe_time = t;
// 动态调整 step_time ,保证 fps 恒定为 24 左右
if (this.fps < this._exp_fps_0 && step_time > 1) {
step_time --;
} else if (this.fps > this._exp_fps_1) {
step_time ++;
}
// if (step_time != this.step_time)
// TD.log("FPS: " + this.fps + ", Step Time: " + step_time);
this.step_time = step_time;
}
if (this.iframe % 2400 == 0) TD.gc(); // 每隔一段时间自动回收垃圾
this.stage.step();
this.stage.render();
var _this = this;
this._st = setTimeout(function () {
_this.step();
}, this.step_time);
},
/**
* 取得事件相对于 canvas 左上角的坐标
* @param e
*/
getEventXY: function (e) {
var wra = TD.lang.$e("wrapper"),
x = e.clientX - wra.offsetLeft - this.canvas.offsetLeft + Math.max(document.documentElement.scrollLeft, document.body.scrollLeft),
y = e.clientY - wra.offsetTop - this.canvas.offsetTop + Math.max(document.documentElement.scrollTop, document.body.scrollTop);
return [x, y];
},
/**
* 鼠标移到指定位置事件
* @param x
* @param y
*/
hover: function (x, y) {
this.eventManager.hover(x, y);
},
/**
* 点击事件
* @param x
* @param y
*/
click: function (x, y) {
this.eventManager.click(x, y);
},
/**
* 是否将 canvas 中的鼠标指针变为手的形状
* @param v {Boolean}
*/
mouseHand: function (v) {
this.canvas.style.cursor = v ? "pointer" : "default";
},
/**
* 显示调试信息,只在 is_debug 为 true 的情况下有效
* @param txt
*/
log: function (txt) {
this.is_debug && window.console && console.log && console.log(txt);
},
/**
* 回收内存
* 注意:CollectGarbage 只在 IE 下有效
*/
gc: function () {
if (window.CollectGarbage) {
CollectGarbage();
setTimeout(CollectGarbage, 1);
}
}
};
for (i = 0; this.a[i]; i ++) {
// 依次执行添加到列表中的函数
this.a[i](TD);
}
delete this.a;
TD.init(td_board);
}
}; | zzy-code-test | html5/tower_defense/js/td.js | JavaScript | gpl2 | 6,425 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
var _default_wait_clearInvalidElements = 20;
// map 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var map_obj = {
_init: function (cfg) {
cfg = cfg || {};
this.grid_x = cfg.grid_x || 10;
this.grid_y = cfg.grid_y || 10;
this.x = cfg.x || 0;
this.y = cfg.y || 0;
this.width = this.grid_x * TD.grid_size;
this.height = this.grid_y * TD.grid_size;
this.x2 = this.x + this.width;
this.y2 = this.y + this.width;
this.grids = [];
this.entrance = this.exit = null;
this.buildings = [];
this.monsters = [];
this.bullets = [];
this.scene = cfg.scene;
this.is_main_map = !!cfg.is_main_map;
this.select_hl = TD.MapSelectHighLight(this.id + "-hl", {
map: this
});
this.select_hl.addToScene(this.scene, 1, 9);
this.selected_building = null;
this._wait_clearInvalidElements = _default_wait_clearInvalidElements;
this._wait_add_monsters = 0;
this._wait_add_monsters_arr = [];
if (this.is_main_map) {
this.mmm = new MainMapMask(this.id + "-mmm", {
map: this
});
this.mmm.addToScene(this.scene, 1, 7);
}
// 下面添加相应的格子
var i, l = this.grid_x * this.grid_y,
grid_data = cfg["grid_data"] || [],
d, grid;
for (i = 0; i < l; i ++) {
d = grid_data[i] || {};
d.mx = i % this.grid_x;
d.my = Math.floor(i / this.grid_x);
d.map = this;
d.step_level = this.step_level;
d.render_level = this.render_level;
grid = new TD.Grid(this.id + "-grid-" + d.mx + "-" + d.my, d);
this.grids.push(grid);
}
if (cfg.entrance && cfg.exit && !TD.lang.arrayEqual(cfg.entrance, cfg.exit)) {
this.entrance = this.getGrid(cfg.entrance[0], cfg.entrance[1]);
this.entrance.is_entrance = true;
this.exit = this.getGrid(cfg.exit[0], cfg.exit[1]);
this.exit.is_exit = true;
}
var _this = this;
if (cfg.grids_cfg) {
TD.lang.each(cfg.grids_cfg, function (obj) {
var grid = _this.getGrid(obj.pos[0], obj.pos[1]);
if (!grid) return;
if (!isNaN(obj.passable_flag))
grid.passable_flag = obj.passable_flag;
if (!isNaN(obj.build_flag))
grid.build_flag = obj.build_flag;
if (obj.building) {
grid.addBuilding(obj.building);
}
});
}
},
/**
* 检查地图中是否有武器(具备攻击性的建筑)
* 因为第一波怪物只有在地图上有了第一件武器后才会出现
*/
checkHasWeapon: function () {
this.has_weapon = (this.anyBuilding(function (obj) {
return obj.is_weapon;
}) != null);
},
/**
* 取得指定位置的格子对象
* @param mx {Number} 地图上的坐标 x
* @param my {Number} 地图上的坐标 y
*/
getGrid: function (mx, my) {
var p = my * this.grid_x + mx;
return this.grids[p];
},
anyMonster: function (f) {
return TD.lang.any(this.monsters, f);
},
anyBuilding: function (f) {
return TD.lang.any(this.buildings, f);
},
anyBullet: function (f) {
return TD.lang.any(this.bullets, f);
},
eachBuilding: function (f) {
TD.lang.each(this.buildings, f);
},
eachMonster: function (f) {
TD.lang.each(this.monsters, f);
},
eachBullet: function (f) {
TD.lang.each(this.bullets, f);
},
/**
* 预建设
* @param building_type {String}
*/
preBuild: function (building_type) {
TD.mode = "build";
if (this.pre_building) {
this.pre_building.remove();
}
this.pre_building = new TD.Building(this.id + "-" + "pre-building-" + TD.lang.rndStr(), {
type: building_type,
map: this,
is_pre_building: true
});
this.scene.addElement(this.pre_building, 1, this.render_level + 1);
//this.show_all_ranges = true;
},
/**
* 退出预建设状态
*/
cancelPreBuild: function () {
TD.mode = "normal";
if (this.pre_building) {
this.pre_building.remove();
}
//this.show_all_ranges = false;
},
/**
* 清除地图上无效的元素
*/
clearInvalidElements: function () {
if (this._wait_clearInvalidElements > 0) {
this._wait_clearInvalidElements --;
return;
}
this._wait_clearInvalidElements = _default_wait_clearInvalidElements;
var a = [];
TD.lang.shift(this.buildings, function (obj) {
if (obj.is_valid)
a.push(obj);
});
this.buildings = a;
a = [];
TD.lang.shift(this.monsters, function (obj) {
if (obj.is_valid)
a.push(obj);
});
this.monsters = a;
a = [];
TD.lang.shift(this.bullets, function (obj) {
if (obj.is_valid)
a.push(obj);
});
this.bullets = a;
},
/**
* 在地图的入口处添加一个怪物
* @param monster 可以是数字,也可以是 monster 对象
*/
addMonster: function (monster) {
if (!this.entrance) return;
if (typeof monster == "number") {
monster = new TD.Monster(null, {
idx: monster,
difficulty: TD.difficulty,
step_level: this.step_level,
render_level: this.render_level + 2
});
}
this.entrance.addMonster(monster);
},
/**
* 在地图的入口处添加 n 个怪物
* @param n
* @param monster
*/
addMonsters: function (n, monster) {
this._wait_add_monsters = n;
this._wait_add_monsters_objidx = monster;
},
/**
* arr 的格式形如:
* [[1, 0], [2, 5], [3, 6], [10, 4]...]
*/
addMonsters2: function (arr) {
this._wait_add_monsters_arr = arr;
},
/**
* 检查地图的指定格子是否可通过
* @param mx {Number}
* @param my {Number}
*/
checkPassable: function (mx, my) {
var grid = this.getGrid(mx, my);
return (grid != null && grid.passable_flag == 1 && grid.build_flag != 2);
},
step: function () {
this.clearInvalidElements();
if (this._wait_add_monsters > 0) {
this.addMonster(this._wait_add_monsters_objidx);
this._wait_add_monsters --;
} else if (this._wait_add_monsters_arr.length > 0) {
var a = this._wait_add_monsters_arr.shift();
this.addMonsters(a[0], a[1]);
}
},
render: function () {
var ctx = TD.ctx;
ctx.strokeStyle = "#99a";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.strokeRect(this.x + 0.5, this.y + 0.5, this.width, this.height);
ctx.closePath();
ctx.stroke();
},
/**
* 鼠标移出地图事件
*/
onOut: function () {
if (this.is_main_map && this.pre_building)
this.pre_building.hide();
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* grid_x: 宽度(格子),
* grid_y: 高度(格子),
* scene: 属于哪个场景,
* }
*/
TD.Map = function (id, cfg) {
// map 目前只需要监听 out 事件
// 虽然只需要监听 out 事件,但同时也需要监听 enter ,因为如果
// 没有 enter ,out 将永远不会被触发
cfg.on_events = ["enter", "out"];
var map = new TD.Element(id, cfg);
TD.lang.mix(map, map_obj);
map._init(cfg);
return map;
};
/**
* 地图选中元素高亮边框对象
*/
var map_selecthl_obj = {
_init: function (cfg) {
this.map = cfg.map;
this.width = TD.grid_size + 2;
this.height = TD.grid_size + 2;
this.is_visiable = false;
},
show: function (grid) {
this.x = grid.x;
this.y = grid.y;
this.is_visiable = true;
},
render: function () {
var ctx = TD.ctx;
ctx.lineWidth = 2;
ctx.strokeStyle = "#f93";
ctx.beginPath();
ctx.strokeRect(this.x, this.y, this.width - 1, this.height - 1);
ctx.closePath();
ctx.stroke();
}
};
/**
* 地图选中的高亮框
* @param cfg <object> 至少需要包含
* {
* map: map 对象
* }
*/
TD.MapSelectHighLight = function (id, cfg) {
var map_selecthl = new TD.Element(id, cfg);
TD.lang.mix(map_selecthl, map_selecthl_obj);
map_selecthl._init(cfg);
return map_selecthl;
};
var mmm_obj = {
_init: function (cfg) {
this.map = cfg.map;
this.x1 = this.map.x;
this.y1 = this.map.y;
this.x2 = this.map.x2 + 1;
this.y2 = this.map.y2 + 1;
this.w = this.map.scene.stage.width;
this.h = this.map.scene.stage.height;
this.w2 = this.w - this.x2;
this.h2 = this.h - this.y2;
},
render: function () {
var ctx = TD.ctx;
/*ctx.clearRect(0, 0, this.x1, this.h);
ctx.clearRect(0, 0, this.w, this.y1);
ctx.clearRect(0, this.y2, this.w, this.h2);
ctx.clearRect(this.x2, 0, this.w2, this.h2);*/
ctx.fillStyle = "#fff";
ctx.beginPath();
ctx.fillRect(0, 0, this.x1, this.h);
ctx.fillRect(0, 0, this.w, this.y1);
ctx.fillRect(0, this.y2, this.w, this.h2);
ctx.fillRect(this.x2, 0, this.w2, this.h);
ctx.closePath();
ctx.fill();
}
};
/**
* 主地图外边的遮罩,用于遮住超出地图的射程等
*/
function MainMapMask(id, cfg) {
var mmm = new TD.Element(id, cfg);
TD.lang.mix(mmm, mmm_obj);
mmm._init(cfg);
return mmm;
}
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-obj-map.js | JavaScript | gpl2 | 9,460 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
TD.lang = {
/**
* document.getElementById 方法的简写
* @param el_id {String}
*/
$e: function (el_id) {
return document.getElementById(el_id);
},
/**
* 创建一个 DOM 元素
* @param tag_name {String}
* @param attributes {Object}
* @param parent_node {HTMLElement}
* @return {HTMLElement}
*/
$c: function (tag_name, attributes, parent_node) {
var el = document.createElement(tag_name);
attributes = attributes || {};
for (var k in attributes)
el.setAttribute(k, attributes[k]);
if (parent_node)
parent_node.appendChild(el);
return el;
},
/**
* 从字符串 s 左边截取n个字符
* 如果包含汉字,则汉字按两个字符计算
* @param s {String} 输入的字符串
* @param n {Number}
*/
strLeft: function (s, n) {
var s2 = s.slice(0, n),
i = s2.replace(/[^\x00-\xff]/g, "**").length;
if (i <= n) return s2;
i -= s2.length;
switch (i) {
case 0: return s2;
case n: return s.slice(0, n >> 1);
default:
var k = n - i,
s3 = s.slice(k, n),
j = s3.replace(/[\x00-\xff]/g, "").length;
return j ?
s.slice(0, k) + this.arguments.callee(s3, j) :
s.slice(0, k);
}
},
/**
* 取得一个字符串的字节长度
* 汉字等字符长度算2,英文、数字等算1
* @param s {String}
*/
strLen2: function (s) {
return s.replace(/[^\x00-\xff]/g, "**").length;
},
/**
* 对一个数组的每一个元素执行指定方法
* @param list {Array}
* @param f {Function}
*/
each: function (list, f) {
if (Array.prototype.forEach) {
list.forEach(f);
} else {
for (var i = 0, l = list.length; i < l; i ++) {
f(list[i]);
}
}
},
/**
* 对一个数组的每一项依次执行指定方法,直到某一项的返回值为 true
* 返回第一个令 f 值为 true 的元素,如没有元素令 f 值为 true,则
* 返回 null
* @param list {Array}
* @param f {Function}
* @return {Object}
*/
any: function (list, f) {
for (var i = 0, l = list.length; i < l; i ++) {
if (f(list[i]))
return list[i];
}
return null;
},
/**
* 依次弹出列表中的元素,并对其进行操作
* 注意,执行完毕之后原数组将被清空
* 类似于 each,不同的是这个函数执行完后原数组将被清空
* @param list {Array}
* @param f {Function}
*/
shift: function (list, f) {
while (list[0]) {
f(list.shift());
// f.apply(list.shift(), args);
}
},
/**
* 传入一个数组,将其随机排序并返回
* 返回的是一个新的数组,原数组不变
* @param list {Array}
* @return {Array}
*/
rndSort: function (list) {
var a = list.concat();
return a.sort(function () {
return Math.random() - 0.5;
});
},
_rndRGB2: function (v) {
var s = v.toString(16);
return s.length == 2 ? s : ("0" + s);
},
/**
* 随机生成一个 RGB 颜色
*/
rndRGB: function () {
var r = Math.floor(Math.random() * 256),
g = Math.floor(Math.random() * 256),
b = Math.floor(Math.random() * 256);
return "#" + this._rndRGB2(r) + this._rndRGB2(g) + this._rndRGB2(b);
},
/**
* 将一个 rgb 色彩字符串转化为一个数组
* eg: '#ffffff' => [255, 255, 255]
* @param rgb_str {String} rgb色彩字符串,类似于“#f8c693”
*/
rgb2Arr: function (rgb_str) {
if (rgb_str.length != 7) return [0, 0, 0];
var r = rgb_str.substr(1, 2),
g = rgb_str.substr(3, 2),
b = rgb_str.substr(3, 2);
return [parseInt(r, 16), parseInt(g, 16), parseInt(b, 16)];
},
/**
* 生成一个长度为 n 的随机字符串
*
* @param n {Number}
*/
rndStr: function (n) {
n = n || 16;
var chars = "1234567890abcdefghijklmnopqrstuvwxyz",
a = [],
i, chars_len = chars.length, r;
for (i = 0; i < n; i ++) {
r = Math.floor(Math.random() * chars_len);
a.push(chars.substr(r, 1));
}
return a.join("");
},
/**
* 空函数,一般用于占位
*/
nullFunc: function () {
},
/**
* 判断两个数组是否相等
*
* @param arr1 {Array}
* @param arr2 {Array}
*/
arrayEqual: function (arr1, arr2) {
var i, l = arr1.length;
if (l != arr2.length) return false;
for (i = 0; i < l; i ++) {
if (arr1[i] != arr2[i]) return false;
}
return true;
},
/**
* 将所有 s 的属性复制给 r
* @param r {Object}
* @param s {Object}
* @param is_overwrite {Boolean} 如指定为 false ,则不覆盖已有的值,其它值
* 包括 undefined ,都表示 s 中的同名属性将覆盖 r 中的值
*/
mix: function (r, s, is_overwrite) {
if (!s || !r) return r;
for (var p in s) {
if (is_overwrite !== false || !(p in r)) {
r[p] = s[p];
}
}
return r;
}
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-lang.js | JavaScript | gpl2 | 5,293 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
// panel 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var panel_obj = {
_init: function (cfg) {
cfg = cfg || {};
this.x = cfg.x;
this.y = cfg.y;
this.scene = cfg.scene;
this.map = cfg.main_map;
// make panel map
var panel_map = new TD.Map("panel-map", TD.lang.mix({
x: this.x + cfg.map.x,
y: this.y + cfg.map.y,
scene: this.scene,
step_level: this.step_level,
render_level: this.render_level
}, cfg.map, false));
this.addToScene(this.scene, 1, 7);
panel_map.addToScene(this.scene, 1, 7, panel_map.grids);
this.scene.panel_map = panel_map;
this.gameover_obj = new TD.GameOver("panel-gameover", {
panel: this,
scene: this.scene,
step_level: this.step_level,
is_visiable: false,
x: 0,
y: 0,
width: this.scene.stage.width,
height: this.scene.stage.height,
render_level: 9
});
this.balloontip = new TD.BalloonTip("panel-balloon-tip", {
scene: this.scene,
step_level: this.step_level,
render_level: 9
});
this.balloontip.addToScene(this.scene, 1, 9);
// make buttons
// 暂停按钮
this.btn_pause = new TD.Button("panel-btn-pause", {
scene: this.scene,
x: this.x,
y: this.y + 260,
text: TD._t("button_pause_text"),
//desc: TD._t("button_pause_desc_0"),
step_level: this.step_level,
render_level: this.render_level + 1,
onClick: function () {
if (this.scene.state == 1) {
this.scene.pause();
this.text = TD._t("button_continue_text");
this.scene.panel.btn_upgrade.hide();
this.scene.panel.btn_sell.hide();
this.scene.panel.btn_restart.show();
//this.desc = TD._t("button_pause_desc_1");
} else if (this.scene.state == 2) {
this.scene.start();
this.text = TD._t("button_pause_text");
this.scene.panel.btn_restart.hide();
if (this.scene.map.selected_building) {
this.scene.panel.btn_upgrade.show();
this.scene.panel.btn_sell.show();
}
//this.desc = TD._t("button_pause_desc_0");
}
}
});
// 重新开始按钮
this.btn_restart = new TD.Button("panel-btn-restart", {
scene: this.scene,
x: this.x,
y: this.y + 300,
is_visiable: false,
text: TD._t("button_restart_text"),
step_level: this.step_level,
render_level: this.render_level + 1,
onClick: function () {
setTimeout(function () {
TD.stage.clear();
TD.is_paused = true;
TD.start();
TD.mouseHand(false);
}, 0);
}
});
// 建筑升级按钮
this.btn_upgrade = new TD.Button("panel-btn-upgrade", {
scene: this.scene,
x: this.x,
y: this.y + 300,
is_visiable: false,
text: TD._t("button_upgrade_text"),
step_level: this.step_level,
render_level: this.render_level + 1,
onClick: function () {
this.scene.map.selected_building.tryToUpgrade(this);
}
});
// 建筑出售按钮
this.btn_sell = new TD.Button("panel-btn-sell", {
scene: this.scene,
x: this.x,
y: this.y + 340,
is_visiable: false,
text: TD._t("button_sell_text"),
step_level: this.step_level,
render_level: this.render_level + 1,
onClick: function () {
this.scene.map.selected_building.tryToSell(this);
}
});
},
step: function () {
if (TD.life_recover) {
this._life_recover = this._life_recover2 = TD.life_recover;
this._life_recover_wait = this._life_recover_wait2 = TD.exp_fps * 3;
TD.life_recover = 0;
}
if (this._life_recover && (TD.iframe % TD.exp_fps_eighth == 0)) {
TD.life ++;
this._life_recover --;
}
},
render: function () {
// 画状态文字
var ctx = TD.ctx;
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillStyle = "#000";
ctx.font = "normal 12px 'Courier New'";
ctx.beginPath();
ctx.fillText(TD._t("panel_money_title") + TD.money, this.x, this.y);
ctx.fillText(TD._t("panel_score_title") + TD.score, this.x, this.y + 20);
ctx.fillText(TD._t("panel_life_title") + TD.life, this.x, this.y + 40);
ctx.fillText(TD._t("panel_building_title") + this.map.buildings.length,
this.x, this.y + 60);
ctx.fillText(TD._t("panel_monster_title") + this.map.monsters.length,
this.x, this.y + 80);
ctx.fillText(TD._t("wave_info", [this.scene.wave]), this.x, this.y + 210);
ctx.closePath();
if (this._life_recover_wait) {
// 画生命恢复提示
var a = this._life_recover_wait / this._life_recover_wait2;
ctx.fillStyle = "rgba(255, 0, 0, " + a + ")";
ctx.font = "bold 12px 'Verdana'";
ctx.beginPath();
ctx.fillText("+" + this._life_recover2, this.x + 60, this.y + 40);
ctx.closePath();
this._life_recover_wait --;
}
// 在右下角画版本信息
ctx.textAlign = "right";
ctx.fillStyle = "#666";
ctx.font = "normal 12px 'Courier New'";
ctx.beginPath();
ctx.fillText("version: " + TD.version + " | oldj.net", TD.stage.width - TD.padding,
TD.stage.height - TD.padding * 2);
ctx.closePath();
// 在左下角画FPS信息
ctx.textAlign = "left";
ctx.fillStyle = "#666";
ctx.font = "normal 12px 'Courier New'";
ctx.beginPath();
ctx.fillText("FPS: " + TD.fps, TD.padding, TD.stage.height - TD.padding * 2);
ctx.closePath();
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* life: 怪物的生命值
* shield: 怪物的防御值
* speed: 怪物的速度
* }
*/
TD.Panel = function (id, cfg) {
var panel = new TD.Element(id, cfg);
TD.lang.mix(panel, panel_obj);
panel._init(cfg);
return panel;
};
// balloon tip对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var balloontip_obj = {
_init: function (cfg) {
cfg = cfg || {};
this.scene = cfg.scene;
},
caculatePos: function () {
var el = this.el;
this.x = el.cx + 0.5;
this.y = el.cy + 0.5;
if (this.x + this.width > this.scene.stage.width - TD.padding) {
this.x = this.x - this.width;
}
this.px = this.x + 5;
this.py = this.y + 4;
},
msg: function (txt, el) {
this.text = txt;
var ctx = TD.ctx;
ctx.font = "normal 12px 'Courier New'";
this.width = Math.max(
ctx.measureText(txt).width + 10,
TD.lang.strLen2(txt) * 6 + 10
);
this.height = 24;
if (el && el.cx && el.cy) {
this.el = el;
this.caculatePos();
this.show();
}
},
step: function () {
if (!this.el || !this.el.is_valid) {
this.hide();
return;
}
if (this.el.is_monster) {
// monster 会移动,所以需要重新计算 tip 的位置
this.caculatePos();
}
},
render: function () {
if (!this.el) return;
var ctx = TD.ctx;
ctx.lineWidth = 1;
ctx.fillStyle = "rgba(255, 255, 0, 0.5)";
ctx.strokeStyle = "rgba(222, 222, 0, 0.9)";
ctx.beginPath();
ctx.rect(this.x, this.y, this.width, this.height);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillStyle = "#000";
ctx.font = "normal 12px 'Courier New'";
ctx.beginPath();
ctx.fillText(this.text, this.px, this.py);
ctx.closePath();
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* scene: scene
* }
*/
TD.BalloonTip = function (id, cfg) {
var balloontip = new TD.Element(id, cfg);
TD.lang.mix(balloontip, balloontip_obj);
balloontip._init(cfg);
return balloontip;
};
// button 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var button_obj = {
_init: function (cfg) {
cfg = cfg || {};
this.text = cfg.text;
this.onClick = cfg.onClick || TD.lang.nullFunc;
this.x = cfg.x;
this.y = cfg.y;
this.width = cfg.width || 80;
this.height = cfg.height || 30;
this.font_x = this.x + 8;
this.font_y = this.y + 7;
this.scene = cfg.scene;
this.desc = cfg.desc || "";
this.addToScene(this.scene, this.step_level, this.render_level);
this.caculatePos();
},
onEnter: function () {
TD.mouseHand(true);
if (this.desc) {
this.scene.panel.balloontip.msg(this.desc, this);
}
},
onOut: function () {
TD.mouseHand(false);
if (this.scene.panel.balloontip.el == this) {
this.scene.panel.balloontip.hide();
}
},
render: function () {
var ctx = TD.ctx;
ctx.lineWidth = 2;
ctx.fillStyle = this.is_hover ? "#eee" : "#ccc";
ctx.strokeStyle = "#999";
ctx.beginPath();
ctx.rect(this.x, this.y, this.width, this.height);
ctx.closePath();
ctx.fill();
ctx.stroke();
ctx.textAlign = "left";
ctx.textBaseline = "top";
ctx.fillStyle = "#000";
ctx.font = "normal 12px 'Courier New'";
ctx.beginPath();
ctx.fillText(this.text, this.font_x, this.font_y);
ctx.closePath();
ctx.fill();
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* x:
* y:
* text:
* onClick: function
* sence:
* }
*/
TD.Button = function (id, cfg) {
cfg.on_events = ["enter", "out", "click"];
var button = new TD.Element(id, cfg);
TD.lang.mix(button, button_obj);
button._init(cfg);
return button;
};
// gameover 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var gameover_obj = {
_init: function (cfg) {
this.panel = cfg.panel;
this.scene = cfg.scene;
this.addToScene(this.scene, 1, 9);
},
render: function () {
this.panel.btn_pause.hide();
this.panel.btn_upgrade.hide();
this.panel.btn_sell.hide();
this.panel.btn_restart.show();
var ctx = TD.ctx;
ctx.textAlign = "center";
ctx.textBaseline = "middle";
ctx.fillStyle = "#ccc";
ctx.font = "bold 62px 'Verdana'";
ctx.beginPath();
ctx.fillText("GAME OVER", this.width / 2, this.height / 2);
ctx.closePath();
ctx.fillStyle = "#f00";
ctx.font = "bold 60px 'Verdana'";
ctx.beginPath();
ctx.fillText("GAME OVER", this.width / 2, this.height / 2);
ctx.closePath();
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* panel:
* scene:
* }
*/
TD.GameOver = function (id, cfg) {
var obj = new TD.Element(id, cfg);
TD.lang.mix(obj, gameover_obj);
obj._init(cfg);
return obj;
};
/**
* 恢复 n 点生命值
* @param n
*/
TD.recover = function (n) {
// TD.life += n;
TD.life_recover = n;
TD.log("life recover: " + n);
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-obj-panel.js | JavaScript | gpl2 | 11,345 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
// grid 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var grid_obj = {
_init: function (cfg) {
cfg = cfg || {};
this.map = cfg.map;
this.scene = this.map.scene;
this.mx = cfg.mx; // 在 map 中的格子坐标
this.my = cfg.my;
this.width = TD.grid_size;
this.height = TD.grid_size;
this.is_entrance = this.is_exit = false;
this.passable_flag = 1; // 0: 不可通过; 1: 可通过
this.build_flag = 1;// 0: 不可修建; 1: 可修建; 2: 已修建
this.building = null;
this.caculatePos();
},
/**
* 根据 map 位置及本 grid 的 (mx, my) ,计算格子的位置
*/
caculatePos: function () {
this.x = this.map.x + this.mx * TD.grid_size;
this.y = this.map.y + this.my * TD.grid_size;
this.x2 = this.x + TD.grid_size;
this.y2 = this.y + TD.grid_size;
this.cx = Math.floor(this.x + TD.grid_size / 2);
this.cy = Math.floor(this.y + TD.grid_size / 2);
},
/**
* 检查如果在当前格子建东西,是否会导致起点与终点被阻塞
*/
checkBlock: function () {
if (this.is_entrance || this.is_exit) {
this._block_msg = TD._t("entrance_or_exit_be_blocked");
return true;
}
var is_blocked,
_this = this,
fw = new TD.FindWay(
this.map.grid_x, this.map.grid_y,
this.map.entrance.mx, this.map.entrance.my,
this.map.exit.mx, this.map.exit.my,
function (x, y) {
return !(x == _this.mx && y == _this.my) && _this.map.checkPassable(x, y);
}
);
is_blocked = fw.is_blocked;
if (!is_blocked) {
is_blocked = !!this.map.anyMonster(function (obj) {
return obj.chkIfBlocked(_this.mx, _this.my);
});
if (is_blocked)
this._block_msg = TD._t("monster_be_blocked");
} else {
this._block_msg = TD._t("blocked");
}
return is_blocked;
},
/**
* 购买建筑
* @param building_type {String}
*/
buyBuilding: function (building_type) {
var cost = TD.getDefaultBuildingAttributes(building_type).cost || 0;
if (TD.money >= cost) {
TD.money -= cost;
this.addBuilding(building_type);
} else {
TD.log(TD._t("not_enough_money", [cost]));
this.scene.panel.balloontip.msg(TD._t("not_enough_money", [cost]), this);
}
},
/**
* 在当前格子添加指定类型的建筑
* @param building_type {String}
*/
addBuilding: function (building_type) {
if (this.building) {
// 如果当前格子已经有建筑,先将其移除
this.removeBuilding();
}
var building = new TD.Building("building-" + building_type + "-" + TD.lang.rndStr(), {
type: building_type,
step_level: this.step_level,
render_level: this.render_level
});
building.locate(this);
this.scene.addElement(building, this.step_level, this.render_level + 1);
this.map.buildings.push(building);
this.building = building;
this.build_flag = 2;
this.map.checkHasWeapon();
if (this.map.pre_building)
this.map.pre_building.hide();
},
/**
* 移除当前格子的建筑
*/
removeBuilding: function () {
if (this.build_flag == 2)
this.build_flag = 1;
if (this.building)
this.building.remove();
this.building = null;
},
/**
* 在当前建筑添加一个怪物
* @param monster
*/
addMonster: function (monster) {
monster.beAddToGrid(this);
this.map.monsters.push(monster);
monster.start();
},
/**
* 高亮当前格子
* @param show {Boolean}
*/
hightLight: function (show) {
this.map.select_hl[show ? "show" : "hide"](this);
},
render: function () {
var ctx = TD.ctx,
px = this.x + 0.5,
py = this.y + 0.5;
//if (this.map.is_main_map) {
//ctx.drawImage(this.map.res,
//0, 0, 32, 32, this.x, this.y, 32, 32
//);
//}
if (this.is_hover) {
ctx.fillStyle = "rgba(255, 255, 200, 0.2)";
ctx.beginPath();
ctx.fillRect(px, py, this.width, this.height);
ctx.closePath();
ctx.fill();
}
if (this.passable_flag == 0) {
// 不可通过
ctx.fillStyle = "#fcc";
ctx.beginPath();
ctx.fillRect(px, py, this.width, this.height);
ctx.closePath();
ctx.fill();
}
/**
* 画入口及出口
*/
if (this.is_entrance || this.is_exit) {
ctx.lineWidth = 1;
ctx.fillStyle = "#ccc";
ctx.beginPath();
ctx.fillRect(px, py, this.width, this.height);
ctx.closePath();
ctx.fill();
ctx.strokeStyle = "#666";
ctx.fillStyle = this.is_entrance ? "#fff" : "#666";
ctx.beginPath();
ctx.arc(this.cx, this.cy, TD.grid_size * 0.325, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
ctx.strokeStyle = "#eee";
ctx.lineWidth = 1;
ctx.beginPath();
ctx.strokeRect(px, py, this.width, this.height);
ctx.closePath();
ctx.stroke();
},
/**
* 鼠标进入当前格子事件
*/
onEnter: function () {
if (this.map.is_main_map && TD.mode == "build") {
if (this.build_flag == 1) {
this.map.pre_building.show();
this.map.pre_building.locate(this);
} else {
this.map.pre_building.hide();
}
} else if (this.map.is_main_map) {
var msg = "";
if (this.is_entrance) {
msg = TD._t("entrance");
} else if (this.is_exit) {
msg = TD._t("exit");
} else if (this.passable_flag == 0) {
msg = TD._t("_cant_pass");
} else if (this.build_flag == 0) {
msg = TD._t("_cant_build");
}
if (msg) {
this.scene.panel.balloontip.msg(msg, this);
}
}
},
/**
* 鼠标移出当前格子事件
*/
onOut: function () {
// 如果当前气球提示指向本格子,将其隐藏
if (this.scene.panel.balloontip.el == this) {
this.scene.panel.balloontip.hide();
}
},
/**
* 鼠标点击了当前格子事件
*/
onClick: function () {
if (this.scene.state != 1) return;
if (TD.mode == "build" && this.map.is_main_map && !this.building) {
// 如果处于建设模式下,并且点击在主地图的空格子上,则尝试建设指定建筑
if (this.checkBlock()) {
// 起点与终点之间被阻塞,不能修建
this.scene.panel.balloontip.msg(this._block_msg, this);
} else {
// 购买建筑
this.buyBuilding(this.map.pre_building.type);
}
} else if (!this.building && this.map.selected_building) {
// 取消选中建筑
this.map.selected_building.toggleSelected();
this.map.selected_building = null;
}
}
};
/**
* @param id {String}
* @param cfg {object} 配置对象
* 至少需要包含以下项:
* {
* mx: 在 map 格子中的横向坐标,
* my: 在 map 格子中的纵向坐标,
* map: 属于哪个 map,
* }
*/
TD.Grid = function (id, cfg) {
cfg.on_events = ["enter", "out", "click"];
var grid = new TD.Element(id, cfg);
TD.lang.mix(grid, grid_obj);
grid._init(cfg);
return grid;
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-obj-grid.js | JavaScript | gpl2 | 7,437 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
TD._msg_texts = {
"_cant_build": "不能在这儿修建",
"_cant_pass": "怪物不能通过这儿",
"entrance": "起点",
"exit": "终点",
"not_enough_money": "金钱不足,需要 $${0}!",
"wave_info": "第 ${0} 波",
"panel_money_title": "金钱: ",
"panel_score_title": "积分: ",
"panel_life_title": "生命: ",
"panel_building_title": "建筑: ",
"panel_monster_title": "怪物: ",
"building_name_wall": "路障",
"building_name_cannon": "炮台",
"building_name_LMG": "轻机枪",
"building_name_HMG": "重机枪",
"building_name_laser_gun": "激光炮",
"building_info": "${0}: 等级 ${1},攻击 ${2},速度 ${3},射程 ${4},战绩 ${5}",
"building_info_wall": "${0}",
"building_intro_wall": "路障 可以阻止怪物通过 ($${0})",
"building_intro_cannon": "炮台 射程、杀伤力较为平衡 ($${0})",
"building_intro_LMG": "轻机枪 射程较远,杀伤力一般 ($${0})",
"building_intro_HMG": "重机枪 快速射击,威力较大,射程一般 ($${0})",
"building_intro_laser_gun": "激光枪 伤害较大,命中率 100% ($${0})",
"click_to_build": "左键点击建造 ${0} ($${1})",
"upgrade": "升级 ${0} 到 ${1} 级,需花费 $${2}。",
"sell": "出售 ${0},可获得 $${1}",
"upgrade_success": "升级成功,${0} 已升级到 ${1} 级!下次升级需要 $${2}。",
"monster_info": "怪物: 生命 ${0},防御 ${1},速度 ${2},伤害 ${3}",
"button_upgrade_text": "升级",
"button_sell_text": "出售",
"button_start_text": "开始",
"button_restart_text": "重新开始",
"button_pause_text": "暂停",
"button_continue_text": "继续",
"button_pause_desc_0": "游戏暂停",
"button_pause_desc_1": "游戏继续",
"blocked": "不能在这儿修建建筑,起点与终点之间至少要有一条路可到达!",
"monster_be_blocked": "不能在这儿修建建筑,有怪物被围起来了!",
"entrance_or_exit_be_blocked": "不能在起点或终点处修建建筑!",
"_": "ERROR"
};
TD._t = TD.translate = function (k, args) {
args = (typeof args == "object" && args.constructor == Array) ? args : [];
var msg = this._msg_texts[k] || this._msg_texts["_"],
i,
l = args.length;
for (i = 0; i < l; i ++) {
msg = msg.replace("${" + i + "}", args[i]);
}
return msg;
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-msg.js | JavaScript | gpl2 | 2,611 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
/**
* 舞台类
* @param id {String} 舞台ID
* @param cfg {Object} 配置
*/
TD.Stage = function (id, cfg) {
this.id = id || ("stage-" + TD.lang.rndStr());
this.cfg = cfg || {};
this.width = this.cfg.width || 600;
this.height = this.cfg.height || 540;
/**
* mode 有以下状态:
* "normal": 普通状态
* "build": 建造模式
*/
this.mode = "normal";
/*
* state 有以下几种状态:
* 0: 等待中
* 1: 运行中
* 2: 暂停
* 3: 已结束
*/
this.state = 0;
this.acts = [];
this.current_act = null;
this._step2 = TD.lang.nullFunc;
this._init();
};
TD.Stage.prototype = {
_init: function () {
if (typeof this.cfg.init == "function") {
this.cfg.init.call(this);
}
if (typeof this.cfg.step2 == "function") {
this._step2 = this.cfg.step2;
}
},
start: function () {
this.state = 1;
TD.lang.each(this.acts, function (obj) {
obj.start();
});
},
pause: function () {
this.state = 2;
},
gameover: function () {
//this.pause();
this.current_act.gameover();
},
/**
* 清除本 stage 所有物品
*/
clear: function () {
this.state = 3;
TD.lang.each(this.acts, function (obj) {
obj.clear();
});
// delete this;
},
/**
* 主循环函数
*/
step: function () {
if (this.state != 1 || !this.current_act) return;
TD.eventManager.step();
this.current_act.step();
this._step2();
},
/**
* 绘制函数
*/
render: function () {
if (this.state == 0 || this.state == 3 || !this.current_act) return;
this.current_act.render();
},
addAct: function (act) {
this.acts.push(act);
},
addElement: function (el, step_level, render_level) {
if (this.current_act)
this.current_act.addElement(el, step_level, render_level);
}
};
}); // _TD.a.push end
// _TD.a.push begin
_TD.a.push(function (TD) {
TD.Act = function (stage, id) {
this.stage = stage;
this.id = id || ("act-" + TD.lang.rndStr());
/*
* state 有以下几种状态:
* 0: 等待中
* 1: 运行中
* 2: 暂停
* 3: 已结束
*/
this.state = 0;
this.scenes = [];
this.end_queue = []; // 本 act 结束后要执行的队列,添加时请保证里面全是函数
this.current_scene = null;
this._init();
};
TD.Act.prototype = {
_init: function () {
this.stage.addAct(this);
},
/*
* 开始当前 act
*/
start: function () {
if (this.stage.current_act && this.stage.current_act.state != 3) {
// queue...
this.state = 0;
this.stage.current_act.queue(this.start);
return;
}
// start
this.state = 1;
this.stage.current_act = this;
TD.lang.each(this.scenes, function (obj) {
obj.start();
});
},
pause: function () {
this.state = 2;
},
end: function () {
this.state = 3;
var f;
while (f = this.end_queue.shift()) {
f();
}
this.stage.current_act = null;
},
queue: function (f) {
this.end_queue.push(f);
},
clear: function () {
this.state = 3;
TD.lang.each(this.scenes, function (obj) {
obj.clear();
});
// delete this;
},
step: function () {
if (this.state != 1 || !this.current_scene) return;
this.current_scene.step();
},
render: function () {
if (this.state == 0 || this.state == 3 || !this.current_scene) return;
this.current_scene.render();
},
addScene: function (scene) {
this.scenes.push(scene);
},
addElement: function (el, step_level, render_level) {
if (this.current_scene)
this.current_scene.addElement(el, step_level, render_level);
},
gameover: function () {
//this.is_paused = true;
//this.is_gameover = true;
this.current_scene.gameover();
}
};
}); // _TD.a.push end
// _TD.a.push begin
_TD.a.push(function (TD) {
TD.Scene = function (act, id) {
this.act = act;
this.stage = act.stage;
this.is_gameover = false;
this.id = id || ("scene-" + TD.lang.rndStr());
/*
* state 有以下几种状态:
* 0: 等待中
* 1: 运行中
* 2: 暂停
* 3: 已结束
*/
this.state = 0;
this.end_queue = []; // 本 scene 结束后要执行的队列,添加时请保证里面全是函数
this._step_elements = [
// step 共分为 3 层
[],
// 0
[],
// 1 默认
[] // 2
];
this._render_elements = [ // 渲染共分为 10 层
[], // 0 背景 1 背景图片
[], // 1 背景 2
[], // 2 背景 3 地图、格子
[], // 3 地面 1 一般建筑
[], // 4 地面 2 人物、NPC等
[], // 5 地面 3
[], // 6 天空 1 子弹等
[], // 7 天空 2 主地图外边的遮罩,panel
[], // 8 天空 3
[] // 9 系统特殊操作,如选中高亮,提示、文字遮盖等
];
this._init();
};
TD.Scene.prototype = {
_init: function () {
this.act.addScene(this);
this.wave = 0; // 第几波
},
start: function () {
if (this.act.current_scene &&
this.act.current_scene != this &&
this.act.current_scene.state != 3) {
// queue...
this.state = 0;
this.act.current_scene.queue(this.start);
return;
}
// start
this.state = 1;
this.act.current_scene = this;
},
pause: function () {
this.state = 2;
},
end: function () {
this.state = 3;
var f;
while (f = this.end_queue.shift()) {
f();
}
this.clear();
this.act.current_scene = null;
},
/**
* 清空场景
*/
clear: function () {
// 清空本 scene 中引用的所有对象以回收内存
TD.lang.shift(this._step_elements, function (obj) {
TD.lang.shift(obj, function (obj2) {
// element
//delete this.scene;
obj2.del();
// delete this;
});
// delete this;
});
TD.lang.shift(this._render_elements, function (obj) {
TD.lang.shift(obj, function (obj2) {
// element
//delete this.scene;
obj2.del();
// delete this;
});
// delete this;
});
// delete this;
},
queue: function (f) {
this.end_queue.push(f);
},
gameover: function () {
if (this.is_gameover) return;
this.pause();
this.is_gameover = true;
},
step: function () {
if (this.state != 1) return;
if (TD.life <= 0) {
TD.life = 0;
this.gameover();
}
var i, a;
for (i = 0; i < 3; i ++) {
a = [];
var level_elements = this._step_elements[i];
TD.lang.shift(level_elements, function (obj) {
if (obj.is_valid) {
if (!obj.is_paused)
obj.step();
a.push(obj);
} else {
setTimeout(function () {
obj = null;
}, 500); // 一会儿之后将这个对象彻底删除以收回内存
}
});
this._step_elements[i] = a;
}
},
render: function () {
if (this.state == 0 || this.state == 3) return;
var i, a,
ctx = TD.ctx;
ctx.clearRect(0, 0, this.stage.width, this.stage.height);
for (i = 0; i < 10; i ++) {
a = [];
var level_elements = this._render_elements[i];
TD.lang.shift(level_elements, function (obj) {
if (obj.is_valid) {
if (obj.is_visiable)
obj.render();
a.push(obj);
}
});
this._render_elements[i] = a;
}
if (this.is_gameover) {
this.panel.gameover_obj.show();
}
},
addElement: function (el, step_level, render_level) {
//TD.log([step_level, render_level]);
step_level = step_level || el.step_level || 1;
render_level = render_level || el.render_level;
this._step_elements[step_level].push(el);
this._render_elements[render_level].push(el);
el.scene = this;
el.step_level = step_level;
el.render_level = render_level;
}
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-stage.js | JavaScript | gpl2 | 8,127 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
// building 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var building_obj = {
_init: function (cfg) {
this.is_selected = false;
this.level = 0;
this.killed = 0; // 当前建筑杀死了多少怪物
this.target = null;
cfg = cfg || {};
this.map = cfg.map || null;
this.grid = cfg.grid || null;
/**
* 子弹类型,可以有以下类型:
* 1:普通子弹
* 2:激光类,发射后马上命中,暂未实现
* 3:导弹类,击中后会爆炸,带来面攻击,暂未实现
*/
this.bullet_type = cfg.bullet_type || 1;
/**
* type 可能的值有:
* "wall": 墙壁,没有攻击性
* "cannon": 炮台
* "LMG": 轻机枪
* "HMG": 重机枪
* "laser_gun": 激光枪
*
*/
this.type = cfg.type;
this.speed = cfg.speed;
this.bullet_speed = cfg.bullet_speed;
this.is_pre_building = !!cfg.is_pre_building;
this.blink = this.is_pre_building;
this.wait_blink = this._default_wait_blink = 20;
this.is_weapon = (this.type != "wall"); // 墙等不可攻击的建筑此项为 false ,其余武器此项为 true
var o = TD.getDefaultBuildingAttributes(this.type);
TD.lang.mix(this, o);
this.range_px = this.range * TD.grid_size;
this.money = this.cost; // 购买、升级本建筑已花费的钱
this.caculatePos();
},
/**
* 升级本建筑需要的花费
*/
getUpgradeCost: function () {
return Math.floor(this.money * 0.75);
},
/**
* 出售本建筑能得到多少钱
*/
getSellMoney: function () {
return Math.floor(this.money * 0.5) || 1;
},
/**
* 切换选中 / 未选中状态
*/
toggleSelected: function () {
this.is_selected = !this.is_selected;
this.grid.hightLight(this.is_selected); // 高亮
var _this = this;
if (this.is_selected) {
// 如果当前建筑被选中
this.map.eachBuilding(function (obj) {
obj.is_selected = obj == _this;
});
// 取消另一个地图中选中建筑的选中状态
(
this.map.is_main_map ? this.scene.panel_map : this.scene.map
).eachBuilding(function (obj) {
obj.is_selected = false;
obj.grid.hightLight(false);
});
this.map.selected_building = this;
if (!this.map.is_main_map) {
// 在面版地图中选中了建筑,进入建筑模式
this.scene.map.preBuild(this.type);
} else {
// 取消建筑模式
this.scene.map.cancelPreBuild();
}
} else {
// 如果当前建筑切换为未选中状态
if (this.map.selected_building == this)
this.map.selected_building = null;
if (!this.map.is_main_map) {
// 取消建筑模式
this.scene.map.cancelPreBuild();
}
}
// 如果是选中 / 取消选中主地图上的建筑,显示 / 隐藏对应的操作按钮
if (this.map.is_main_map) {
if (this.map.selected_building) {
this.scene.panel.btn_upgrade.show();
this.scene.panel.btn_sell.show();
this.updateBtnDesc();
} else {
this.scene.panel.btn_upgrade.hide();
this.scene.panel.btn_sell.hide();
}
}
},
/**
* 生成、更新升级按钮的说明文字
*/
updateBtnDesc: function () {
this.scene.panel.btn_upgrade.desc = TD._t(
"upgrade", [
TD._t("building_name_" + this.type),
this.level + 1,
this.getUpgradeCost()
]);
this.scene.panel.btn_sell.desc = TD._t(
"sell", [
TD._t("building_name_" + this.type),
this.getSellMoney()
]);
},
/**
* 将本建筑放置到一个格子中
* @param grid {Element} 指定格子
*/
locate: function (grid) {
this.grid = grid;
this.map = grid.map;
this.cx = this.grid.cx;
this.cy = this.grid.cy;
this.x = this.grid.x;
this.y = this.grid.y;
this.x2 = this.grid.x2;
this.y2 = this.grid.y2;
this.width = this.grid.width;
this.height = this.grid.height;
this.px = this.x + 0.5;
this.py = this.y + 0.5;
this.wait_blink = this._default_wait_blink;
this._fire_wait = Math.floor(Math.max(2 / (this.speed * TD.global_speed), 1));
this._fire_wait2 = this._fire_wait;
},
/**
* 将本建筑彻底删除
*/
remove: function () {
// TD.log("remove building #" + this.id + ".");
if (this.grid && this.grid.building && this.grid.building == this)
this.grid.building = null;
this.hide();
this.del();
},
/**
* 寻找一个目标(怪物)
*/
findTaget: function () {
if (!this.is_weapon || this.is_pre_building || !this.grid) return;
var cx = this.cx, cy = this.cy,
range2 = Math.pow(this.range_px, 2);
// 如果当前建筑有目标,并且目标还是有效的,并且目标仍在射程内
if (this.target && this.target.is_valid &&
Math.pow(this.target.cx - cx, 2) + Math.pow(this.target.cy - cy, 2) <= range2)
return;
// 在进入射程的怪物中寻找新的目标
this.target = TD.lang.any(
TD.lang.rndSort(this.map.monsters), // 将怪物随机排序
function (obj) {
return Math.pow(obj.cx - cx, 2) + Math.pow(obj.cy - cy, 2) <= range2;
});
},
/**
* 取得目标的坐标(相对于地图左上角)
*/
getTargetPosition: function () {
if (!this.target) {
// 以 entrance 为目标
var grid = this.map.is_main_map ? this.map.entrance : this.grid;
return [grid.cx, grid.cy];
}
return [this.target.cx, this.target.cy];
},
/**
* 向自己的目标开火
*/
fire: function () {
if (!this.target || !this.target.is_valid) return;
if (this.type == "laser_gun") {
// 如果是激光枪,目标立刻被击中
this.target.beHit(this, this.damage);
return;
}
var muzzle = this.muzzle || [this.cx, this.cy], // 炮口的位置
cx = muzzle[0],
cy = muzzle[1];
new TD.Bullet(null, {
building: this,
damage: this.damage,
target: this.target,
speed: this.bullet_speed,
x: cx,
y: cy
});
},
tryToFire: function () {
if (!this.is_weapon || !this.target)
return;
this._fire_wait --;
if (this._fire_wait > 0) {
// return;
} else if (this._fire_wait < 0) {
this._fire_wait = this._fire_wait2;
} else {
this.fire();
}
},
_upgrade2: function (k) {
if (!this._upgrade_records[k])
this._upgrade_records[k] = this[k];
var v = this._upgrade_records[k],
mk = "max_" + k,
uk = "_upgrade_rule_" + k,
uf = this[uk] || TD.default_upgrade_rule;
if (!v || isNaN(v)) return;
v = uf(this.level, v);
if (this[mk] && !isNaN(this[mk]) && this[mk] < v)
v = this[mk];
this._upgrade_records[k] = v;
this[k] = Math.floor(v);
},
/**
* 升级建筑
*/
upgrade: function () {
if (!this._upgrade_records)
this._upgrade_records = {};
var attrs = [
// 可升级的变量
"damage", "range", "speed", "life", "shield"
], i, l = attrs.length;
for (i = 0; i < l; i ++)
this._upgrade2(attrs[i]);
this.level ++;
this.range_px = this.range * TD.grid_size;
},
tryToUpgrade: function (btn) {
var cost = this.getUpgradeCost(),
msg = "";
if (cost > TD.money) {
msg = TD._t("not_enough_money", [cost]);
} else {
TD.money -= cost;
this.money += cost;
this.upgrade();
msg = TD._t("upgrade_success", [
TD._t("building_name_" + this.type), this.level,
this.getUpgradeCost()
]);
}
this.updateBtnDesc();
this.scene.panel.balloontip.msg(msg, btn);
},
tryToSell: function () {
if (!this.is_valid) return;
TD.money += this.getSellMoney();
this.grid.removeBuilding();
this.is_valid = false;
this.map.selected_building = null;
this.map.select_hl.hide();
this.map.checkHasWeapon();
this.scene.panel.btn_upgrade.hide();
this.scene.panel.btn_sell.hide();
this.scene.panel.balloontip.hide();
},
step: function () {
if (this.blink) {
this.wait_blink --;
if (this.wait_blink < -this._default_wait_blink)
this.wait_blink = this._default_wait_blink;
}
this.findTaget();
this.tryToFire();
},
render: function () {
if (!this.is_visiable || this.wait_blink < 0) return;
var ctx = TD.ctx;
TD.renderBuilding(this);
if (
this.map.is_main_map &&
(
this.is_selected || (this.is_pre_building) ||
this.map.show_all_ranges
) &&
this.is_weapon && this.range > 0 && this.grid
) {
// 画射程
ctx.lineWidth = 1;
ctx.fillStyle = "rgba(187, 141, 32, 0.15)";
ctx.strokeStyle = "#bb8d20";
ctx.beginPath();
ctx.arc(this.cx, this.cy, this.range_px, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
}
if (this.type == "laser_gun" && this.target && this.target.is_valid) {
// 画激光
ctx.lineWidth = 3;
ctx.strokeStyle = "rgba(50, 50, 200, 0.5)";
ctx.beginPath();
ctx.moveTo(this.cx, this.cy);
ctx.lineTo(this.target.cx, this.target.cy);
ctx.closePath();
ctx.stroke();
ctx.lineWidth = 1;
ctx.strokeStyle = "rgba(150, 150, 255, 0.5)";
ctx.beginPath();
ctx.lineTo(this.cx, this.cy);
ctx.closePath();
ctx.stroke();
}
},
onEnter: function () {
if (this.is_pre_building) return;
var msg = "建筑工事";
if (this.map.is_main_map) {
msg = TD._t("building_info" + (this.type == "wall" ? "_wall" : ""), [TD._t("building_name_" + this.type), this.level, this.damage, this.speed, this.range, this.killed]);
} else {
msg = TD._t("building_intro_" + this.type, [TD.getDefaultBuildingAttributes(this.type).cost]);
}
this.scene.panel.balloontip.msg(msg, this.grid);
},
onOut: function () {
if (this.scene.panel.balloontip.el == this.grid) {
this.scene.panel.balloontip.hide();
}
},
onClick: function () {
if (this.is_pre_building || this.scene.state != 1) return;
this.toggleSelected();
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* type: 建筑类型,可选的值有
* "wall"
* "cannon"
* "LMG"
* "HMG"
* "laser_gun"
* }
*/
TD.Building = function (id, cfg) {
cfg.on_events = ["enter", "out", "click"];
var building = new TD.Element(id, cfg);
TD.lang.mix(building, building_obj);
building._init(cfg);
return building;
};
// bullet 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var bullet_obj = {
_init: function (cfg) {
cfg = cfg || {};
this.speed = cfg.speed;
this.damage = cfg.damage;
this.target = cfg.target;
this.cx = cfg.x;
this.cy = cfg.y;
this.r = cfg.r || Math.max(Math.log(this.damage), 2);
if (this.r < 1) this.r = 1;
if (this.r > 6) this.r = 6;
this.building = cfg.building || null;
this.map = cfg.map || this.building.map;
this.type = cfg.type || 1;
this.color = cfg.color || "#000";
this.map.bullets.push(this);
this.addToScene(this.map.scene, 1, 6);
if (this.type == 1) {
this.caculate();
}
},
/**
* 计算子弹的一些数值
*/
caculate: function () {
var sx, sy, c,
tx = this.target.cx,
ty = this.target.cy,
speed;
sx = tx - this.cx;
sy = ty - this.cy;
c = Math.sqrt(Math.pow(sx, 2) + Math.pow(sy, 2)),
speed = 20 * this.speed * TD.global_speed,
this.vx = sx * speed / c,
this.vy = sy * speed / c;
},
/**
* 检查当前子弹是否已超出地图范围
*/
checkOutOfMap: function () {
this.is_valid = !(
this.cx < this.map.x ||
this.cx > this.map.x2 ||
this.cy < this.map.y ||
this.cy > this.map.y2
);
return !this.is_valid;
},
/**
* 检查当前子弹是否击中了怪物
*/
checkHit: function () {
var cx = this.cx,
cy = this.cy,
r = this.r,
monster = this.map.anyMonster(function (obj) {
return Math.pow(obj.cx - cx, 2) + Math.pow(obj.cy - cy, 2) <= Math.pow(obj.r + r, 2) * 2;
});
if (monster) {
// 击中的怪物
monster.beHit(this.building, this.damage);
this.is_valid = false;
// 子弹小爆炸效果
TD.Explode(this.id + "-explode", {
cx: this.cx,
cy: this.cy,
r: this.r,
step_level: this.step_level,
render_level: this.render_level,
color: this.color,
scene: this.map.scene,
time: 0.2
});
return true;
}
return false;
},
step: function () {
if (this.checkOutOfMap() || this.checkHit()) return;
this.cx += this.vx;
this.cy += this.vy;
},
render: function () {
var ctx = TD.ctx;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.cx, this.cy, this.r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* x: 子弹发出的位置
* y: 子弹发出的位置
* speed:
* damage:
* target: 目标,一个 monster 对象
* building: 所属的建筑
* }
* 子弹类型,可以有以下类型:
* 1:普通子弹
* 2:激光类,发射后马上命中
* 3:导弹类,击中后会爆炸,带来面攻击
*/
TD.Bullet = function (id, cfg) {
var bullet = new TD.Element(id, cfg);
TD.lang.mix(bullet, bullet_obj);
bullet._init(cfg);
return bullet;
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-obj-building.js | JavaScript | gpl2 | 14,150 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
// monster 对象的属性、方法。注意属性中不要有数组、对象等
// 引用属性,否则多个实例的相关属性会发生冲突
var monster_obj = {
_init: function (cfg) {
cfg = cfg || {};
this.is_monster = true;
this.idx = cfg.idx || 1;
this.difficulty = cfg.difficulty || 1.0;
var attr = TD.getDefaultMonsterAttributes(this.idx);
this.speed = Math.floor(
(attr.speed + this.difficulty / 2) * (Math.random() * 0.5 + 0.75)
);
if (this.speed < 1) this.speed = 1;
if (this.speed > cfg.max_speed) this.speed = cfg.max_speed;
this.life = this.life0 = Math.floor(
attr.life * (this.difficulty + 1) * (Math.random() + 0.5) * 0.5
);
if (this.life < 1) this.life = this.life0 = 1;
this.shield = Math.floor(attr.shield + this.difficulty / 2);
if (this.shield < 0) this.shield = 0;
this.damage = Math.floor(
(attr.damage || 1) * (Math.random() * 0.5 + 0.75)
);
if (this.damage < 1) this.damage = 1;
this.money = attr.money || Math.floor(
Math.sqrt((this.speed + this.life) * (this.shield + 1) * this.damage)
);
if (this.money < 1) this.money = 1;
this.color = attr.color || TD.lang.rndRGB();
this.r = Math.floor(this.damage * 1.2);
if (this.r < 4) this.r = 4;
if (this.r > TD.grid_size / 2 - 4) this.r = TD.grid_size / 2 - 4;
this.render = attr.render;
this.grid = null; // 当前格子
this.map = null;
this.next_grid = null;
this.way = [];
this.toward = 2; // 默认面朝下方
this._dx = 0;
this._dy = 0;
this.is_blocked = false; // 前进的道路是否被阻塞了
},
caculatePos: function () {
// if (!this.map) return;
var r = this.r;
this.x = this.cx - r;
this.y = this.cy - r;
this.x2 = this.cx + r;
this.y2 = this.cy + r;
},
/**
* 怪物被击中
* @param building {Element} 对应的建筑(武器)
* @param damage {Number} 本次攻击的原始伤害值
*/
beHit: function (building, damage) {
if (!this.is_valid) return;
var min_damage = Math.ceil(damage * 0.1);
damage -= this.shield;
if (damage <= min_damage) damage = min_damage;
this.life -= damage;
TD.score += Math.floor(Math.sqrt(damage));
if (this.life <= 0) {
this.beKilled(building);
}
var balloontip = this.scene.panel.balloontip;
if (balloontip.el == this) {
balloontip.text = TD._t("monster_info", [this.life, this.shield, this.speed, this.damage]);
}
},
/**
* 怪物被杀死
* @param building {Element} 对应的建筑(武器)
*/
beKilled: function (building) {
if (!this.is_valid) return;
this.life = 0;
this.is_valid = false;
TD.money += this.money;
building.killed ++;
TD.Explode(this.id + "-explode", {
cx: this.cx,
cy: this.cy,
color: this.color,
r: this.r,
step_level: this.step_level,
render_level: this.render_level,
scene: this.grid.scene
});
},
arrive: function () {
this.grid = this.next_grid;
this.next_grid = null;
this.checkFinish();
},
findWay: function () {
var _this = this;
var fw = new TD.FindWay(
this.map.grid_x, this.map.grid_y,
this.grid.mx, this.grid.my,
this.map.exit.mx, this.map.exit.my,
function (x, y) {
return _this.map.checkPassable(x, y);
}
);
this.way = fw.way;
delete fw;
},
/**
* 检查是否已到达终点
*/
checkFinish: function () {
if (this.grid && this.map && this.grid == this.map.exit) {
TD.life -= this.damage;
TD.wave_damage += this.damage;
if (TD.life <= 0) {
TD.life = 0;
TD.stage.gameover();
} else {
this.pause();
this.del();
}
}
},
beAddToGrid: function (grid) {
this.grid = grid;
this.map = grid.map;
this.cx = grid.cx;
this.cy = grid.cy;
this.grid.scene.addElement(this);
},
/**
* 取得朝向
* 即下一个格子在当前格子的哪边
* 0:上;1:右;2:下;3:左
*/
getToward: function () {
if (!this.grid || !this.next_grid) return;
if (this.grid.my < this.next_grid.my) {
this.toward = 0;
} else if (this.grid.mx < this.next_grid.mx) {
this.toward = 1;
} else if (this.grid.my > this.next_grid.my) {
this.toward = 2;
} else if (this.grid.mx > this.next_grid.mx) {
this.toward = 3;
}
},
/**
* 取得要去的下一个格子
*/
getNextGrid: function () {
if (this.way.length == 0 ||
Math.random() < 0.1 // 有 1/10 的概率自动重新寻路
) {
this.findWay();
}
var next_grid = this.way.shift();
if (next_grid && !this.map.checkPassable(next_grid[0], next_grid[1])) {
this.findWay();
next_grid = this.way.shift();
}
if (!next_grid) {
return;
}
this.next_grid = this.map.getGrid(next_grid[0], next_grid[1]);
// this.getToward(); // 在这个版本中暂时没有用
},
/**
* 检查假如在地图 (x, y) 的位置修建建筑,是否会阻塞当前怪物
* @param mx {Number} 地图的 x 坐标
* @param my {Number} 地图的 y 坐标
* @return {Boolean}
*/
chkIfBlocked: function (mx, my) {
var _this = this,
fw = new TD.FindWay(
this.map.grid_x, this.map.grid_y,
this.grid.mx, this.grid.my,
this.map.exit.mx, this.map.exit.my,
function (x, y) {
return !(x == mx && y == my) &&
_this.map.checkPassable(x, y);
}
);
return fw.is_blocked;
},
/**
* 怪物前进的道路被阻塞(被建筑包围了)
*/
beBlocked: function () {
if (this.is_blocked) return;
this.is_blocked = true;
TD.log("monster be blocked!");
},
step: function () {
if (!this.is_valid || this.is_paused || !this.grid) return;
if (!this.next_grid) {
this.getNextGrid();
/**
* 如果依旧找不着下一步可去的格子,说明当前怪物被阻塞了
*/
if (!this.next_grid) {
this.beBlocked();
return;
}
}
if (this.cx == this.next_grid.cx && this.cy == this.next_grid.cy) {
this.arrive();
} else {
// 移动到 next grid
var dpx = this.next_grid.cx - this.cx,
dpy = this.next_grid.cy - this.cy,
sx = dpx < 0 ? -1 : 1,
sy = dpy < 0 ? -1 : 1,
speed = this.speed * TD.global_speed;
if (Math.abs(dpx) < speed && Math.abs(dpy) < speed) {
this.cx = this.next_grid.cx;
this.cy = this.next_grid.cy;
this._dx = speed - Math.abs(dpx);
this._dy = speed - Math.abs(dpy);
} else {
this.cx += dpx == 0 ? 0 : sx * (speed + this._dx);
this.cy += dpy == 0 ? 0 : sy * (speed + this._dy);
this._dx = 0;
this._dy = 0;
}
}
this.caculatePos();
},
onEnter: function () {
var msg,
balloontip = this.scene.panel.balloontip;
if (balloontip.el == this) {
balloontip.hide();
balloontip.el = null;
} else {
msg = TD._t("monster_info",
[this.life, this.shield, this.speed, this.damage]);
balloontip.msg(msg, this);
}
},
onOut: function () {
// if (this.scene.panel.balloontip.el == this) {
// this.scene.panel.balloontip.hide();
// }
}
};
/**
* @param cfg <object> 配置对象
* 至少需要包含以下项:
* {
* life: 怪物的生命值
* shield: 怪物的防御值
* speed: 怪物的速度
* }
*/
TD.Monster = function (id, cfg) {
cfg.on_events = ["enter", "out"];
var monster = new TD.Element(id, cfg);
TD.lang.mix(monster, monster_obj);
monster._init(cfg);
return monster;
};
/**
* 怪物死亡时的爆炸效果对象
*/
var explode_obj = {
_init: function (cfg) {
cfg = cfg || {};
var rgb = TD.lang.rgb2Arr(cfg.color);
this.cx = cfg.cx;
this.cy = cfg.cy;
this.r = cfg.r;
this.step_level = cfg.step_level;
this.render_level = cfg.render_level;
this.rgb_r = rgb[0];
this.rgb_g = rgb[1];
this.rgb_b = rgb[2];
this.rgb_a = 1;
this.wait = this.wait0 = TD.exp_fps * (cfg.time || 1);
cfg.scene.addElement(this);
},
step: function () {
if (!this.is_valid) return;
this.wait --;
this.r ++;
this.is_valid = this.wait > 0;
this.rgb_a = this.wait / this.wait0;
},
render: function () {
var ctx = TD.ctx;
ctx.fillStyle = "rgba(" + this.rgb_r + "," + this.rgb_g + ","
+ this.rgb_b + "," + this.rgb_a + ")";
ctx.beginPath();
ctx.arc(this.cx, this.cy, this.r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
}
};
/**
* @param cfg {Object} 配置对象
* {
* // 至少需要包含以下项:
* cx: 中心 x 坐标
* cy: 中心 y 坐标
* r: 半径
* color: RGB色彩,形如“#f98723”
* scene: Scene 对象
* step_level:
* render_level:
*
* // 以下项可选:
* time: 持续时间,默认为 1,单位大致为秒(根据渲染情况而定,不是很精确)
* }
*/
TD.Explode = function (id, cfg) {
// cfg.on_events = ["enter", "out"];
var explode = new TD.Element(id, cfg);
TD.lang.mix(explode, explode_obj);
explode._init(cfg);
return explode;
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-obj-monster.js | JavaScript | gpl2 | 9,649 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
/** 本文件定义了 Element 类,这个类是游戏中所有元素的基类,
* 包括地图、格子、怪物、建筑、子弹、气球提示等都基于这个类
*
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
/**
* Element 是游戏中所有可控制元素的基类
* @param id {String} 给这个元素一个唯一的不重复的 ID,如果不指定则随机生成
* @param cfg {Object} 元素的配置信息
*/
TD.Element = function (id, cfg) {
this.id = id || ("el-" + TD.lang.rndStr());
this.cfg = cfg || {};
this.is_valid = true;
this.is_visiable = typeof cfg.is_visiable != "undefined" ? cfg.is_visiable : true;
this.is_paused = false;
this.is_hover = false;
this.x = this.cfg.x || -1;
this.y = this.cfg.y || -1;
this.width = this.cfg.width || 0;
this.height = this.cfg.height || 0;
this.step_level = cfg.step_level || 1;
this.render_level = cfg.render_level;
this.on_events = cfg.on_events || [];
this._init();
};
TD.Element.prototype = {
_init: function () {
var _this = this,
i, en, len;
// 监听指定事件
for (i = 0, len = this.on_events.length; i < len; i ++) {
en = this.on_events[i];
switch (en) {
// 鼠标进入元素
case "enter":
this.on("enter", function () {
_this.onEnter();
});
break;
// 鼠标移出元素
case "out":
this.on("out", function () {
_this.onOut();
});
break;
// 鼠标在元素上,相当于 DOM 中的 onmouseover
case "hover":
this.on("hover", function () {
_this.onHover();
});
break;
// 鼠标点击了元素
case "click":
this.on("click", function () {
_this.onClick();
});
break;
}
}
this.caculatePos();
},
/**
* 重新计算元素的位置信息
*/
caculatePos: function () {
this.cx = this.x + this.width / 2; // 中心的位置
this.cy = this.y + this.height / 2;
this.x2 = this.x + this.width; // 右边界
this.y2 = this.y + this.height; // 下边界
},
start: function () {
this.is_paused = false;
},
pause: function () {
this.is_paused = true;
},
hide: function () {
this.is_visiable = false;
this.onOut();
},
show: function () {
this.is_visiable = true;
},
/**
* 删除本元素
*/
del: function () {
this.is_valid = false;
},
/**
* 绑定指定类型的事件
* @param evt_type {String} 事件类型
* @param f {Function} 处理方法
*/
on: function (evt_type, f) {
TD.eventManager.on(this, evt_type, f);
},
// 下面几个方法默认为空,实例中按需要重载
onEnter: TD.lang.nullFunc,
onOut: TD.lang.nullFunc,
onHover: TD.lang.nullFunc,
onClick: TD.lang.nullFunc,
step: TD.lang.nullFunc,
render: TD.lang.nullFunc,
/**
* 将当前 element 加入到场景 scene 中
* 在加入本 element 之前,先加入 pre_add_list 中的element
* @param scene
* @param step_level {Number}
* @param render_level {Number}
* @param pre_add_list {Array} Optional [element1, element2, ...]
*/
addToScene: function (scene, step_level, render_level, pre_add_list) {
this.scene = scene;
if (isNaN(step_level)) return;
this.step_level = step_level || this.step_level;
this.render_level = render_level || this.render_level;
if (pre_add_list) {
TD.lang.each(pre_add_list, function (obj) {
scene.addElement(obj, step_level, render_level);
});
}
scene.addElement(this, step_level, render_level);
}
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-element.js | JavaScript | gpl2 | 3,864 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
/**
* 事件管理器
*/
TD.eventManager = {
ex: -1, // 事件坐标 x
ey: -1, // 事件坐标 y
_registers: {}, // 注册监听事件的元素
// 目前支持的事件类型
ontypes: [
"enter", // 鼠标移入
"hover", // 鼠标在元素上,相当于 onmouseover
"out", // 鼠标移出
"click" // 鼠标点击
],
// 当前事件类型
current_type: "hover",
/**
* 根据事件坐标,判断事件是否在元素上
* @param el {Element} Element 元素
* @return {Boolean}
*/
isOn: function (el) {
return (this.ex != -1 &&
this.ey != -1 &&
this.ex > el.x &&
this.ex < el.x2 &&
this.ey > el.y &&
this.ey < el.y2);
},
/**
* 根据元素名、事件名,生成一个字符串标识,用于注册事件监听
* @param el {Element}
* @param evt_type {String}
* @return evt_name {String} 字符串标识
*/
_mkElEvtName: function (el, evt_type) {
return el.id + "::_evt_::" + evt_type;
},
/**
* 为元素注册事件监听
* 现在的实现比较简单,如果一个元素对某个事件多次注册监听,后面的监听将会覆盖前面的
*
* @param el {Element}
* @param evt_type {String}
* @param f {Function}
*/
on: function (el, evt_type, f) {
this._registers[this._mkElEvtName(el, evt_type)] = [el, evt_type, f];
},
/**
* 移除元素对指定事件的监听
* @param el {Element}
* @param evt_type {String}
*/
removeEventListener: function (el, evt_type) {
var en = this._mkElEvtName(el, evt_type);
delete this._registers[en];
},
/**
* 清除所有监听事件
*/
clear: function () {
delete this._registers;
this._registers = {};
//this.elements = [];
},
/**
* 主循环方法
*/
step: function () {
if (!this.current_type) return; // 没有事件被触发
var k, a, el, et, f, en, j,
_this = this,
ontypes_len = this.ontypes.length,
is_evt_on,
// reg_length = 0,
to_del_el = [];
//var m = TD.stage.current_act.current_scene.map;
//TD.log([m.is_hover, this.isOn(m)]);
// 遍历当前注册的事件
for (k in this._registers) {
// reg_length ++;
a = this._registers[k];
el = a[0]; // 事件对应的元素
et = a[1]; // 事件类型
f = a[2]; // 事件处理函数
if (!el.is_valid) {
to_del_el.push(el);
continue;
}
if (!el.is_visiable) continue; // 不可见元素不响应事件
is_evt_on = this.isOn(el); // 事件是否发生在元素上
if (this.current_type != "click") {
// enter / out / hover 事件
if (et == "hover" && el.is_hover && is_evt_on) {
// 普通的 hover
f();
this.current_type = "hover";
} else if (et == "enter" && !el.is_hover && is_evt_on) {
// enter 事件
el.is_hover = true;
f();
this.current_type = "enter";
} else if (et == "out" && el.is_hover && !is_evt_on) {
// out 事件
el.is_hover = false;
f();
this.current_type = "out";
// } else {
// 事件与当前元素无关
// continue;
}
} else {
// click 事件
if (is_evt_on && et == "click") f();
}
}
// 删除指定元素列表的事件
TD.lang.each(to_del_el, function(obj) {
for (j = 0; j < ontypes_len; j ++)
_this.removeEventListener(obj, _this.ontypes[j]);
});
// TD.log(reg_length);
this.current_type = "";
},
/**
* 鼠标在元素上
* @param ex {Number}
* @param ey {Number}
*/
hover: function (ex, ey) {
// 如果还有 click 事件未处理则退出,点击事件具有更高的优先级
if (this.current_type == "click") return;
this.current_type = "hover";
this.ex = ex;
this.ey = ey;
},
/**
* 点击事件
* @param ex {Number}
* @param ey {Number}
*/
click: function (ex, ey) {
this.current_type = "click";
this.ex = ex;
this.ey = ey;
}
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-event.js | JavaScript | gpl2 | 4,341 |
/*
* Copyright (c) 2011.
*
* Author: oldj <oldj.wu@gmail.com>
* Blog: http://oldj.net/
*
* Last Update: 2011/1/10 5:22:52
*/
/** 本文件定义了怪物默认属性及渲染方法
*/
// _TD.a.push begin
_TD.a.push(function (TD) {
/**
* 默认的怪物渲染方法
*/
function defaultMonsterRender() {
if (!this.is_valid || !this.grid) return;
var ctx = TD.ctx;
// 画一个圆代表怪物
ctx.strokeStyle = "#000";
ctx.lineWidth = 1;
ctx.fillStyle = this.color;
ctx.beginPath();
ctx.arc(this.cx, this.cy, this.r, 0, Math.PI * 2, true);
ctx.closePath();
ctx.fill();
ctx.stroke();
// 画怪物的生命值
if (TD.show_monster_life) {
var s = Math.floor(TD.grid_size / 4),
l = s * 2 - 2;
ctx.fillStyle = "#000";
ctx.beginPath();
ctx.fillRect(this.cx - s, this.cy - this.r - 6, s * 2, 4);
ctx.closePath();
ctx.fillStyle = "#f00";
ctx.beginPath();
ctx.fillRect(this.cx - s + 1, this.cy - this.r - 5, this.life * l / this.life0, 2);
ctx.closePath();
}
}
/**
* 取得怪物的默认属性
* @param monster_idx {Number} 怪物的类型
* @return attributes {Object}
*/
TD.getDefaultMonsterAttributes = function (monster_idx) {
var monster_attributes = [
{
// idx: 0
name: "monster 1",
desc: "最弱小的怪物",
speed: 3,
max_speed: 10,
life: 50,
damage: 1, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 0,
money: 5 // 消灭本怪物后可得多少金钱(可选)
},
{
// idx: 1
name: "monster 2",
desc: "稍强一些的小怪",
speed: 6,
max_speed: 20,
life: 50,
damage: 2, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 1
},
{
// idx: 2
name: "monster speed",
desc: "速度较快的小怪",
speed: 12,
max_speed: 30,
life: 50,
damage: 3, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 1
},
{
// idx: 3
name: "monster life",
desc: "生命值很强的小怪",
speed: 5,
max_speed: 10,
life: 500,
damage: 3, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 1
},
{
// idx: 4
name: "monster shield",
desc: "防御很强的小怪",
speed: 5,
max_speed: 10,
life: 50,
damage: 3, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 20
},
{
// idx: 5
name: "monster damage",
desc: "伤害值很大的小怪",
speed: 7,
max_speed: 14,
life: 50,
damage: 10, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 2
},
{
// idx: 6
name: "monster speed-life",
desc: "速度、生命都较高的怪物",
speed: 15,
max_speed: 30,
life: 100,
damage: 3, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 3
},
{
// idx: 7
name: "monster speed-2",
desc: "速度很快的怪物",
speed: 30,
max_speed: 40,
life: 30,
damage: 4, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 1
},
{
// idx: 8
name: "monster shield-life",
desc: "防御很强、生命值很高的怪物",
speed: 3,
max_speed: 10,
life: 300,
damage: 5, // 到达终点后会带来多少点伤害(1 ~ 10)
shield: 15
}
];
if (typeof monster_idx == "undefined") {
// 如果只传了一个参数,则只返回共定义了多少种怪物(供 td.js 中使用)
return monster_attributes.length;
}
var attr = monster_attributes[monster_idx] || monster_attributes[0],
attr2 = {};
TD.lang.mix(attr2, attr);
if (!attr2.render) {
// 如果没有指定当前怪物的渲染方法
attr2.render = defaultMonsterRender
}
return attr2;
};
/**
* 生成一个怪物列表,
* 包含 n 个怪物
* 怪物类型在 range 中指定,如未指定,则为随机
*/
TD.makeMonsters = function (n, range) {
var a = [], count = 0, i, c, d, r, l = TD.monster_type_count;
if (!range) {
range = [];
for (i = 0; i < l; i ++) {
range.push(i);
}
}
while (count < n) {
d = n - count;
c = Math.min(
Math.floor(Math.random() * d) + 1,
3 // 同一类型的怪物一次最多出现 3 个,防止某一波中怪出大量高防御或高速度的怪
);
r = Math.floor(Math.random() * l);
a.push([c, range[r]]);
count += c;
}
return a;
};
}); // _TD.a.push end
| zzy-code-test | html5/tower_defense/js/td-cfg-monsters.js | JavaScript | gpl2 | 4,630 |
/**
* c.css
*
* @save-up: [../js/td.js, ../td.html]
*
* last update: 2010-11-22 10:50:50
*/
html, body {
margin: 0;
padding: 0;
font-size: 12px;
line-height: 20px;
font-family: Verdana, "Times New Roman", serif;
background: #1A74BA;
}
h1 {
padding: 0;
margin: 0;
line-height: 48px;
font-size: 18px;
font-weight: bold;
font-family: Verdana, "Times New Roman", serif;
letter-spacing: 0.12em;
}
#wrapper {
margin: 0 auto;
}
#td-wrapper {
padding: 8px 24px 60px 24px;
background: #E0F4FC;
}
#td-board {
display: none;
font-size: 16px;
}
#td-board canvas#td-canvas {
position: relative;
background: #fff;
border: solid 1px #cdf;
}
#td-loading {
font-size: 18px;
line-height: 48px;
padding: 60px 0 120px 0;
font-style: italic;
}
#about {
color: #fff;
padding: 8px 24px;
}
#about a {
color: #fff;
}
| zzy-code-test | html5/tower_defense/css/c.css | CSS | gpl2 | 883 |
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Cache-Control" content="no-cache"/>
<meta http-equiv="Expires" content="Thu, 01 Jan 1970 00:00:01 GMT"/>
<meta http-equiv="Expires" content="0"/>
<title>HTML5 Tower Defense</title>
<link href="css/c.css" rel="stylesheet" type="text/css" media="screen"/>
<style type="text/css">
</style>
</head>
<body id="tower-defense">
<div id="wrapper">
<div id="td-wrapper">
<h1>HTML5 塔防游戏</h1>
<div id="td-loading">加载中...</div>
<div id="td-board">
<canvas id="td-canvas">抱歉,您的浏览器不支持 HTML 5 Canvas 标签,请使用 IE9 / Chrome / Opera 等浏览器浏览本页以获得最佳效果。</canvas>
</div>
</div>
<div id="about">
<a href="http://oldj.net/article/html5-tower-defense/" target="_blank">关于</a> |
<a href="https://github.com/oldj/html5-tower-defense" target="_blank">源码</a> |
<a href="http://oldj.net/">oldj.net</a> © 2010-2011
</div>
</div>
<script type="text/javascript" src="js/td.js"></script>
<script type="text/javascript" src="js/td-lang.js"></script>
<script type="text/javascript" src="js/td-event.js"></script>
<script type="text/javascript" src="js/td-stage.js"></script>
<script type="text/javascript" src="js/td-element.js"></script>
<script type="text/javascript" src="js/td-obj-map.js"></script>
<script type="text/javascript" src="js/td-obj-grid.js"></script>
<script type="text/javascript" src="js/td-obj-building.js"></script>
<script type="text/javascript" src="js/td-obj-monster.js"></script>
<script type="text/javascript" src="js/td-obj-panel.js"></script>
<script type="text/javascript" src="js/td-data-stage-1.js"></script>
<script type="text/javascript" src="js/td-cfg-buildings.js"></script>
<script type="text/javascript" src="js/td-cfg-monsters.js"></script>
<script type="text/javascript" src="js/td-render-buildings.js"></script>
<script type="text/javascript" src="js/td-msg.js"></script>
<script type="text/javascript" src="js/td-walk.js"></script>
<!--<script type="text/javascript" src="td-pkg-min.js?fmts=1"></script>-->
<script type="text/javascript">
window.onload = function () {
_TD.init("td-board", true);
document.getElementById("td-loading").style.display = "none";
document.getElementById("td-board").style.display = "block";
};
</script>
</body>
</html>
| zzy-code-test | html5/tower_defense/index.html | HTML | gpl2 | 2,603 |
window.onload = function () {
C = Math.cos; // cache Math objects
S = Math.sin;
U = 0;
w = window;
j = document;
d = j.getElementById("c");
c = d.getContext("2d");
W = d.width = w.innerWidth;
H = d.height = w.innerHeight;
c.fillRect(0, 0, W, H); // resize <canvas> and draw black rect (default)
c.globalCompositeOperation = "lighter"; // switch to additive color application
c.lineWidth = 0.2;
c.lineCap = "round";
var bool = 0,
t = 0; // theta
d.onmousemove = function (e) {
if(window.T) {
if(D==9) { D=Math.random()*15; f(1); }
clearTimeout(T);
}
X = e.pageX; // grab mouse pixel coords
Y = e.pageY;
a=0; // previous coord.x
b=0; // previous coord.y
A = X, // original coord.x
B = Y; // original coord.y
R=(e.pageX/W * 999>>0)/999;
r=(e.pageY/H * 999>>0)/999;
U=e.pageX/H * 360 >>0;
D=9;
g = 360 * Math.PI / 180;
T = setInterval(f = function (e) { // start looping spectrum
c.save();
c.globalCompositeOperation = "source-over"; // switch to additive color application
if(e!=1) {
c.fillStyle = "rgba(0,0,0,0.02)";
c.fillRect(0, 0, W, H); // resize <canvas> and draw black rect (default)
}
c.restore();
i = 25; while(i --) {
c.beginPath();
if(D > 450 || bool) { // decrease diameter
if(!bool) { // has hit maximum
bool = 1;
}
if(D < 0.1) { // has hit minimum
bool = 0;
}
t -= g; // decrease theta
D -= 0.1; // decrease size
}
if(!bool) {
t += g; // increase theta
D += 0.1; // increase size
}
q = (R / r - 1) * t; // create hypotrochoid from current mouse position, and setup variables (see: http://en.wikipedia.org/wiki/Hypotrochoid)
x = (R - r) * C(t) + D * C(q) + (A + (X - A) * (i / 25)) + (r - R); // center on xy coords
y = (R - r) * S(t) - D * S(q) + (B + (Y - B) * (i / 25));
if (a) { // draw once two points are set
c.moveTo(a, b);
c.lineTo(x, y)
}
c.strokeStyle = "hsla(" + (U % 360) + ",100%,50%,0.75)"; // draw rainbow hypotrochoid
c.stroke();
a = x; // set previous coord.x
b = y; // set previous coord.y
}
U -= 0.5; // increment hue
A = X; // set original coord.x
B = Y; // set original coord.y
}, 16);
}
j.onkeydown = function(e) { a=b=0; R += 0.05 }
d.onmousemove({pageX:300, pageY:290})
}
| zzy-code-test | html5/star/star.js | JavaScript | gpl2 | 2,322 |
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<title>star</title>
<script type="text/javascript" src=star.js>
</script>
</head>
<body style="margin:0px;padding:0px;width:100%;height:100%;overflow:hidden;">
<canvas id="c"></canvas>
</body>
</html>
| zzy-code-test | html5/star/index.html | HTML | gpl2 | 293 |
/*
* lightgl.js
* http://github.com/evanw/lightgl.js/
*
* Copyright 2011 Evan Wallace
* Released under the MIT license
*/
(function(){
function u(a){
window.handleError&&window.handleError(a);
throw a;
};
function x(a){
return new Vector((a&1)*2-1,(a&2)-1,(a&4)/2-1)
};
window.onload=function(){
function a(f){
mouseX=f.pageX;mouseY=f.pageY;
for(f=gl.canvas;f;f=f.offsetParent){
mouseX-=f.offsetLeft;mouseY-=f.offsetTop
};
deltaMouseX=mouseX-h;deltaMouseY=mouseY-i;h=mouseX;i=mouseY
};
function b(f){switch(f){case 8:return"BACKSPACE";case 9:return"TAB";case 13:return"ENTER";
case 16:
return"SHIFT";
case 27:
return"ESCAPE";
case 32:
return"SPACE";
case 37:
return"LEFT";
case 38:
return"UP";
case 39:
return"RIGHT";
case 40:
return"DOWN"
};
return f>=65&&f<=90?String.fromCharCode(f):f
};
function c(){
var f=new Date;
if(gl.autoDraw){
window.update&&window.update((f-v)/1E3);
window.draw&&window.draw();s(c)
};
else
setTimeout(c,100);
v=f
};
var d=document.createElement("canvas");
d.width=800;d.height=600;window.gl=null;
try{
gl=d.getContext("webgl")
};
catch(e){
};
try{
gl=gl||d.getContext("experimental-webgl")
};
catch(g){
};
gl||u("WebGL not supported");
window.mouseX=window.mouseY=window.deltaMouseX=window.deltaMouseY=0;
window.mouseDragging=false;
var h=0,i=0;
document.onmousedown=function(f){
a(f);
mouseDragging=true;
window.mousePressed&&window.mousePressed()
};
document.onmousemove=function(f){
a(f);
if(!mouseDragging&&window.mouseMoved)
window.mouseMoved();
else
mouseDragging&&window.mouseDragged&&window.mouseDragged()
};
document.onmouseup=function(f){
a(f);
mouseDragging=false;
window.mouseReleased&&window.mouseReleased()
};
window.key=null;
window.keys={
};
document.onkeydown=function(f){
if(!f.altKey&&!f.ctrlKey&&!f.metaKey){
key=b(f.keyCode);keys[key]=true;
window.keyPressed&&window.keyPressed()
};
};
document.onkeyup=function(f){
if(!f.altKey&&!f.ctrlKey&&!f.metaKey){
key=b(f.keyCode);
keys[key]=false;
window.keyReleased&&window.keyReleased()
};
};
gl.MODELVIEW=305397761;
gl.PROJECTION=305397762;
gl.modelviewMatrix=new Matrix;gl.projectionMatrix=new Matrix;
var j=[],q=[],k,l;
gl.matrixMode=function(f){
switch(f){
case gl.MODELVIEW:k="modelviewMatrix";l=j;break;
case gl.PROJECTION:k="projectionMatrix";l=q;break;
default:u("invalid matrix mode "+f)
};
};
gl.loadIdentity=function(){
gl[k].m=(new Matrix).m
};
gl.loadMatrix=function(f){
gl[k].m=f.m.slice()
};
gl.multMatrix=function(f){
gl[k].m=gl[k].multiply(f).m
};
gl.perspective=function(f,n,o,p){
gl.multMatrix(Matrix.perspective(f,n,o,p))
};
gl.frustum=function(f,n,o,p,r,m){
gl.multMatrix(Matrix.frustum(f,n,o,p,r,m))
};
gl.ortho=function(f,n,o,p,r,m){
gl.multMatrix(Matrix.ortho(f,n,o,p,r,m))
};
gl.scale=function(f,n,o){
gl.multMatrix(Matrix.scale(f,n,o))
};
gl.translate=function(f,n,o){
gl.multMatrix(Matrix.translate(f,
n,o))
};
gl.rotate=function(f,n,o,p){
gl.multMatrix(Matrix.rotate(f,n,o,p))
};
gl.lookAt=function(f,n,o,p,r,m,z,A,B){
gl.multMatrix(Matrix.lookAt(f,n,o,p,r,m,z,A,B))
};
gl.pushMatrix=function(){
l.push(gl[k].m.slice())
};
gl.popMatrix=function(){
gl[k].m=l.pop()
};
gl.project=function(f,n,o,p,r,m){
p=p||gl.modelviewMatrix;r=r||gl.projectionMatrix;m=m||gl.getParameter(gl.VIEWPORT);f=r.transformPoint(p.transformPoint(new Vector(f,n,o)));return new Vector(m[0]+m[2]*(f.x*0.5+0.5),m[1]+m[3]*(f.y*0.5+0.5),f.z*0.5+0.5)
};
gl.unProject=function(f,n,o,p,r,m){
p=p||gl.modelviewMatrix;r=r||gl.projectionMatrix;m=m||gl.getParameter(gl.VIEWPORT);f=new Vector((f-m[0])/m[2]*2-1,(n-m[1])/m[3]*2-1,o*2-1);return r.multiply(p).inverse().transformPoint(f)
};
gl.matrixMode(gl.MODELVIEW);gl.autoDraw=true;var s=window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||function(f){
setTimeout(f,1E3/60)
};
,v=new Date;window.setup&&window.setup();c()
};
Matrix=function(){
this.m=Array.prototype.concat.apply([],arguments);if(!this.m.length)this.m=
[1,0,0,0,0,1,0,0,0,0,1,0,0,0,0,1]
};
Matrix.prototype.inverse=function(){
var a=this.m,b=new Matrix(a[5]*a[10]*a[15]-a[5]*a[14]*a[11]-a[6]*a[9]*a[15]+a[6]*a[13]*a[11]+a[7]*a[9]*a[14]-a[7]*a[13]*a[10],-a[1]*a[10]*a[15]+a[1]*a[14]*a[11]+a[2]*a[9]*a[15]-a[2]*a[13]*a[11]-a[3]*a[9]*a[14]+a[3]*a[13]*a[10],a[1]*a[6]*a[15]-a[1]*a[14]*a[7]-a[2]*a[5]*a[15]+a[2]*a[13]*a[7]+a[3]*a[5]*a[14]-a[3]*a[13]*a[6],-a[1]*a[6]*a[11]+a[1]*a[10]*a[7]+a[2]*a[5]*a[11]-a[2]*a[9]*a[7]-a[3]*a[5]*a[10]+a[3]*a[9]*a[6],-a[4]*a[10]*
a[15]+a[4]*a[14]*a[11]+a[6]*a[8]*a[15]-a[6]*a[12]*a[11]-a[7]*a[8]*a[14]+a[7]*a[12]*a[10],a[0]*a[10]*a[15]-a[0]*a[14]*a[11]-a[2]*a[8]*a[15]+a[2]*a[12]*a[11]+a[3]*a[8]*a[14]-a[3]*a[12]*a[10],-a[0]*a[6]*a[15]+a[0]*a[14]*a[7]+a[2]*a[4]*a[15]-a[2]*a[12]*a[7]-a[3]*a[4]*a[14]+a[3]*a[12]*a[6],a[0]*a[6]*a[11]-a[0]*a[10]*a[7]-a[2]*a[4]*a[11]+a[2]*a[8]*a[7]+a[3]*a[4]*a[10]-a[3]*a[8]*a[6],a[4]*a[9]*a[15]-a[4]*a[13]*a[11]-a[5]*a[8]*a[15]+a[5]*a[12]*a[11]+a[7]*a[8]*a[13]-a[7]*a[12]*a[9],-a[0]*a[9]*a[15]+a[0]*a[13]*
a[11]+a[1]*a[8]*a[15]-a[1]*a[12]*a[11]-a[3]*a[8]*a[13]+a[3]*a[12]*a[9],a[0]*a[5]*a[15]-a[0]*a[13]*a[7]-a[1]*a[4]*a[15]+a[1]*a[12]*a[7]+a[3]*a[4]*a[13]-a[3]*a[12]*a[5],-a[0]*a[5]*a[11]+a[0]*a[9]*a[7]+a[1]*a[4]*a[11]-a[1]*a[8]*a[7]-a[3]*a[4]*a[9]+a[3]*a[8]*a[5],-a[4]*a[9]*a[14]+a[4]*a[13]*a[10]+a[5]*a[8]*a[14]-a[5]*a[12]*a[10]-a[6]*a[8]*a[13]+a[6]*a[12]*a[9],a[0]*a[9]*a[14]-a[0]*a[13]*a[10]-a[1]*a[8]*a[14]+a[1]*a[12]*a[10]+a[2]*a[8]*a[13]-a[2]*a[12]*a[9],-a[0]*a[5]*a[14]+a[0]*a[13]*a[6]+a[1]*a[4]*a[14]-
a[1]*a[12]*a[6]-a[2]*a[4]*a[13]+a[2]*a[12]*a[5],a[0]*a[5]*a[10]-a[0]*a[9]*a[6]-a[1]*a[4]*a[10]+a[1]*a[8]*a[6]+a[2]*a[4]*a[9]-a[2]*a[8]*a[5]);
a=a[0]*b.m[0]+a[1]*b.m[4]+a[2]*b.m[8]+a[3]*b.m[12];
if(a==0)
return new Matrix;
for(var c=0;c<16;c++)
b.m[c]/=a;
return b
};
Matrix.prototype.transpose=function(){
var a=this.m;return new Matrix(a[0],a[4],a[8],a[12],a[1],a[5],a[9],a[13],a[2],a[6],a[10],a[14],a[3],a[7],a[11],a[15])
};
Matrix.prototype.multiply=function(a){
var b=this.m;a=a.m;return new Matrix(b[0]*a[0]+
b[1]*a[4]+b[2]*a[8]+b[3]*a[12],b[0]*a[1]+b[1]*a[5]+b[2]*a[9]+b[3]*a[13],b[0]*a[2]+b[1]*a[6]+b[2]*a[10]+b[3]*a[14],b[0]*a[3]+b[1]*a[7]+b[2]*a[11]+b[3]*a[15],b[4]*a[0]+b[5]*a[4]+b[6]*a[8]+b[7]*a[12],b[4]*a[1]+b[5]*a[5]+b[6]*a[9]+b[7]*a[13],b[4]*a[2]+b[5]*a[6]+b[6]*a[10]+b[7]*a[14],b[4]*a[3]+b[5]*a[7]+b[6]*a[11]+b[7]*a[15],b[8]*a[0]+b[9]*a[4]+b[10]*a[8]+b[11]*a[12],b[8]*a[1]+b[9]*a[5]+b[10]*a[9]+b[11]*a[13],b[8]*a[2]+b[9]*a[6]+b[10]*a[10]+b[11]*a[14],b[8]*a[3]+b[9]*a[7]+b[10]*a[11]+b[11]*a[15],b[12]*
a[0]+b[13]*a[4]+b[14]*a[8]+b[15]*a[12],b[12]*a[1]+b[13]*a[5]+b[14]*a[9]+b[15]*a[13],b[12]*a[2]+b[13]*a[6]+b[14]*a[10]+b[15]*a[14],b[12]*a[3]+b[13]*a[7]+b[14]*a[11]+b[15]*a[15])
};
Matrix.prototype.transformPoint=function(a){
var b=this.m;return(new Vector(b[0]*a.x+b[1]*a.y+b[2]*a.z+b[3],b[4]*a.x+b[5]*a.y+b[6]*a.z+b[7],b[8]*a.x+b[9]*a.y+b[10]*a.z+b[11])).divide(b[12]*a.x+b[13]*a.y+b[14]*a.z+b[15])
};
Matrix.prototype.transformVector=function(a){
var b=this.m;return new Vector(b[0]*a.x+b[1]*a.y+b[2]*a.z,
b[4]*a.x+b[5]*a.y+b[6]*a.z,b[8]*a.x+b[9]*a.y+b[10]*a.z)
};
Matrix.perspective=function(a,b,c,d){
a=Math.tan(a*Math.PI/360)*c;b=a*b;return Matrix.frustum(-b,b,-a,a,c,d)
};
Matrix.frustum=function(a,b,c,d,e,g){
return new Matrix(2*e/(b-a),0,(b+a)/(b-a),0,0,2*e/(d-c),(d+c)/(d-c),0,0,0,-(g+e)/(g-e),-2*g*e/(g-e),0,0,-1,0)
};
Matrix.ortho=function(a,b,c,d,e,g){
return new Matrix(2/(b-a),0,0,(b+a)/(b-a),0,2/(d-c),0,(d+c)/(d-c),0,0,-2/(g-e),(g+e)/(g-e),0,0,0,1)
};
Matrix.scale=function(a,b,c){
return new Matrix(a,0,
0,0,0,b,0,0,0,0,c,0,0,0,0,1)
};
Matrix.translate=function(a,b,c){
return new Matrix(1,0,0,a,0,1,0,b,0,0,1,c,0,0,0,1)
};
Matrix.rotate=function(a,b,c,d){
if(a&&(b||c||d)){
var e=Math.sqrt(b*b+c*c+d*d);a*=Math.PI/180;b/=e;c/=e;d/=e;e=Math.cos(a);a=Math.sin(a);var g=1-e;return new Matrix(b*b*g+e,b*c*g-d*a,b*d*g+c*a,0,c*b*g+d*a,c*c*g+e,c*d*g-b*a,0,d*b*g-c*a,d*c*g+b*a,d*d*g+e,0,0,0,0,1)
};
else return new Matrix
};
Matrix.lookAt=function(a,b,c,d,e,g,h,i,j){
a=new Vector(a,b,c);d=new Vector(d,e,g);i=new Vector(h,i,
j);h=a.subtract(d).unit();i=i.cross(h).unit();j=h.cross(i).unit();return new Matrix(i.x,i.y,i.z,-i.dot(a),j.x,j.y,j.z,-j.dot(a),h.x,h.y,h.z,-h.dot(a),0,0,0,1)
};
Indexer=function(){
this.unique=[];this.indices=[];this.map={
};
};
Indexer.prototype.add=function(a){
var b=JSON.stringify(a);if(!(b in this.map)){
this.map[b]=this.unique.length;this.unique.push(a)
};
return this.map[b]
};
Buffer=function(a,b){
this.buffer=null;this.target=a;this.type=b;this.data=[]
};
Buffer.prototype.compile=function(a){
for(var b=[],
c=0;c<this.data.length;c+=1E4)b=Array.prototype.concat.apply(b,this.data.slice(c,c+1E4));if(b.length){
this.buffer=this.buffer||gl.createBuffer();this.buffer.length=b.length;this.buffer.spacing=b.length/this.data.length;gl.bindBuffer(this.target,this.buffer);gl.bufferData(this.target,new this.type(b),a||gl.STATIC_DRAW)
};
};
Mesh=function(a){
a=a||{
};
this.vertexBuffers={
};
this.indexBuffers={
};
this.addVertexBuffer("vertices","gl_Vertex");if(!("coords"in a)||a.coords)this.addVertexBuffer("coords","gl_TexCoord");
if(!("normals"in a)||a.normals)this.addVertexBuffer("normals","gl_Normal");this.addIndexBuffer("triangles");this.addIndexBuffer("lines")
};
Mesh.prototype.addVertexBuffer=function(a,b){
(this.vertexBuffers[b]=new Buffer(gl.ARRAY_BUFFER,Float32Array)).name=a;this[a]=[]
};
Mesh.prototype.addIndexBuffer=function(a){
this.indexBuffers[a]=new Buffer(gl.ELEMENT_ARRAY_BUFFER,Int16Array);this[a]=[]
};
Mesh.prototype.compile=function(){
for(var a in this.vertexBuffers){
var b=this.vertexBuffers[a];b.data=this[b.name];
b.compile()
};
for(var c in this.indexBuffers){
b=this.indexBuffers[c];b.data=this[c];b.compile()
};
};
Mesh.prototype.transform=function(a){
this.vertices=this.vertices.map(function(c){
return a.transformPoint(Vector.fromArray(c)).toArray()
};
);if(this.normals){
var b=a.inverse().transpose();this.normals=this.normals.map(function(c){
return b.transformVector(Vector.fromArray(c)).unit().toArray()
};
)
};
this.compile();return this
};
Mesh.prototype.computeNormals=function(){
this.normals||this.addVertexBuffer("normals","gl_Normal");
for(var a=0;a<this.vertices.length;a++)this.normals[a]=new Vector;
for(a=0;a<this.triangles.length;a++){
var b=this.triangles[a],c=Vector.fromArray(this.vertices[b[0]]),d=Vector.fromArray(this.vertices[b[1]]),e=Vector.fromArray(this.vertices[b[2]]);
c=d.subtract(c).cross(e.subtract(c)).unit();
this.normals[b[0]]=this.normals[b[0]].add(c);
this.normals[b[1]]=this.normals[b[1]].add(c);this.normals[b[2]]=this.normals[b[2]].add(c)
};
for(a=0;a<this.vertices.length;a++)this.normals[a]=this.normals[a].unit().toArray();
this.compile();return this
};
Mesh.prototype.computeWireframe=function(){
for(var a=new Indexer,b=0;b<this.triangles.length;b++)for(var c=this.triangles[b],d=0;d<c.length;d++){
var e=c[d],g=c[(d+1)%c.length];a.add([Math.min(e,g),Math.max(e,g)])
};
this.lines=a.unique;this.compile();return this
};
Mesh.prototype.getAABB=function(){
var a={min:new Vector(Number.MAX_VALUE,Number.MAX_VALUE,Number.MAX_VALUE)
};
a.max=a.min.negative();for(var b=0;b<this.vertices.length;b++){
var c=Vector.fromArray(this.vertices[b]);
a.min=Vector.min(a.min,c);a.max=Vector.max(a.max,c)
};
return a
};
Mesh.prototype.getBoundingSphere=function(){
var a=this.getAABB();a={center:a.min.add(a.max).divide(2),radius:0
};
for(var b=0;b<this.vertices.length;b++)a.radius=Math.max(a.radius,Vector.fromArray(this.vertices[b]).subtract(a.center).length());return a
};
Mesh.plane=function(a,b,c){
c=new Mesh(c);a=a||1;b=b||1;for(var d=0;d<=b;d++)for(var e=d/b,g=0;g<=a;g++){
var h=g/a;c.vertices.push([2*h-1,2*e-1,0]);c.coords&&c.coords.push([h,e]);c.normals&&
c.normals.push([0,0,1]);if(g<a&&d<b){
h=g+d*(a+1);c.triangles.push([h,h+1,h+a+1]);c.triangles.push([h+a+1,h+1,h+a+2])
};
};
c.compile();return c
};
var y=[[0,4,2,6,-1,0,0],[1,3,5,7,+1,0,0],[0,1,4,5,0,-1,0],[2,6,3,7,0,+1,0],[0,2,1,3,0,0,-1],[4,5,6,7,0,0,+1]];Mesh.cube=function(a){
a=new Mesh(a);for(var b=0;b<y.length;b++){
for(var c=y[b],d=b*4,e=0;e<4;e++){
a.vertices.push(x(c[e]).toArray());a.coords&&a.coords.push([e&1,(e&2)/2]);a.normals&&a.normals.push([c[4],c[5],c[6]])
};
a.triangles.push([d,d+1,d+2]);a.triangles.push([d+
2,d+1,d+3])
};
a.compile();return a
};
Mesh.sphere=function(a,b){
var c=new Mesh(b),d=new Indexer;a=a||6;for(var e=0;e<8;e++)for(var g=x(e),h=g.x*g.y*g.z>0,i=[],j=0;j<=a;j++){
for(var q=0;j+q<=a;q++){
var k=j/a,l=q/a,s=(a-j-q)/a;l={vertex:(new Vector(k+(k-k*k)/2,l+(l-l*l)/2,s+(s-s*s)/2)).unit().multiply(g).toArray()
};
if(c.coords)l.coord=g.y>0?[1-k,s]:[s,1-k];i.push(d.add(l))
};
if(j>0)for(q=0;j+q<=a;q++){
k=(j-1)*(a+1)+(j-1-(j-1)*(j-1))/2+q;l=j*(a+1)+(j-j*j)/2+q;c.triangles.push(h?[i[k],i[l],i[k+1]]:[i[k],i[k+
1],i[l]]);j+q<a&&c.triangles.push(h?[i[l],i[l+1],i[k+1]]:[i[l],i[k+1],i[l+1]])
};
};
c.vertices=d.unique.map(function(v){
return v.vertex
};
);if(c.coords)c.coords=d.unique.map(function(v){
return v.coord
};
);if(c.normals)c.normals=c.vertices;c.compile();return c
};
Mesh.load=function(a,b){
b=b||{
};
if(!a.coords)b.coords=false;if(!a.normals)b.normals=false;var c=new Mesh(b);c.vertices=a.vertices;if(c.coords)c.coords=a.coords;if(c.normals)c.normals=a.normals;c.triangles=a.triangles||[];c.lines=a.lines||[];c.compile();
return c
};
HitTest=function(a,b,c){
this.t=arguments.length?a:Number.MAX_VALUE;this.hit=b;this.normal=c
};
HitTest.prototype.mergeWith=function(a){
if(a.t>0&&a.t<this.t){
this.t=a.t;this.hit=a.hit;this.normal=a.normal
};
};
Raytracer=function(){
var a=gl.getParameter(gl.VIEWPORT),b=gl.modelviewMatrix.m,c=new Vector(b[0],b[4],b[8]),d=new Vector(b[1],b[5],b[9]),e=new Vector(b[2],b[6],b[10]);b=new Vector(b[3],b[7],b[11]);this.eye=new Vector(-b.dot(c),-b.dot(d),-b.dot(e));c=a[0];d=c+a[2];e=a[1];b=e+a[3];this.ray00=
gl.unProject(c,e,1).subtract(this.eye);this.ray10=gl.unProject(d,e,1).subtract(this.eye);this.ray01=gl.unProject(c,b,1).subtract(this.eye);this.ray11=gl.unProject(d,b,1).subtract(this.eye);this.viewport=a
};
Raytracer.prototype.getRayForPixel=function(a,b){
a=(a-this.viewport[0])/this.viewport[2];b=1-(b-this.viewport[1])/this.viewport[3];var c=Vector.lerp(this.ray00,this.ray10,a),d=Vector.lerp(this.ray01,this.ray11,a);return Vector.lerp(c,d,b).unit()
};
Raytracer.hitTestBox=function(a,b,c,d){
var e=c.subtract(a).divide(b),
g=d.subtract(a).divide(b),h=Vector.min(e,g);e=Vector.max(e,g);h=h.max();e=e.min();if(h>0&&h<e){
a=a.add(b.multiply(h));c=c.add(1.0E-6);d=d.subtract(1.0E-6);return new HitTest(h,a,new Vector((a.x>d.x)-(a.x<c.x),(a.y>d.y)-(a.y<c.y),(a.z>d.z)-(a.z<c.z)))
};
return null
};
Raytracer.hitTestSphere=function(a,b,c,d){
var e=a.subtract(c),g=b.dot(b),h=2*b.dot(e);e=e.dot(e)-d*d;e=h*h-4*g*e;if(e>0){
g=(-h-Math.sqrt(e))/(2*g);a=a.add(b.multiply(g));return new HitTest(g,a,a.subtract(c).divide(d))
};
return null
};
Raytracer.hitTestTriangle=
function(a,b,c,d,e){
var g=d.subtract(c),h=e.subtract(c);e=g.cross(h).unit();d=e.dot(c.subtract(a)).divide(e.dot(b));if(d>0){
a=a.add(b.multiply(d));var i=a.subtract(c);c=h.dot(h);b=h.dot(g);h=h.dot(i);var j=g.dot(g);g=g.dot(i);i=c*j-b*b;j=(j*h-b*g)/i;g=(c*g-b*h)/i;if(j>=0&&g>=0&&j+g<=1)return new HitTest(d,a,e)
};
return null
};
Shader=function(a,b){
function c(h,i,j){
for(;(result=h.exec(i))!=null;)j(result)
};
function d(h,i){
var j=/^((\s*\/\/.*\n|\s*#extension.*\n)+)[^]*$/.exec(i);i=j?j[1]+h+i.substr(j[1].length):
h+i;c(/\bgl_\w+\b/g,h,function(q){
i=i.replace(RegExp(q,"g"),"_"+q)
};
);return i
};
function e(h,i){
var j=gl.createShader(h);gl.shaderSource(j,i);gl.compileShader(j);gl.getShaderParameter(j,gl.COMPILE_STATUS)||u("compile error: "+gl.getShaderInfoLog(j));return j
};
a=d("attribute vec3 gl_Vertex;attribute vec2 gl_TexCoord;attribute vec3 gl_Normal;uniform mat4 gl_ModelViewMatrix;uniform mat4 gl_ProjectionMatrix;uniform mat4 gl_ModelViewProjectionMatrix;",
a);b=d("precision highp float;uniform mat4 gl_ModelViewMatrix;uniform mat4 gl_ProjectionMatrix;uniform mat4 gl_ModelViewProjectionMatrix;",b);this.program=gl.createProgram();gl.attachShader(this.program,e(gl.VERTEX_SHADER,a));gl.attachShader(this.program,e(gl.FRAGMENT_SHADER,b));gl.linkProgram(this.program);gl.getProgramParameter(this.program,gl.LINK_STATUS)||u("link error: "+gl.getProgramInfoLog(this.program));this.attributes={
};
var g={
};
c(/uniform\s+sampler(1D|2D|3D|Cube)\s+(\w+)\s*;/g,
a+b,function(h){
g[h[2]]=1
};
);this.isSampler=g;this.needsMVP=(a+b).indexOf("gl_ModelViewProjectionMatrix")!=-1
};
Shader.prototype.uniforms=function(a){
gl.useProgram(this.program);for(var b in a){
var c=gl.getUniformLocation(this.program,b);if(c){
var d=a[b];if(d instanceof Vector)d=[d.x,d.y,d.z];else if(d instanceof Matrix)d=d.m;if(Object.prototype.toString.call(d)=="[object Array]")switch(d.length){
case 1:gl.uniform1fv(c,new Float32Array(d));break;case 2:gl.uniform2fv(c,new Float32Array(d));break;case 3:gl.uniform3fv(c,
new Float32Array(d));break;case 4:gl.uniform4fv(c,new Float32Array(d));break;case 9:gl.uniformMatrix3fv(c,false,new Float32Array([d[0],d[3],d[6],d[1],d[4],d[7],d[2],d[5],d[8]]));break;case 16:gl.uniformMatrix4fv(c,false,new Float32Array([d[0],d[4],d[8],d[12],d[1],d[5],d[9],d[13],d[2],d[6],d[10],d[14],d[3],d[7],d[11],d[15]]));break;default:u("don't know how to load uniform \""+b+'" of length '+d.length)
};
else Object.prototype.toString.call(d)=="[object Number]"?(this.isSampler[b]?gl.uniform1i:gl.uniform1f).call(gl,
c,d):u('attempted to set uniform "'+b+'" to invalid value '+d)
};
};
return this
};
Shader.prototype.draw=function(a,b){
this.drawBuffers(a.vertexBuffers,a.indexBuffers[b==gl.LINES?"lines":"triangles"],b||gl.TRIANGLES)
};
Shader.prototype.drawBuffers=function(a,b,c){
this.uniforms({_gl_ModelViewMatrix:gl.modelviewMatrix,_gl_ProjectionMatrix:gl.projectionMatrix
};
);
this.needsMVP&&this.uniforms({_gl_ModelViewProjectionMatrix:gl.projectionMatrix.multiply(gl.modelviewMatrix)
};
);
for(var d in a){
var e=a[d],g=this.attributes[d]||
gl.getAttribLocation(this.program,d.replace(/^gl_/,"_gl_"));
if(g!=-1){
this.attributes[d]=g;gl.bindBuffer(gl.ARRAY_BUFFER,e.buffer);gl.enableVertexAttribArray(g);gl.vertexAttribPointer(g,e.buffer.spacing,gl.FLOAT,false,0,0)
};
};
for(d in this.attributes)d in a||gl.disableVertexAttribArray(this.attributes[d]);
gl.bindBuffer(gl.ELEMENT_ARRAY_BUFFER,b.buffer);gl.drawElements(c,b.buffer.length,gl.UNSIGNED_SHORT,0);return this
};
Texture=function(a,b,c){
c=c||{
};
this.id=gl.createTexture();this.width=a;this.height=
b;this.format=c.format||gl.RGBA;this.type=c.type||gl.UNSIGNED_BYTE;gl.bindTexture(gl.TEXTURE_2D,this.id);gl.pixelStorei(gl.UNPACK_FLIP_Y_WEBGL,1);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MAG_FILTER,c.filter||c.magFilter||gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_MIN_FILTER,c.filter||c.minFilter||gl.LINEAR);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_S,c.wrap||c.wrapS||gl.CLAMP_TO_EDGE);gl.texParameteri(gl.TEXTURE_2D,gl.TEXTURE_WRAP_T,c.wrap||c.wrapT||gl.CLAMP_TO_EDGE);gl.texImage2D(gl.TEXTURE_2D,
0,this.format,a,b,0,this.format,this.type,null)
};
Texture.prototype.bind=function(a){
gl.activeTexture(gl.TEXTURE0+(a||0));gl.bindTexture(gl.TEXTURE_2D,this.id)
};
Texture.prototype.unbind=function(a){
gl.activeTexture(gl.TEXTURE0+(a||0));gl.bindTexture(gl.TEXTURE_2D,null)
};
var w,t;Texture.prototype.drawTo=function(a){
var b=gl.getParameter(gl.VIEWPORT);w=w||gl.createFramebuffer();t=t||gl.createRenderbuffer();gl.bindFramebuffer(gl.FRAMEBUFFER,w);gl.bindRenderbuffer(gl.RENDERBUFFER,t);if(this.width!=t.width||
this.height!=t.height){
t.width=this.width;t.height=this.height;gl.renderbufferStorage(gl.RENDERBUFFER,gl.DEPTH_COMPONENT16,this.width,this.height)
};
gl.framebufferTexture2D(gl.FRAMEBUFFER,gl.COLOR_ATTACHMENT0,gl.TEXTURE_2D,this.id,0);gl.framebufferRenderbuffer(gl.FRAMEBUFFER,gl.DEPTH_ATTACHMENT,gl.RENDERBUFFER,t);gl.viewport(0,0,this.width,this.height);a();gl.bindFramebuffer(gl.FRAMEBUFFER,null);gl.bindRenderbuffer(gl.RENDERBUFFER,null);gl.viewport(b[0],b[1],b[2],b[3])
};
Texture.prototype.swapWith=function(a){
var b;
b=a.id;a.id=this.id;this.id=b;b=a.width;a.width=this.width;this.width=b;b=a.height;a.height=this.height;this.height=b
};
Texture.fromImage=function(a,b){
b=b||{
};
var c=new Texture(a.width,a.height,b);gl.texImage2D(gl.TEXTURE_2D,0,c.format,c.format,c.type,a);b.minFilter&&b.minFilter!=gl.NEAREST&&b.minFilter!=gl.LINEAR&&gl.generateMipmap(gl.TEXTURE_2D);return c
};
Vector=function(a,b,c){
this.x=a||0;this.y=b||0;this.z=c||0
};
Vector.prototype.negative=function(){
return new Vector(-this.x,-this.y,-this.z)
};
Vector.prototype.add=function(a){
var b=a instanceof Vector;return new Vector(this.x+(b?a.x:a),this.y+(b?a.y:a),this.z+(b?a.z:a))
};
Vector.prototype.subtract=function(a){
var b=a instanceof Vector;return new Vector(this.x-(b?a.x:a),this.y-(b?a.y:a),this.z-(b?a.z:a))
};
Vector.prototype.multiply=function(a){
var b=a instanceof Vector;return new Vector(this.x*(b?a.x:a),this.y*(b?a.y:a),this.z*(b?a.z:a))
};
Vector.prototype.divide=function(a){
var b=a instanceof Vector;return new Vector(this.x/(b?a.x:a),this.y/
(b?a.y:a),this.z/(b?a.z:a))
};
Vector.prototype.dot=function(a){
return this.x*a.x+this.y*a.y+this.z*a.z
};
Vector.prototype.cross=function(a){
return new Vector(this.y*a.z-this.z*a.y,this.z*a.x-this.x*a.z,this.x*a.y-this.y*a.x)
};
Vector.prototype.length=function(){
return Math.sqrt(this.dot(this))
};
Vector.prototype.unit=function(){
return this.divide(this.length())
};
Vector.prototype.min=function(){
return Math.min(Math.min(this.x,this.y),this.z)
};
Vector.prototype.max=function(){
return Math.max(Math.max(this.x,
this.y),this.z)
};
Vector.prototype.toAngles=function(){
return{theta:Math.atan2(this.z,this.x),phi:Math.asin(this.y/this.length())
};
};
Vector.prototype.toArray=function(a){
return[this.x,this.y,this.z].slice(0,a||3)
};
Vector.fromAngles=function(a,b){
return new Vector(Math.cos(a)*Math.cos(b),Math.sin(b),Math.sin(a)*Math.cos(b))
};
Vector.random=function(){
return Vector.fromAngles(Math.random()*Math.PI*2,Math.asin(Math.random()*2-1))
};
Vector.min=function(a,b){
return new Vector(Math.min(a.x,b.x),Math.min(a.y,
b.y),Math.min(a.z,b.z))
};
Vector.max=function(a,b){
return new Vector(Math.max(a.x,b.x),Math.max(a.y,b.y),Math.max(a.z,b.z))
};
Vector.lerp=function(a,b,c){
return a.add(b.subtract(a).multiply(c))
};
Vector.fromArray=function(a){
return new Vector(a[0],a[1],a[2])
};
};
)();
| zzy-code-test | html5/water_cube_demo/lightgl.js | JavaScript | gpl2 | 23,612 |
exports.unsetObject = function( object ){
for(var i in object)
if(object.hasOwnProperty(i) && typeof object[i] == "function")
object[i] = function(){};
};
exports.getAngleByRadian = function( radian ){
return radian * 180 / Math.PI;
}
exports.pointToRadian = function( origin, point ){
var PI = Math.PI;
if( point[0] === origin[0] ){
if ( point[1] > origin[1] )
return PI * 0.5;
return PI * 1.5
}else if( point[1] === origin[1] ){
if ( point[0] > origin[0] )
return 0;
return PI;
}
var t = Math.atan( ( origin[1] - point[1] ) / ( origin[0] - point[0] ) );
if( point[0] > origin[0] && point[1] < origin[1] )
return t + 2 * PI;
if( point[0] > origin[0] && point[1] > origin[1] )
return t;
return t + PI;
} | zzy-code-test | html5/fruitninja/scripts/tools.js | JavaScript | gpl2 | 750 |
/**
* layer manager
*/
var Raphael = require( "lib/raphael" );
var Ucren = require( "lib/ucren" );
var layers = {};
var zindexs = {
"default": zi(),
"light": zi(),
"knife": zi(),
"fruit": zi(),
"juice": zi(),
"flash": zi(),
"mask": zi()
};
exports.createImage = function( layer, src, x, y, w, h ){
layer = this.getLayer( layer );
return layer.image( src, x, y, w, h );
};
exports.createText = function( layer, text, x, y, fill, size ){
layer = this.getLayer( layer );
if( Ucren.isIe )
y += 2;
return layer.text(x, y, text).attr({
fill: fill || "#fff",
"font-size": size || "14px",
"font-family": "黑体",
"text-anchor": "start"
});
};
exports.getLayer = function( name ){
var p, layer;
name = name || "default";
if( p = layers[name] ){
return p;
}else{
layer = Ucren.makeElement( "div", { "class": "layer", "style": "z-index: " + ( zindexs[name] || 0 ) + ";" } );
Ucren.Element( "extra" ).add( layer );
p = layers[name] = Raphael( layer, 640, 480 );
// if( Ucren.isSafari )
// p.safari();
return p;
}
};
function zi(){
return zi.num = ++ zi.num || 2;
} | zzy-code-test | html5/fruitninja/scripts/layer.js | JavaScript | gpl2 | 1,121 |
/**
* a simple state manager
* @author dron
* @date 2012-06-28
*/
var Ucren = require( "lib/ucren" );
var timeline = require( "timeline" );
/**
* usage:
* state( key ).is( value ) -> determine if the value of key is the given value
* state( key ).isnot( value ) -> determine if the value of key is not given value
* state( key ).ison() -> determine if the value of key is the boolean value 'true'
* state( key ).isoff() -> determine if the value of key is the boolean value 'false'
* state( key ).isunset() -> determine if the value of key is undefined
* state( key ).set( value ) -> set the value of key to a given value
* state( key ).get() -> get the value of key
* state( key ).on() -> set the value of key to boolean value 'true'
* state( key ).off() -> set the value of key to boolean value 'false'
*/
var stack = {};
var cache = {};
var callbacks = {};
exports = function( key ){
if( cache[ key ] )
return cache[ key ];
return cache[ key ] = {
is: function( value ){
return stack[key] === value;
},
isnot: function( value ){
return stack[key] !== value;
},
ison: function(){
return this.is( true );
},
isoff: function(){
return this.isnot( true );
},
isunset: function(){
return this.is( undefined );
},
set: function(){
var lastValue = NaN;
return function( value ){
var c;
stack[key] = value;
if( lastValue !== value && ( c = callbacks[ key ] ) )
for(var i = 0, l = c.length; i < l; i ++)
c[i].call( this, value );
lastValue = value;
}
}(),
get: function(){
return stack[key];
},
on: function(){
var me = this;
me.set( true );
return {
keep: function( time ){
timeline.setTimeout( me.set.saturate( me, false ), time );
}
}
},
off: function(){
var me = this;
me.set( false );
return {
keep: function( time ){
timeline.setTimeout( me.set.saturate( me, true ), time );
}
}
},
hook: function( fn ){
var c;
if( !( c = callbacks[ key ] ) )
callbacks[ key ] = [ fn ];
else
c.push( fn );
},
unhook: function(){
// TODO:
}
}
}; | zzy-code-test | html5/fruitninja/scripts/state.js | JavaScript | gpl2 | 2,211 |
var timeline = require( "timeline" );
var tools = require( "tools" );
var sence = require( "sence" );
var Ucren = require( "lib/ucren" );
var buzz = require( "lib/buzz" );
var control = require( "control" );
var csl = require( "object/console" );
var message = require( "message" );
var state = require( "state" );
var game = require( "game" );
var collide = require( "collide" );
var setTimeout = timeline.setTimeout.bind( timeline );
var log = function(){
var time = 1e3, add = 300, fn;
fn = function( text ){
setTimeout( function(){ csl.log( text ); }, time );
time += add;
};
fn.clear = function(){
setTimeout( csl.clear.bind( csl ), time );
time += add;
};
return fn;
}();
exports.start = function(){
[ timeline, sence, control ].invoke( "init" );
log( "正在加载鼠标控制脚本" );
log( "正在加载图像资源" );
log( "正在加载游戏脚本" );
log( "正在加载剧情" );
log( "正在初始化" );
log( "正在启动游戏..." );
log.clear();
setTimeout( sence.switchSence.saturate( sence, "home-menu" ), 3000 );
};
message.addEventListener("slice", function( knife ){
var fruits = collide.check( knife ), angle;
if( fruits.length )
angle = tools.getAngleByRadian( tools.pointToRadian( knife.slice(0, 2), knife.slice(2, 4) ) ),
fruits.forEach(function( fruit ){
message.postMessage( fruit, angle, "slice.at" );
});
});
message.addEventListener("slice.at", function( fruit, angle ){
if( state( "sence-state" ).isnot( "ready" ) )
return ;
if( state( "sence-name" ).is( "game-body" ) ){
game.sliceAt( fruit, angle );
return ;
}
if( state( "sence-name" ).is( "home-menu" ) ){
fruit.broken( angle );
if( fruit.isHomeMenu )
switch( 1 ){
case fruit.isDojoIcon:
sence.switchSence( "dojo-body" ); break;
case fruit.isNewGameIcon:
sence.switchSence( "game-body" ); break;
case fruit.isQuitIcon:
sence.switchSence( "quit-body" ); break;
}
return ;
}
});
var tip = "";
if( !Ucren.isChrome )
tip = "$为了获得最佳流畅度,推荐您使用 <span class='b'>Google Chrome</span> 体验本游戏";
if( !buzz.isSupported() )
tip = tip.replace( "$", "您的浏览器不支持 <audio> 播放声效,且" );
tip = tip.replace( "$", "" );
Ucren.Element( "browser" ).html( tip ); | zzy-code-test | html5/fruitninja/scripts/main.js | JavaScript | gpl2 | 2,545 |
/**
* a easy timeline manager
* @version 1.0
* @author dron
*/
var Ucren = require( "lib/ucren" );
var timerCache = {};
var timeline = {};
// var timer = timeline;
// <or>
// var timer = timeline.use( name ).init( 10 ); // to use a new timeline instance
//
// var t = timer.createTask(...);
// t.stop();
//
// timer.setTimeout(...);
// timer.setInterval(...);
// timer.getFPS();
function ClassTimer(){
this.tasks = [];
this.addingTasks = [];
this.adding = 0;
}
/**
* initialize timeline
*/
ClassTimer.prototype.init = function( ms ){
var me = this;
if( me.inited )
return ;
else
me.inited = 1;
me.startTime = now();
me.intervalTime = ms || 5;
me.count = 0;
me.intervalFn = function(){
me.count ++;
me.update( now() );
};
me.start();
return me;
};
/**
* create a task
* @param {Object} conf the config
* @return {Task} a task instance
*/
ClassTimer.prototype.createTask = function( conf ){
/* e.g. timer.createTask({
start: 500, duration: 2000, data: [a, b, c,..], object: module,
onTimeUpdate: fn(time, a, b, c,..), onTimeStart: fn(a, b, c,..), onTimeEnd: fn(a, b, c,..),
recycle: []
}); */
var task = createTask( conf );
this.addingTasks.unshift( task );
this.adding = 1;
if( conf.recycle )
this.taskList( conf.recycle, task );
this.start();
return task;
};
/**
* use a array to recycle the task
* @param {Array} queue be use for recycling task
* @param {Task} task a task instance
* @return {Array} this queue
*/
ClassTimer.prototype.taskList = function( queue, task ){
if( !queue.clear )
queue.clear = function(){
var i = this.length;
while( i -- )
task = this[i],
task.stop(),
this.splice( i, 1 );
return this;
};
if( task )
queue.unshift( task );
return queue;
};
/**
* create a timer for once callback
* @param {Function} fn callback function
* @param {Number} time time, unit: ms
*/
ClassTimer.prototype.setTimeout = function( fn, time ){
// e.g. setTimeout(fn, time);
return this.createTask({ start: time, duration: 0, onTimeStart: fn });
};
/**
* create a timer for ongoing callback
* @param {Function} fn callback function
* @param {Number} time time, unit: ms
*/
ClassTimer.prototype.setInterval = function( fn, time ){
// e.g. setInterval(fn, time);
var timer = setInterval( fn, time );
return {
stop: function(){
clearInterval( timer );
}
};
};
/**
* get the current fps
* @return {Number} fps number
*/
ClassTimer.prototype.getFPS = function(){
var t = now(), c = this.count, fps = c / ( t - this.startTime ) * 1e3;
if( c > 1e3 )
this.count = 0,
this.startTime = t;
return fps;
};
// privates
ClassTimer.prototype.start = function(){
clearInterval( this.interval );
this.interval = setInterval( this.intervalFn, this.intervalTime );
};
ClassTimer.prototype.stop = function(){
clearInterval( this.interval );
};
ClassTimer.prototype.update = function( time ){
var tasks = this.tasks, addingTasks = this.addingTasks, adding = this.adding;
var i = tasks.length, t, task, start, duration, data;
while( i -- ){
task = tasks[i];
start = task.start;
duration = task.duration;
if( time >= start ){
if( task.stopped ){
tasks.splice( i, 1 );
continue;
}
checkStartTask( task );
if( ( t = time - start ) < duration )
updateTask( task, t );
else
updateTask( task, duration ),
task.onTimeEnd.apply( task.object, task.data.slice(1) ),
tasks.splice( i, 1 );
}
}
if( adding )
tasks.unshift.apply( tasks, addingTasks ),
addingTasks.length = adding = 0;
if( !tasks.length )
this.stop();
};
timeline.use = function( name ){
var module;
if( module = timerCache[ name ] )
return module;
else
module = timerCache[ name ] = new ClassTimer;
return module;
};
/**
* @functions
*/
var now = function(){
return new Date().getTime();
};
var createTask = function( conf ){
var object = conf.object || {};
conf.start = conf.start || 0;
return {
start: conf.start + now(),
duration: conf.duration == -1 ? 86400000 : conf.duration,
data: conf.data ? [ 0 ].concat( conf.data ) : [ 0 ],
started: 0,
object: object,
onTimeStart: conf.onTimeStart || object.onTimeStart || Ucren.nul,
onTimeUpdate: conf.onTimeUpdate || object.onTimeUpdate || Ucren.nul,
onTimeEnd: conf.onTimeEnd || object.onTimeEnd || Ucren.nul,
stop: function(){
this.stopped = 1;
}
}
};
var updateTask = function( task, time ){
var data = task.data;
data[0] = time;
task.onTimeUpdate.apply( task.object, data );
};
var checkStartTask = function( task ){
if( !task.started )
task.started = 1,
task.onTimeStart.apply( task.object, task.data.slice(1) ),
updateTask( task, 0 );
};
/**
* for compatible the old version
*/
exports = timeline.use( "default" ).init( 10 );
exports.use = function( name ){
if( Ucren.isIe )
exports;
return timeline.use( name );
}; | zzy-code-test | html5/fruitninja/scripts/timeline.js | JavaScript | gpl2 | 5,050 |
var layer = require( "../layer" );
var timeline = require( "../timeline" );
var tween = require( "../lib/tween" );
/**
* 位移类模块模型
*/
exports.create = function( imageSrc, width, height, origX, origY, targetX, targetY, animMap, animDur ){
var module = {};
var image;
var anim = {};
if( typeof animMap === "function" )
anim.show = anim.hide = animMap;
else
anim = animMap;
var createTask = function( start, duration, sx, sy, ex, ey, anim, mode ){
timeline.createTask({
start: start,
duration: duration,
object: module, data: [ sx, sy, ex, ey, anim, mode ],
onTimeUpdate: module.onTimeUpdate, onTimeStart: module.onTimeStart, onTimeEnd: module.onTimeEnd,
recycle: module.anims
});
};
module.anims = [];
module.set = function(){
image = layer.createImage( "default", imageSrc, origX, origY, width, height );
};
module.show = function( start ){
createTask( start, animDur, origX, origY, targetX, targetY, anim.show, "show" );
};
module.hide = function(){
this.anims.clear();
createTask( 0, animDur, targetX, targetY, origX, origY, anim.hide, "hide" );
};
module.onTimeUpdate = function( time, sx, sy, ex, ey, anim ){
image.attr( {
x: anim( time, sx, ex - sx, animDur ),
y: anim( time, sy, ey - sy, animDur )
} );
};
module.onTimeStart = function(){
};
module.onTimeEnd = function( sx, sy, ex, ey, anim ){
if( anim === "hide" )
image.hide();
};
return module;
}; | zzy-code-test | html5/fruitninja/scripts/factory/displacement.js | JavaScript | gpl2 | 1,479 |
var layer = require( "../layer" );
var Ucren = require( "../lib/ucren" );
var timeline = require( "../timeline" ).use( "fruit" ).init( 1 );
var timeline2 = require( "../timeline" ).use( "fruit-apart" ).init( 1 );
var tween = require( "../lib/tween" );
var message = require( "../message" );
var flame = require( "../object/flame" );
var flash = require( "../object/flash" );
var juice = require( "../factory/juice" );
var ie = Ucren.isIe;
var safari = Ucren.isSafari;
/**
* 水果模块模型
*/
var zoomAnim = tween.exponential.co;
var rotateAnim = tween.circular;
var linearAnim = tween.linear;
var dropAnim = tween.quadratic.ci;
var fallOffAnim = tween.quadratic.co;
var random = Ucren.randomNumber;
var min = Math.min;
var average = function( a, b ){ return ( ( a + b ) / 2 ) >> 0; };
var dropTime = 1200, dropXScope = 200, shadowPos = 50;
var infos = {
// type: [ imageSrc, width, height, radius, fixAngle, isReverse, juiceColor ]
boom: [ "images/fruit/boom.png", 66, 68, 26, 0, 0, null ],
peach: [ "images/fruit/peach.png", 62, 59, 37, -50, 0, "#e6c731" ],
sandia: [ "images/fruit/sandia.png", 98, 85, 38, -100, 0, "#c00" ],
apple: [ "images/fruit/apple.png", 66, 66, 31, -54, 0, "#c8e925" ],
banana: [ "images/fruit/banana.png", 126, 50, 43, 90, 0, null ],
basaha: [ "images/fruit/basaha.png", 68, 72, 32, -135, 0, "#c00" ]
};
// TODO: 是否水果全开?
var types = [ "peach", "sandia", "apple", "banana", "basaha" ];
// var types = [ "sandia", "boom" ];
var rotateSpeed = [ 60, 50, 40, -40, -50, -60 ];
var fruitCache = [];
function ClassFruit(conf){
var info = infos[ conf.type ], radius = info[3];
this.type = conf.type;
this.originX = conf.originX;
this.originY = conf.originY;
this.radius = radius;
this.startX = conf.originX;
this.startY = conf.originY;
this.radius = radius;
this.anims = [];
if( this.type === "boom" )
this.flame = flame.create( this.startX - radius + 4, this.startY - radius + 5, conf.flameStart || 0 );
}
ClassFruit.prototype.set = function( hide ){
var inf = infos[ this.type ], radius = this.radius;
this.shadow = layer.createImage( "fruit", "images/shadow.png", this.startX - radius, this.startY - radius + shadowPos, 106, 77 );
this.image = layer.createImage( "fruit", inf[0], this.startX - radius, this.startY - radius, inf[1], inf[2] );
if( hide )
this.image.hide(),
this.shadow.hide();
return this;
};
ClassFruit.prototype.pos = function( x, y ){
if( x == this.originX && y == this.originY )
return ;
var r = this.radius;
this.originX = x;
this.originY = y;
this.image.attr({ x: x -= r, y: y -= r });
this.shadow.attr({ x: x, y: y + shadowPos });
if( this.type === "boom" )
this.flame.pos( x + 4, y + 5 );
};
ClassFruit.prototype.show = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1e-5, 1, "show" ],
object: this, onTimeUpdate: this.onScaling, onTimeStart: this.onShowStart,
recycle: this.anims
});
};
ClassFruit.prototype.hide = function( start ){
if( this.type !== "boom" ) // if it is not a boom, it can't to be hide.
return ;
this.anims.clear();
this.flame.remove();
timeline.createTask({
start: start, duration: 500, data: [ 1, 1e-5, "hide" ],
object: this, onTimeUpdate: this.onScaling, onTimeEnd: this.onHideEnd,
recycle: this.anims
});
};
ClassFruit.prototype.rotate = function( start, speed ){
this.rotateSpeed = speed || rotateSpeed[ random( 6 ) ];
this.rotateAnim = timeline.createTask({
start: start, duration: -1,
object: this, onTimeUpdate: this.onRotating,
recycle: this.anims
});
};
ClassFruit.prototype.broken = function( angle ){
if( this.brokend )return;
this.brokend = true;
var index;
if( ( index = fruitCache.indexOf( this ) ) > -1 )
fruitCache.splice( index, 1 );
if( this.type !== "boom" )
flash.showAt( this.originX, this.originY, angle ),
juice.create( this.originX, this.originY, infos[ this.type ][6] ),
this.apart( angle );
else
this.hide();
};
ClassFruit.prototype.pause = function(){
if( this.brokend )
return;
this.anims.clear();
if( this.type == "boom" )
this.flame.remove();
};
// 分开
ClassFruit.prototype.apart = function( angle ){
this.anims.clear();
this.image.hide();
this.shadow.hide();
this.aparted = true;
var inf = infos[ this.type ], preSrc = inf[0].replace( ".png", "" ), radius = this.radius;
var create = layer.createImage.saturate( layer, this.startX - radius, this.startY - radius, inf[1], inf[2] );
angle = ( ( angle % 180 ) + 360 + inf[4] ) % 360;
this.bImage1 = create( "fruit", preSrc + "-1.png" );
this.bImage2 = create( "fruit", preSrc + "-2.png" );
[ this.bImage1, this.bImage2 ].invoke( "rotate", angle );
this.apartAngle = angle;
timeline2.createTask({
start: 0, duration: dropTime, object: this,
onTimeUpdate: this.onBrokenDropUpdate, onTimeStart: this.onBrokenDropStart, onTimeEnd: this.onBrokenDropEnd,
recycle: this.anims
});
};
// 抛出
ClassFruit.prototype.shotOut = function(){
var sign = [ -1, 1 ];
return function( start, endX ){
this.shotOutStartX = this.originX;
this.shotOutStartY = this.originY;
this.shotOutEndX = average( this.originX, endX );
this.shotOutEndY = min( this.startY - random( this.startY - 100 ), 200 );
this.fallOffToX = endX;
timeline.createTask({
start: start, duration: dropTime, object: this,
onTimeUpdate: this.onShotOuting, onTimeStart: this.onShotOutStart, onTimeEnd: this.onShotOutEnd,
recycle: this.anims
});
if( this.type != "boom" )
this.rotate( 0, ( random( 180 ) + 90 ) * sign[ random( 2 ) ] );
return this;
};
}();
// 掉落
ClassFruit.prototype.fallOff = function(){
var sign = [ -1, 1 ];
var signIndex = 0;
return function( start, x ){
if( this.aparted || this.brokend )
return ;
var y = 600;
if( typeof x !== "number" )
x = this.originX + random( dropXScope ) * sign[ ( signIndex ++ ) % 2 ];
this.fallTargetX = x;
this.fallTargetY = y;
timeline.createTask({
start: start, duration: dropTime, object: this,
onTimeUpdate: this.onFalling, onTimeStart: this.onFallStart, onTimeEnd: this.onFallEnd,
recycle: this.anims
});
}
}();
ClassFruit.prototype.remove = function(){
var index;
this.anims.clear();
if( this.image )
this.image.remove(),
this.shadow.remove();
if( this.bImage1 )
this.bImage1.remove(),
this.bImage2.remove();
if( this.type === "boom" )
this.flame.remove();
if( ( index = fruitCache.indexOf( this ) ) > -1 )
fruitCache.splice( index, 1 );
for(var name in this)
if( typeof this[name] === "function" )
this[name] = function( name ){
return function(){
throw new Error( "method " + name + " has been removed" );
};
}( name );
else delete this[name];
message.postMessage( this, "fruit.remove" );
};
// 显示/隐藏 相关
ClassFruit.prototype.onShowStart = function(){
this.image.show();
// this.shadow.show();
};
ClassFruit.prototype.onScaling = function( time, a, b, z ){
this.image.scale( z = zoomAnim( time, a, b - a, 500 ), z );
this.shadow.scale( z, z );
};
ClassFruit.prototype.onHideEnd = function(){
this.remove();
};
// 旋转相关
ClassFruit.prototype.onRotateStart = function(){
};
ClassFruit.prototype.onRotating = function( time ){
this.image.rotate( ( this.rotateSpeed * time / 1e3 ) % 360, true );
};
// 裂开相关
ClassFruit.prototype.onBrokenDropUpdate = function( time ){
var radius = this.radius;
this.bImage1.attr({
x: linearAnim( time, this.brokenPosX - radius, this.brokenTargetX1, dropTime ),
y: dropAnim( time, this.brokenPosY - radius, this.brokenTargetY1 - this.brokenPosY + radius, dropTime )
}).rotate( linearAnim( time, this.apartAngle, this.bImage1RotateAngle, dropTime ), true );
this.bImage2.attr({
x: linearAnim( time, this.brokenPosX - radius, this.brokenTargetX2, dropTime ),
y: dropAnim( time, this.brokenPosY - radius, this.brokenTargetY2 - this.brokenPosY + radius, dropTime )
}).rotate( linearAnim( time, this.apartAngle, this.bImage2RotateAngle, dropTime ), true );
};
ClassFruit.prototype.onBrokenDropStart = function(){
this.brokenTargetX1 = -( random( dropXScope ) + 75 );
this.brokenTargetX2 = random( dropXScope + 75 );
this.brokenTargetY1 = 600;
this.brokenTargetY2 = 600;
this.brokenPosX = this.originX;
this.brokenPosY = this.originY;
this.bImage1RotateAngle = - random( 150 ) - 50;
this.bImage2RotateAngle = random( 150 ) + 50;
for(var f, i = fruitCache.length - 1; i >= 0; i --)
if( fruitCache[i] === this )
fruitCache.splice( i, 1 );
};
ClassFruit.prototype.onBrokenDropEnd = function(){
this.remove();
};
// 抛出相关
ClassFruit.prototype.onShotOuting = function( time ){
this.pos(
linearAnim( time, this.shotOutStartX, this.shotOutEndX - this.shotOutStartX, dropTime ),
fallOffAnim( time, this.shotOutStartY, this.shotOutEndY - this.shotOutStartY, dropTime )
);
};
ClassFruit.prototype.onShotOutStart = function(){
// body...
};
ClassFruit.prototype.onShotOutEnd = function(){
this.fallOff( 0, this.fallOffToX );
};
// 掉落相关
ClassFruit.prototype.onFalling = function( time ){
var y;
this.pos(
linearAnim( time, this.brokenPosX, this.fallTargetX - this.brokenPosX, dropTime ),
y = dropAnim( time, this.brokenPosY, this.fallTargetY - this.brokenPosY, dropTime )
);
this.checkForFallOutOfViewer( y );
};
ClassFruit.prototype.onFallStart = function(){
this.brokenPosX = this.originX;
this.brokenPosY = this.originY;
};
ClassFruit.prototype.onFallEnd = function(){
message.postMessage( this, "fruit.fallOff" );
this.remove();
};
// privates
ClassFruit.prototype.checkForFallOutOfViewer = function( y ){
if( y > 480 + this.radius )
this.checkForFallOutOfViewer = Ucren.nul,
this.rotateAnim && this.rotateAnim.stop(),
message.postMessage( this, "fruit.fallOutOfViewer" );
};
exports.create = function( type, originX, originY, isHide, flameStart ){
if( typeof type == "number" ) // 缺省 type
isHide = originY,
originY = originX,
originX = type,
type = getType();
var fruit = new ClassFruit({ type: type, originX: originX, originY: originY, flameStart: flameStart }).set( isHide );
fruitCache.unshift( fruit );
return fruit;
};
exports.getFruitInView = function(){
return fruitCache;
};
exports.getDropTimeSetting = function(){
return dropTime;
};
function getType(){
if( random( 8 ) == 4 )
return "boom";
else
return types[ random( 5 ) ];
} | zzy-code-test | html5/fruitninja/scripts/factory/fruit.js | JavaScript | gpl2 | 10,496 |
/**
* 果汁
*/
var Ucren = require( "../lib/ucren" );
var layer = require( "../layer" ).getLayer("juice");
var timeline = require( "../timeline" ).use( "juice" ).init( 10 );
var tween = require( "../lib/tween" );
var tools = require( "../tools" );
var random = Ucren.randomNumber;
var dur = 1500;
var anim = tween.exponential.co;
var dropAnim = tween.quadratic.co;
var sin = Math.sin;
var cos = Math.cos;
var num = 10;
var radius = 10;
// if( Ucren.isIe6 || Ucren.isSafari )
// switchOn = false;
// if( Ucren.isIe || Ucren.isSafari )
// num = 6;
function ClassJuice( x, y, color ){
this.originX = x;
this.originY = y;
this.color = color;
this.distance = random( 200 ) + 100;
this.radius = radius;
this.dir = random( 360 ) * Math.PI / 180;
}
ClassJuice.prototype.render = function(){
this.circle = layer.circle( this.originX, this.originY, this.radius ).attr({
fill: this.color,
stroke: "none"
});
};
ClassJuice.prototype.sputter = function(){
timeline.createTask({
start: 0, duration: dur,
object: this, onTimeUpdate: this.onTimeUpdate, onTimeEnd: this.onTimeEnd
});
};
ClassJuice.prototype.onTimeUpdate = function( time ){
var distance, x, y, z;
distance = anim( time, 0, this.distance, dur );
x = this.originX + distance * cos( this.dir );
y = this.originY + distance * sin( this.dir ) + dropAnim( time, 0, 200, dur );
z = anim( time, 1, -1, dur );
this.circle.attr({ cx: x, cy: y }).scale( z, z );
};
ClassJuice.prototype.onTimeEnd = function(){
this.circle.remove();
tools.unsetObject( this );
};
exports.create = function( x, y, color ){
for(var i = 0; i < num; i ++)
this.createOne( x, y, color );
};
exports.createOne = function( x, y, color ){
if( !color )
return;
var juice = new ClassJuice( x, y, color );
juice.render();
juice.sputter();
}; | zzy-code-test | html5/fruitninja/scripts/factory/juice.js | JavaScript | gpl2 | 1,828 |
var layer = require( "../layer" );
var timeline = require( "../timeline" );
var Ucren = require( "../lib/ucren" );
/**
* 旋转类模块模型
*/
exports.create = function( imageSrc, x, y, w, h, z, anim, animDur ){
var module = {}, image;
var rotateDire = [12, -12][Ucren.randomNumber(2)];
var defaultAngle = Ucren.randomNumber(360);
module.anims = [];
module.set = function(){
image = layer.createImage( "default", imageSrc, x, y, w, h ).scale( z, z ).rotate( defaultAngle, true );
};
module.show = function(start){
timeline.createTask({
start: start,
duration: animDur,
object: this,
data: [z, 1],
onTimeUpdate: this.onZooming,
onTimeEnd: this.onShowEnd,
recycle: this.anims
});
};
module.hide = function(start){
this.anims.clear();
timeline.createTask({
start: start,
duration: animDur,
object: this,
data: [ 1, z ],
onTimeUpdate: this.onZooming,
recycle: this.anims
});
};
module.onShowEnd = function(name){
this.anims.clear();
timeline.createTask({
start: 0,
duration: -1,
object: this,
onTimeUpdate: module.onRotating,
recycle: this.anims
});
};
module.onZooming = function(){
var z;
return function( time, a, b ){
image.scale( z = anim( time, a, b - a, animDur ), z );
}
}();
module.onRotating = function(){
var lastTime = 0, an = defaultAngle;
return function( time, name, a, b ){
an = ( an + ( time - lastTime ) / 1e3 * rotateDire ) % 360;
image.rotate( an, true );
lastTime = time;
}
}();
return module;
} | zzy-code-test | html5/fruitninja/scripts/factory/rotate.js | JavaScript | gpl2 | 1,575 |
/**
*
*/
var layer = require( "../layer" );
var timeline = require( "../timeline" ).use( "flash" ).init( 10 );
var tween = require( "../lib/tween" );
var sound = require( "../lib/sound" );
var image, snd, xDiff = 0, yDiff = 0;
var anim = tween.quadratic.cio;
var anims = [];
var dur = 100;
exports.set = function(){
image = layer.createImage( "flash", "images/flash.png", 0, 0, 358, 20 ).hide();
snd = sound.create( "sound/splatter" );
};
exports.showAt = function( x, y, an ){
image.rotate( an, true ).scale( 1e-5, 1e-5 ).attr({
x: x + xDiff,
y: y + yDiff
}).show();
anims.clear && anims.clear();
snd.play();
timeline.createTask({
start: 0, duration: dur, data: [ 1e-5, 1 ],
object: this, onTimeUpdate: this.onTimeUpdate,
recycle: anims
});
timeline.createTask({
start: dur, duration: dur, data: [ 1, 1e-5 ],
object: this, onTimeUpdate: this.onTimeUpdate,
recycle: anims
});
};
exports.onTimeUpdate = function( time, a, b, z ){
image.scale( z = anim( time, a, b - a, dur ), z );
}; | zzy-code-test | html5/fruitninja/scripts/object/flash.js | JavaScript | gpl2 | 1,096 |
var displacement = require( "../factory/displacement" );
var tween = require( "../lib/tween" );
exports = displacement.create("images/ninja.png", 244, 81, 315, -140, 315, 43, {
show: tween.bounce.co,
hide: tween.exponential.co
}, 1e3); | zzy-code-test | html5/fruitninja/scripts/object/ninja.js | JavaScript | gpl2 | 238 |
/**
* 炸弹爆炸时的光线
*/
var layer = require( "../layer" );
var maskLayer = layer.getLayer( "mask" );
layer = layer.getLayer( "light" );
var Ucren = require( "../lib/ucren" );
var timeline = require( "../timeline" );
var message = require( "../message" );
var random = Ucren.randomNumber;
var pi = Math.PI;
var sin = Math.sin;
var cos = Math.cos;
var lights = [];
var indexs = [];
var lightsNum = 10;
for(var i = 0; i < lightsNum; i ++)
indexs[i] = i;
exports.start = function( boom ){
var x = boom.originX, y = boom.originY, time = 0, idx = indexs.random();
var i = lightsNum, b = function(){
build( x, y, idx[ this ] );
};
while( i -- )
timeline.setTimeout( b.bind( i ), time += 100 );
timeline.setTimeout(function(){
this.overWhiteLight();
}.bind( this ), time + 100);
};
exports.overWhiteLight = function(){
message.postMessage( "overWhiteLight.show" );
this.removeLights();
var dur = 4e3;
var mask = maskLayer.rect( 0, 0, 640, 480 ).attr({ fill: "#fff", stroke: "none" });
var control = {
onTimeUpdate: function( time ){
mask.attr( "opacity", 1 - time / dur );
},
onTimeEnd: function(){
mask.remove();
message.postMessage( "game.over" );
}
};
timeline.createTask({
start: 0, duration: dur,
object: control, onTimeUpdate: control.onTimeUpdate, onTimeEnd: control.onTimeEnd
});
};
exports.removeLights = function(){
for(var i = 0, l = lights.length; i < l; i ++)
lights[i].remove();
lights.length = 0;
};
function build( x, y, r ){
var a1, a2, x1, y1, x2, y2;
a1 = r * 36 + random( 10 );
a2 = a1 + 5;
a1 = pi * a1 / 180;
a2 = pi * a2 / 180;
x1 = x + 640 * cos( a1 );
y1 = y + 640 * sin( a1 );
x2 = x + 640 * cos( a2 );
y2 = y + 640 * sin( a2 );
var light = layer.path( [ "M", x, y, "L", x1, y1, "L", x2, y2, "Z" ] ).attr({
stroke: "none",
fill: "#fff"
});
lights.push( light );
} | zzy-code-test | html5/fruitninja/scripts/object/light.js | JavaScript | gpl2 | 1,994 |
var layer = require( "../layer" );
var tween = require( "../lib/tween" );
var timeline = require( "../timeline" );
var Ucren = require( "../lib/ucren" );
var setTimeout = timeline.setTimeout.bind( timeline );
var anim = tween.exponential.co;
var message = require( "../message" );
/**
* 分数模块
*/
var image, text1, text2, animLength = 500;;
var imageSx = -94, imageEx = 6;
var text1Sx = -59, text1Ex = 41;
var text2Sx = -93, text2Ex = 7;
exports.anims = [];
exports.set = function(){
image = layer.createImage( "default", "images/score.png", imageSx, 8, 29, 31 ).hide();
text1 = layer.createText( "default", "0", text1Sx, 24, "90-#fc7f0c-#ffec53", "30px" ).hide();
text2 = layer.createText( "default", "BEST 999", text2Sx, 48, "#af7c05", "14px" ).hide();
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "show", imageSx, imageEx, text1Sx, text1Ex, text2Sx, text2Ex ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: animLength, data: [ "hide", imageEx, imageSx, text1Ex, text1Sx, text2Ex, text2Sx ],
object: this, onTimeUpdate: this.onTimeUpdate, onTimeStart: this.onTimeStart, onTimeEnd: this.onTimeEnd,
recycle: this.anims
});
};
exports.number = function( number ){
text1.attr( "text", number || 0 );
image.scale( 1.2, 1.2 );
setTimeout(function(){
image.scale( 1, 1 );
}, 60);
// message.postMessage( number, "score.change" );
};
// 显示/隐藏 相关
exports.onTimeUpdate = function( time, mode, isx, iex, t1sx, t1ex, t2sx, t2ex ){
image.attr( "x", anim( time, isx, iex - isx, animLength ) );
text1.attr( "x", anim( time, t1sx, t1ex - t1sx, animLength ) );
text2.attr( "x", anim( time, t2sx, t2ex - t2sx, animLength ) );
};
exports.onTimeStart = function( mode ){
if( mode === "show" )
[ image, text1, text2 ].invoke( "show" );
};
exports.onTimeEnd = function( mode ){
if( mode === "hide" )
[ image, text1, text2 ].invoke( "hide" ),
text1.attr( "text", 0 );
}; | zzy-code-test | html5/fruitninja/scripts/object/score.js | JavaScript | gpl2 | 2,198 |
var Ucren = require( "../lib/ucren" );
var layer = require( "../layer" );
var timeline = require( "../timeline" );
var image, time;
var random = Ucren.randomNumber;
exports.set = function(){
image = layer.createImage( "default", "images/background.jpg", 0, 0, 640, 480 );
};
exports.wobble = function(){
time = timeline.setInterval( wobble, 50 );
};
exports.stop = function(){
time.stop();
image.attr({ x: 0, y: 0 });
};
function wobble(){
var x, y;
x = random( 12 ) - 6;
y = random( 12 ) - 6;
image.attr({ x: x, y: y });
}; | zzy-code-test | html5/fruitninja/scripts/object/background.js | JavaScript | gpl2 | 555 |
var timeline = require( "../timeline" );
var layer = require( "../layer" ).getLayer( "knife" );
var Ucren = require( "../lib/ucren" );
/**
* 刀光模块
*/
var lastX = null, lastY = null;
var abs = Math.abs;
var life = 200;
var stroke = 10;
var color = "#cbd3db";
var anims = [];
var switchState = true;
var knifes = [];
function ClassKnifePart( conf ){
this.sx = conf.sx;
this.sy = conf.sy;
this.ex = conf.ex;
this.ey = conf.ey;
knifes.push( this );
}
ClassKnifePart.prototype.set = function(){
var sx, sy, ex, ey, dx, dy, ax, ay;
sx = this.sx;
sy = this.sy;
ex = this.ex;
ey = this.ey;
dx = sx - ex;
dy = sy - ey;
ax = abs(dx);
ay = abs(dy);
if(ax > ay)
sx += dx < 0 ? -1 : 1,
sy += dy < 0 ? -( 1 * ay / ax ) : 1 * ay / ax;
else
sx += dx < 0 ? -( 1 * ax / ay ) : 1 * ax / ay,
sy += dy < 0 ? -1 : 1;
this.line = layer.path( "M" + sx + "," + sy + "L" + ex + "," + ey ).attr({
"stroke": color,
"stroke-width": stroke + "px"
});
timeline.createTask({ start: 0, duration: life, object: this, onTimeUpdate: this.update, onTimeEnd: this.end, recycle: anims });
return this;
};
ClassKnifePart.prototype.update = function( time ){
this.line.attr( "stroke-width", stroke * (1 - time / life) + "px" );
};
ClassKnifePart.prototype.end = function(){
this.line.remove();
var index;
if( index = knifes.indexOf( this ) )
knifes.splice( index, 1 );
};
exports.newKnife = function(){
lastX = lastY = null;
};
exports.through = function( x, y ){
if( !switchState )
return ;
var ret = null;
if( lastX !== null && ( lastX != x || lastY != y ) )
new ClassKnifePart({ sx: lastX, sy: lastY, ex: x, ey: y }).set(),
ret = [ lastX, lastY, x, y ];
lastX = x;
lastY = y;
return ret;
};
exports.pause = function(){
anims.clear();
this.switchOff();
};
exports.switchOff = function(){
switchState = false;
};
exports.switchOn = function(){
switchState = true;
this.endAll();
};
exports.endAll = function(){
for(var i = knifes.length - 1; i >= 0; i --)
knifes[i].end();
}; | zzy-code-test | html5/fruitninja/scripts/object/knife.js | JavaScript | gpl2 | 2,072 |
var layer = require( "../layer" );
var tween = require( "../lib/tween" );
var timeline = require( "../timeline" );
var message = require( "../message" );
var exponential = tween.exponential.co;
/**
* "coming soon" 模块
*/
exports.anims = [];
exports.set = function(){
this.image = layer.createImage( "default", "images/developing.png", 103, 218, 429, 53 ).hide().scale( 1e-5, 1e-5 );
};
exports.show = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1e-5, 1, "show" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
this.hide( 2000 );
};
exports.hide = function( start ){
timeline.createTask({
start: start, duration: 500, data: [ 1, 1e-5, "hide" ],
object: this, onTimeUpdate: this.onZooming, onTimeStart: this.onZoomStart, onTimeEnd: this.onZoomEnd,
recycle: this.anims
});
};
// 显示/隐藏 相关
exports.onZoomStart = function(){
this.image.show();
};
exports.onZooming = function( time, sz, ez, z ){
this.image.scale( z = exponential( time, sz, ez - sz, 500 ), z );
};
exports.onZoomEnd = function( sz, ez, mode ){
if( mode === "hide" )
this.image.hide();
}; | zzy-code-test | html5/fruitninja/scripts/object/developing.js | JavaScript | gpl2 | 1,228 |
/**
* 火焰模块
* @author zswang, dron
*/
var layer = require( "../layer" ).getLayer( "fruit" );
var timeline = require( "../timeline" );
var Ucren = require( "../lib/ucren" );
/*
raphael.path('M 27,122 Q 9,42 27,21 45,42 27,122')
.attr({
stroke: 'none',
fill: '180-#D8D380-#EDED7A-#D8D380'
});
*/
// 缩写
var math = Math, cos = math.cos, sin = math.sin,
trunc = parseInt,
random = math.random,
PI = math.PI;
var guid = 0;
/**
* 添加一个火苗
* @param{Array} center 中心位置 单位像素
* @param{Number} angle 运动方向 单位幅度
* @param{Number} length 运动长度 单位像素
* @param{Number} life 存活时间 单位毫秒
*/
function appendFlame( center, angle, length, life, flames ){
return flames[guid] = {
id: guid ++,
birthday: new Date,
center: center,
angle: angle,
length: length,
life: life,
path: layer.path().attr({ stroke: 'none', fill: trunc( angle * 180 / PI ) + '-#fafad9-#f0ef9c' })
};
}
var radius = 15;
function updateFlame( flames, n ){
var item = flames[n];
if ( !item )
return;
var age, center, p1, p2, p3, p4;
age = 1 - (new Date - item.birthday) / item.life;
if ( age <= 0 ){
item.path.remove();
delete flames[item.id];
return;
}
var ia, ic, il;
ia = item.angle;
ic = item.center;
il = item.length;
center = [ trunc(ic[0] + cos(ia) * il * (1 - age)), trunc(ic[1] + sin(ia) * il * (1 - age)) ];
p1 = [ trunc(center[0] - cos(ia) * radius * age), trunc(center[1] - sin(ia) * radius * age) ];
p2 = [ trunc(center[0] + cos(ia) * radius * age), trunc(center[1] + sin(ia) * radius * age) ];
p3 = [ trunc(center[0] - cos(ia + .5 * PI) * radius * .4 * age), trunc(center[1] - sin(ia + .5 * PI) * radius * .4 * age) ];
p4 = [ trunc(center[0] - cos(ia - .5 * PI) * radius * .4 * age), trunc(center[1] - sin(ia - .5 * PI) * radius * .4 * age) ];
item.path.attr({ path: 'M' + p1 + ' Q' + [ p3, p2, p4, p1 ].join(' ') });
};
function removeFlame( flames, n ){
var item = flames[n];
if( !item )
return;
item.path.remove();
delete flames[ n ];
};
exports.create = function( ox, oy, start ){
var timer1, timer2;
var object = {
pos: function( x, y ){
nx = x;
ny = y;
image.attr( "x", nx - 21 ).attr( "y", ny - 21 );
},
remove: function(){
[ timer1, timer2 ].invoke( "stop" );
image.remove();
for (var p in flames)
removeFlame( flames, p );
}
};
var nx = ox, ny = oy;
var image = layer.image("images/smoke.png", nx - 21, ny - 21, 43, 43).hide();
var flames = {};
timer1 = timeline.setTimeout(function(){
image.show();
timer2 = timeline.setInterval(function(){
if(random() < 0.9)
appendFlame( [ nx, ny ], PI * 2 * random(), 60, 200 + 500 * random(), flames );
for (var p in flames)
updateFlame( flames, p );
}, Ucren.isIe ? 20 : 40);
}, start || 0);
return object;
}; | zzy-code-test | html5/fruitninja/scripts/object/flame.js | JavaScript | gpl2 | 2,912 |
var displacement = require( "../factory/displacement" );
var tween = require( "../lib/tween" );
exports = displacement.create("images/home-mask.png", 640, 183, 0, -183, 0, 0, tween.exponential.co, 1e3); | zzy-code-test | html5/fruitninja/scripts/object/home-mask.js | JavaScript | gpl2 | 203 |
var displacement = require( "../factory/displacement" );
var tween = require( "../lib/tween" );
exports = displacement.create("images/home-desc.png", 161, 91, -161, 140, 7, 127, tween.exponential.co, 500); | zzy-code-test | html5/fruitninja/scripts/object/home-desc.js | JavaScript | gpl2 | 206 |
var rotate = require( "../factory/rotate" );
var tween = require( "../lib/tween" );
exports = rotate.create("images/quit.png", 493, 311, 141, 141, 1e-5, tween.exponential.co, 500); | zzy-code-test | html5/fruitninja/scripts/object/quit.js | JavaScript | gpl2 | 181 |