├── .gitattributes ├── .gitignore ├── GNU-AGPL-3.0.txt ├── Readme.txt ├── client ├── client.vcproj ├── client.vcxproj └── client.vcxproj.filters ├── emeralddb.sln ├── emeralddb ├── emeralddb.vcproj ├── emeralddb.vcxproj └── emeralddb.vcxproj.filters └── src ├── Makefile.am ├── bson ├── APACHE-2.0.txt ├── GNU-AGPL-3.0.txt └── src │ ├── bson-inl.h │ ├── bson.h │ ├── bson_db.h │ ├── bsonassert.h │ ├── bsonelement.h │ ├── bsonmisc.h │ ├── bsonobj.cpp │ ├── bsonobj.h │ ├── bsonobjbuilder.h │ ├── bsonobjiterator.h │ ├── bsontypes.h │ ├── inline_decls.h │ ├── lib │ ├── atomic_int.h │ ├── base64.cpp │ ├── base64.h │ ├── md5.cpp │ ├── md5.h │ ├── md5.hpp │ ├── nonce.cpp │ └── nonce.h │ ├── oid.cpp │ ├── oid.h │ ├── ordering.h │ ├── stringdata.h │ └── util │ ├── builder.h │ ├── embedded_builder.h │ ├── hex.h │ ├── json.cpp │ ├── json.h │ ├── misc.h │ ├── optime.h │ └── time_support.h ├── build.sh ├── client ├── command.cpp ├── command.hpp ├── commandFactory.cpp ├── commandFactory.hpp ├── edb.cpp └── edb.hpp ├── dms └── dms.cpp ├── driver └── java │ ├── build.sh │ ├── lib │ └── log4j-1.2.17.jar │ └── src │ ├── com │ ├── emeralddb │ │ ├── base │ │ │ ├── EDBMessage.java │ │ │ ├── Emeralddb.java │ │ │ ├── EmeralddbCommon.java │ │ │ └── EmeralddbConstants.java │ │ ├── exception │ │ │ ├── BaseException.java │ │ │ ├── EDBError.java │ │ │ └── EDBErrorLookup.java │ │ ├── net │ │ │ ├── ConfigOptions.java │ │ │ ├── ConnectionTCPImpl.java │ │ │ ├── IConnection.java │ │ │ └── ServerAddress.java │ │ └── util │ │ │ ├── EDBMessageHelper.java │ │ │ ├── HashAlgorithm.java │ │ │ ├── Helper.java │ │ │ ├── KetamaNodeLocator.java │ │ │ └── KetamaNodeLocatorTest.java │ └── google │ │ └── gson │ │ ├── DefaultDateTypeAdapter.java │ │ ├── ExclusionStrategy.java │ │ ├── FieldAttributes.java │ │ ├── FieldNamingPolicy.java │ │ ├── FieldNamingStrategy.java │ │ ├── Gson.java │ │ ├── GsonBuilder.java │ │ ├── InstanceCreator.java │ │ ├── JsonArray.java │ │ ├── JsonDeserializationContext.java │ │ ├── JsonDeserializer.java │ │ ├── JsonElement.java │ │ ├── JsonIOException.java │ │ ├── JsonNull.java │ │ ├── JsonObject.java │ │ ├── JsonParseException.java │ │ ├── JsonParser.java │ │ ├── JsonPrimitive.java │ │ ├── JsonSerializationContext.java │ │ ├── JsonSerializer.java │ │ ├── JsonStreamParser.java │ │ ├── JsonSyntaxException.java │ │ ├── LongSerializationPolicy.java │ │ ├── TreeTypeAdapter.java │ │ ├── TypeAdapter.java │ │ ├── TypeAdapterFactory.java │ │ ├── annotations │ │ ├── Expose.java │ │ ├── SerializedName.java │ │ ├── Since.java │ │ ├── Until.java │ │ └── package-info.java │ │ ├── internal │ │ ├── $Gson$Preconditions.java │ │ ├── $Gson$Types.java │ │ ├── ConstructorConstructor.java │ │ ├── Excluder.java │ │ ├── JsonReaderInternalAccess.java │ │ ├── LazilyParsedNumber.java │ │ ├── ObjectConstructor.java │ │ ├── Primitives.java │ │ ├── Streams.java │ │ ├── StringMap.java │ │ ├── UnsafeAllocator.java │ │ ├── bind │ │ │ ├── ArrayTypeAdapter.java │ │ │ ├── CollectionTypeAdapterFactory.java │ │ │ ├── DateTypeAdapter.java │ │ │ ├── JsonTreeReader.java │ │ │ ├── JsonTreeWriter.java │ │ │ ├── MapTypeAdapterFactory.java │ │ │ ├── ObjectTypeAdapter.java │ │ │ ├── ReflectiveTypeAdapterFactory.java │ │ │ ├── SqlDateTypeAdapter.java │ │ │ ├── TimeTypeAdapter.java │ │ │ ├── TypeAdapterRuntimeTypeWrapper.java │ │ │ └── TypeAdapters.java │ │ └── package-info.java │ │ ├── package-info.java │ │ ├── reflect │ │ ├── TypeToken.java │ │ └── package-info.java │ │ └── stream │ │ ├── JsonReader.java │ │ ├── JsonScope.java │ │ ├── JsonToken.java │ │ ├── JsonWriter.java │ │ ├── MalformedJsonException.java │ │ └── StringPool.java │ └── org │ └── bson │ ├── BSON.java │ ├── BSONCallback.java │ ├── BSONDecoder.java │ ├── BSONEncoder.java │ ├── BSONException.java │ ├── BSONLazyDecoder.java │ ├── BSONObject.java │ ├── BasicBSONCallback.java │ ├── BasicBSONDecoder.java │ ├── BasicBSONEncoder.java │ ├── BasicBSONObject.java │ ├── EmptyBSONCallback.java │ ├── NewBSONDecoder.java │ ├── Transformer.java │ ├── io │ ├── BSONByteBuffer.java │ ├── BasicOutputBuffer.java │ ├── Bits.java │ ├── OutputBuffer.java │ ├── PoolOutputBuffer.java │ ├── UTF8Encoding.java │ └── package.html │ ├── package.html │ ├── types │ ├── BSONTimestamp.java │ ├── BasicBSONList.java │ ├── Binary.java │ ├── Code.java │ ├── CodeWScope.java │ ├── MaxKey.java │ ├── MinKey.java │ ├── ObjectId.java │ ├── Symbol.java │ └── package.html │ └── util │ ├── AbstractCopyOnWriteMap.java │ ├── AbstractObjectSerializer.java │ ├── Assertions.java │ ├── Base64Codec.java │ ├── ClassAncestry.java │ ├── ClassMap.java │ ├── ClassMapBasedObjectSerializer.java │ ├── ComputingMap.java │ ├── CopyOnWriteMap.java │ ├── Function.java │ ├── JSON.java │ ├── JSONCallback.java │ ├── JSONParseException.java │ ├── JSONSerializers.java │ ├── ObjectSerializer.java │ ├── SimplePool.java │ ├── StringRangeSet.java │ ├── annotations │ ├── GuardedBy.java │ ├── Immutable.java │ ├── NotThreadSafe.java │ └── ThreadSafe.java │ └── package.html ├── include ├── core.hpp ├── dms.hpp ├── dmsRecord.hpp ├── ixmBucket.hpp ├── msg.hpp ├── ossHash.hpp ├── ossLatch.hpp ├── ossMmapFile.hpp ├── ossPrimitiveFileOp.hpp ├── ossQueue.hpp ├── ossSocket.hpp ├── ossUtil.hpp ├── pd.hpp ├── pmd.hpp ├── pmdEDU.hpp ├── pmdEDUEvent.hpp ├── pmdEDUMgr.hpp ├── pmdOptions.hpp ├── rtn.hpp └── wininc.h ├── ixm └── ixmBucket.cpp ├── msg └── msg.cpp ├── oss ├── ossHash.cpp ├── ossMmapFile.cpp ├── ossPrimitiveFileOp.cpp └── ossSocket.cpp ├── pd └── pd.cpp ├── pmd ├── pmd.cpp ├── pmdAgent.cpp ├── pmdEDU.cpp ├── pmdEDUMgr.cpp ├── pmdMain.cpp ├── pmdOptions.cpp └── pmdTcpListener.cpp ├── rtn └── rtn.cpp └── win └── emeralddb_win.cpp /.gitattributes: -------------------------------------------------------------------------------- 1 | # Auto detect text files and perform LF normalization 2 | * text=auto 3 | 4 | # Custom for Visual Studio 5 | *.cs diff=csharp 6 | *.sln merge=union 7 | *.csproj merge=union 8 | *.vbproj merge=union 9 | *.fsproj merge=union 10 | *.dbproj merge=union 11 | 12 | # Standard to msysgit 13 | *.doc diff=astextplain 14 | *.DOC diff=astextplain 15 | *.docx diff=astextplain 16 | *.DOCX diff=astextplain 17 | *.dot diff=astextplain 18 | *.DOT diff=astextplain 19 | *.pdf diff=astextplain 20 | *.PDF diff=astextplain 21 | *.rtf diff=astextplain 22 | *.RTF diff=astextplain 23 | -------------------------------------------------------------------------------- /Readme.txt: -------------------------------------------------------------------------------- 1 | EmeraldDB编译方式 2 | 3 | 1) download and extract boost 4 | 2) modify Makefile.am to use proper boost include/lib directories 5 | -------------------------------------------------------------------------------- /client/client.vcproj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangzhonnew/emeralddb/c00a1b8dbee07d0d52e5103ce13d53094f9f9276/client/client.vcproj -------------------------------------------------------------------------------- /emeralddb.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 11.00 3 | # Visual C++ Express 2010 4 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "emeralddb", "emeralddb\emeralddb.vcxproj", "{4AA4AC33-EFA2-4D6B-BA84-2E5534CBAD53}" 5 | EndProject 6 | Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "client", "client\client.vcxproj", "{BC7A7064-C7B6-4885-89B5-ACE69AF4E3F9}" 7 | EndProject 8 | Global 9 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 10 | Debug|Win32 = Debug|Win32 11 | Release|Win32 = Release|Win32 12 | EndGlobalSection 13 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 14 | {4AA4AC33-EFA2-4D6B-BA84-2E5534CBAD53}.Debug|Win32.ActiveCfg = Debug|Win32 15 | {4AA4AC33-EFA2-4D6B-BA84-2E5534CBAD53}.Debug|Win32.Build.0 = Debug|Win32 16 | {4AA4AC33-EFA2-4D6B-BA84-2E5534CBAD53}.Release|Win32.ActiveCfg = Release|Win32 17 | {4AA4AC33-EFA2-4D6B-BA84-2E5534CBAD53}.Release|Win32.Build.0 = Release|Win32 18 | {BC7A7064-C7B6-4885-89B5-ACE69AF4E3F9}.Debug|Win32.ActiveCfg = Debug|Win32 19 | {BC7A7064-C7B6-4885-89B5-ACE69AF4E3F9}.Debug|Win32.Build.0 = Debug|Win32 20 | {BC7A7064-C7B6-4885-89B5-ACE69AF4E3F9}.Release|Win32.ActiveCfg = Release|Win32 21 | {BC7A7064-C7B6-4885-89B5-ACE69AF4E3F9}.Release|Win32.Build.0 = Release|Win32 22 | EndGlobalSection 23 | GlobalSection(SolutionProperties) = preSolution 24 | HideSolutionNode = FALSE 25 | EndGlobalSection 26 | EndGlobal 27 | -------------------------------------------------------------------------------- /emeralddb/emeralddb.vcproj: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangzhonnew/emeralddb/c00a1b8dbee07d0d52e5103ce13d53094f9f9276/emeralddb/emeralddb.vcproj -------------------------------------------------------------------------------- /src/Makefile.am: -------------------------------------------------------------------------------- 1 | AUTOMAKE_OPTIONS=foreign 2 | bin_PROGRAMS=emeralddb edb 3 | emeralddb_SOURCES=\ 4 | pmd/pmdMain.cpp pmd/pmdTcpListener.cpp pmd/pmdOptions.cpp \ 5 | pmd/pmd.cpp pmd/pmdEDU.cpp pmd/pmdEDUMgr.cpp pmd/pmdAgent.cpp \ 6 | bson/src/bsonobj.cpp bson/src/util/json.cpp bson/src/oid.cpp \ 7 | bson/src/lib/base64.cpp bson/src/lib/md5.cpp bson/src/lib/nonce.cpp \ 8 | oss/ossSocket.cpp oss/ossPrimitiveFileOp.cpp oss/ossMmapFile.cpp \ 9 | oss/ossHash.cpp \ 10 | pd/pd.cpp msg/msg.cpp dms/dms.cpp rtn/rtn.cpp ixm/ixmBucket.cpp 11 | 12 | edb_SOURCES=\ 13 | client/edb.cpp client/command.cpp client/commandFactory.cpp \ 14 | bson/src/bsonobj.cpp bson/src/util/json.cpp bson/src/oid.cpp \ 15 | bson/src/lib/base64.cpp bson/src/lib/md5.cpp bson/src/lib/nonce.cpp \ 16 | oss/ossSocket.cpp oss/ossPrimitiveFileOp.cpp \ 17 | pd/pd.cpp msg/msg.cpp 18 | 19 | emeralddb_CXXFLAGS=-I../boost -Ibson/src -Iinclude -D_FILE_OFFSET_BITS=64 -ggdb -Wall -O0 20 | 21 | emeralddb_LDADD=-lpthread -lm -lboost_system -lboost_thread -lboost_program_options -lrt 22 | 23 | emeralddb_LDFLAGS=-fPIC -rdynamic -L../boost/stage/lib -pthread 24 | 25 | edb_CXXFLAGS=-I../boost -Ibson/src -Iinclude -D_FILE_OFFSET_BITS=64 -ggdb -Wall -O0 26 | edb_LDADD=-lm -lboost_system -lboost_thread -lrt 27 | edb_LDFLAGS=-fPIC -rdynamic -L../boost/stage/lib 28 | -------------------------------------------------------------------------------- /src/bson/src/bson.h: -------------------------------------------------------------------------------- 1 | /** @file bson.h 2 | BSON classes 3 | */ 4 | 5 | /* 6 | * Copyright 2009 10gen Inc. 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | bo and its helpers 23 | 24 | "BSON" stands for "binary JSON" -- ie a binary way to represent objects that 25 | would be represented in JSON (plus a few extensions useful for databases & 26 | other languages). 27 | 28 | http://www.bsonspec.org/ 29 | */ 30 | 31 | #pragma once 32 | 33 | #include "bsonassert.h" 34 | 35 | #include "bsontypes.h" 36 | #include "oid.h" 37 | #include "bsonelement.h" 38 | #include "bsonobj.h" 39 | #include "bsonmisc.h" 40 | #include "bsonobjbuilder.h" 41 | #include "bsonobjiterator.h" 42 | #include "bson-inl.h" 43 | #include "bson_db.h" -------------------------------------------------------------------------------- /src/bson/src/bson_db.h: -------------------------------------------------------------------------------- 1 | /** @file bson_db.h 2 | 3 | This file contains the implementation of BSON-related methods that are required 4 | by the MongoDB database server. 5 | 6 | Normally, for standalone BSON usage, you do not want this file - it will tend to 7 | pull in some other files from the MongoDB project. Thus, bson.h (the main file 8 | one would use) does not include this file. 9 | */ 10 | 11 | /* Copyright 2009 10gen Inc. 12 | * 13 | * Licensed under the Apache License, Version 2.0 (the "License"); 14 | * you may not use this file except in compliance with the License. 15 | * You may obtain a copy of the License at 16 | * 17 | * http://www.apache.org/licenses/LICENSE-2.0 18 | * 19 | * Unless required by applicable law or agreed to in writing, software 20 | * distributed under the License is distributed on an "AS IS" BASIS, 21 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 22 | * See the License for the specific language governing permissions and 23 | * limitations under the License. 24 | */ 25 | 26 | #pragma once 27 | 28 | #include "util/optime.h" 29 | #include "util/time_support.h" 30 | 31 | #ifndef log 32 | #define log(...) std::cerr 33 | #endif 34 | 35 | namespace bson { 36 | 37 | /** 38 | Timestamps are a special BSON datatype that is used internally for 39 | replication. Append a timestamp element to the object being ebuilt. 40 | @param time - in millis (but stored in seconds) 41 | */ 42 | inline BSONObjBuilder& BSONObjBuilder::appendTimestamp( 43 | const StringData& fieldName, unsigned long long time, unsigned int inc) { 44 | OpTime t( (unsigned) (time / 1000) , inc ); 45 | appendTimestamp( fieldName , t.asDate() ); 46 | return *this; 47 | } 48 | 49 | inline OpTime BSONElement::_opTime() const { 50 | if(type() == bson::Date || type() == Timestamp) 51 | return OpTime(*reinterpret_cast< const unsigned long long* >(value())); 52 | return OpTime(); 53 | } 54 | 55 | inline string BSONElement::_asCode() const { 56 | switch( type() ) { 57 | case bson::String: 58 | case Code: 59 | return string(valuestr(), valuestrsize()-1); 60 | case CodeWScope: 61 | return string(codeWScopeCode(), *(int*)(valuestr())-1); 62 | default: 63 | log() << "can't convert type: " << (int)(type()) << " to code" 64 | << endl; 65 | } 66 | uassert( 10062 , "not code" , 0 ); 67 | return ""; 68 | } 69 | 70 | inline BSONObjBuilder& BSONObjBuilderValueStream::operator<<( 71 | DateNowLabeler& id) { 72 | _builder->appendDate(_fieldName, jsTime()); 73 | _fieldName = 0; 74 | return *_builder; 75 | } 76 | 77 | inline BSONObjBuilder& BSONObjBuilderValueStream::operator<<( 78 | MinKeyLabeler& id) { 79 | _builder->appendMinKey(_fieldName); 80 | _fieldName = 0; 81 | return *_builder; 82 | } 83 | 84 | inline BSONObjBuilder& BSONObjBuilderValueStream::operator<<( 85 | MaxKeyLabeler& id) { 86 | _builder->appendMaxKey(_fieldName); 87 | _fieldName = 0; 88 | return *_builder; 89 | } 90 | 91 | } 92 | -------------------------------------------------------------------------------- /src/bson/src/bsonassert.h: -------------------------------------------------------------------------------- 1 | /** @file bsonassert.h 2 | BSON classes 3 | */ 4 | 5 | /* 6 | * Copyright 2009 10gen Inc. 7 | * 8 | * Licensed under the Apache License, Version 2.0 (the "License"); 9 | * you may not use this file except in compliance with the License. 10 | * You may obtain a copy of the License at 11 | * 12 | * http://www.apache.org/licenses/LICENSE-2.0 13 | * 14 | * Unless required by applicable law or agreed to in writing, software 15 | * distributed under the License is distributed on an "AS IS" BASIS, 16 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 17 | * See the License for the specific language governing permissions and 18 | * limitations under the License. 19 | */ 20 | 21 | /** 22 | Main include file for C++ BSON module when using standalone (sans MongoDB client). 23 | 24 | "BSON" stands for "binary JSON" -- ie a binary way to represent objects that 25 | would be represented in JSON (plus a few extensions useful for databases & 26 | other languages). 27 | 28 | http://www.bsonspec.org/ 29 | */ 30 | 31 | #pragma once 32 | 33 | #include 34 | #include 35 | #include 36 | #include 37 | #include 38 | 39 | #include "stringdata.h" 40 | 41 | namespace bson { 42 | 43 | using std::string; 44 | using std::stringstream; 45 | 46 | class assertion : public std::exception { 47 | public: 48 | assertion( unsigned u , const string& s ) 49 | : id( u ) , msg( s ) { 50 | stringstream ss; 51 | ss << "BsonAssertion id: " << u << " " << s; 52 | full = ss.str(); 53 | } 54 | 55 | virtual ~assertion() throw() {} 56 | 57 | virtual const char* what() const throw() { return full.c_str(); } 58 | 59 | unsigned id; 60 | string msg; 61 | string full; 62 | }; 63 | 64 | #if !defined(assert) 65 | inline void assert(bool expr) { 66 | if(!expr) { 67 | throw bson::assertion( 0 , "assertion failure in bson library" ); 68 | } 69 | } 70 | #endif 71 | #if !defined(uassert) 72 | inline void uasserted(unsigned msgid, std::string s) { 73 | throw bson::assertion( msgid , s ); 74 | } 75 | 76 | inline void uassert(unsigned msgid, std::string msg, bool expr) { 77 | if( !expr ) 78 | uasserted( msgid , msg ); 79 | } 80 | inline void msgasserted(int msgid, const char *msg) { 81 | throw bson::assertion( msgid , msg ); 82 | } 83 | inline void msgasserted(int msgid, const std::string &msg) { msgasserted(msgid, msg.c_str()); } 84 | inline void massert(unsigned msgid, std::string msg, bool expr) { 85 | if(!expr) { 86 | std::cout << "assertion failure in bson library: " << msgid << ' ' << msg << std::endl; 87 | throw bson::assertion( msgid , msg ); 88 | } 89 | } 90 | #endif 91 | } -------------------------------------------------------------------------------- /src/bson/src/bsontypes.h: -------------------------------------------------------------------------------- 1 | // bsontypes.h 2 | 3 | /* Copyright 2009 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | #include "util/misc.h" 21 | 22 | namespace bson { 23 | using namespace std; 24 | 25 | class BSONArrayBuilder; 26 | class BSONElement; 27 | class BSONObj; 28 | class BSONObjBuilder; 29 | class BSONObjBuilderValueStream; 30 | class BSONObjIterator; 31 | class Ordering; 32 | struct BSONArray; // empty subclass of BSONObj useful for overloading 33 | struct BSONElementCmpWithoutField; 34 | 35 | extern BSONObj maxKey; 36 | extern BSONObj minKey; 37 | 38 | /** 39 | the complete list of valid BSON types 40 | see also bsonspec.org 41 | */ 42 | enum BSONType { 43 | /** smaller than all other types */ 44 | MinKey=-1, 45 | /** end of object */ 46 | EOO=0, 47 | /** double precision floating point value */ 48 | NumberDouble=1, 49 | /** character string, stored in utf8 */ 50 | String=2, 51 | /** an embedded object */ 52 | Object=3, 53 | /** an embedded array */ 54 | Array=4, 55 | /** binary data */ 56 | BinData=5, 57 | /** Undefined type */ 58 | Undefined=6, 59 | /** ObjectId */ 60 | jstOID=7, 61 | /** boolean type */ 62 | Bool=8, 63 | /** date type */ 64 | Date=9, 65 | /** null type */ 66 | jstNULL=10, 67 | /** regular expression, a pattern with options */ 68 | RegEx=11, 69 | /** deprecated / will be redesigned */ 70 | DBRef=12, 71 | /** deprecated / use CodeWScope */ 72 | Code=13, 73 | /** a programming language (e.g., Python) symbol */ 74 | Symbol=14, 75 | /** javascript code that can execute on the database server, with SavedContext */ 76 | CodeWScope=15, 77 | /** 32 bit signed integer */ 78 | NumberInt = 16, 79 | /** Updated to a Date with value next OpTime on insert */ 80 | Timestamp = 17, 81 | /** 64 bit integer */ 82 | NumberLong = 18, 83 | /** max type that is not MaxKey */ 84 | JSTypeMax=18, 85 | /** larger than all other types */ 86 | MaxKey=127 87 | }; 88 | 89 | /* subtypes of BinData. 90 | bdtCustom and above are ones that the JS compiler understands, but are 91 | opaque to the database. 92 | */ 93 | enum BinDataType { 94 | BinDataGeneral=0, 95 | Function=1, 96 | ByteArrayDeprecated=2, /* use BinGeneral instead */ 97 | bdtUUID = 3, 98 | MD5Type=5, 99 | bdtCustom=128 100 | }; 101 | 102 | } 103 | 104 | -------------------------------------------------------------------------------- /src/bson/src/inline_decls.h: -------------------------------------------------------------------------------- 1 | // inline_decls.h 2 | 3 | /* Copyright 2010 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | #if defined(__GNUC__) 21 | 22 | #define NOINLINE_DECL __attribute__((noinline)) 23 | 24 | #elif defined(_MSC_VER) 25 | 26 | #define NOINLINE_DECL __declspec(noinline) 27 | 28 | #else 29 | 30 | #define NOINLINE_DECL 31 | 32 | #endif 33 | -------------------------------------------------------------------------------- /src/bson/src/lib/base64.cpp: -------------------------------------------------------------------------------- 1 | // util/base64.cpp 2 | 3 | 4 | /* Copyright 2009 10gen Inc. 5 | * 6 | * Licensed under the Apache License, Version 2.0 (the "License"); 7 | * you may not use this file except in compliance with the License. 8 | * You may obtain a copy of the License at 9 | * 10 | * http://www.apache.org/licenses/LICENSE-2.0 11 | * 12 | * Unless required by applicable law or agreed to in writing, software 13 | * distributed under the License is distributed on an "AS IS" BASIS, 14 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 15 | * See the License for the specific language governing permissions and 16 | * limitations under the License. 17 | */ 18 | 19 | #include "base64.h" 20 | #include 21 | 22 | using namespace std; 23 | 24 | namespace base64 { 25 | 26 | Alphabet alphabet; 27 | 28 | void encode( stringstream& ss , const char * data , int size ) { 29 | for ( int i=0; i>2); 35 | 36 | // byte 1 37 | unsigned char temp = ( start[0] << 4 ); 38 | if ( left == 1 ) { 39 | ss << alphabet.e(temp); 40 | break; 41 | } 42 | temp |= ( ( start[1] >> 4 ) & 0xF ); 43 | ss << alphabet.e(temp); 44 | 45 | // byte 2 46 | temp = ( start[1] & 0xF ) << 2; 47 | if ( left == 2 ) { 48 | ss << alphabet.e(temp); 49 | break; 50 | } 51 | temp |= ( ( start[2] >> 6 ) & 0x3 ); 52 | ss << alphabet.e(temp); 53 | 54 | // byte 3 55 | ss << alphabet.e(start[2] & 0x3f); 56 | } 57 | 58 | int mod = size % 3; 59 | if ( mod == 1 ) { 60 | ss << "=="; 61 | } 62 | else if ( mod == 2 ) { 63 | ss << "="; 64 | } 65 | } 66 | 67 | 68 | string encode( const char * data , int size ) { 69 | stringstream ss; 70 | encode( ss , data ,size ); 71 | return ss.str(); 72 | } 73 | 74 | string encode( const string& s ) { 75 | return encode( s.c_str() , s.size() ); 76 | } 77 | 78 | 79 | void decode( stringstream& ss , const string& s ) { 80 | assert( s.size() % 4 == 0 ); 81 | const unsigned char * data = (const unsigned char*)s.c_str(); 82 | int size = s.size(); 83 | 84 | unsigned char buf[3]; 85 | for ( int i=0; i> 4 ) & 0x3 ); 89 | buf[1] = ( ( alphabet.decode[start[1]] << 4 ) & 0xF0 ) | 90 | ( ( alphabet.decode[start[2]] >> 2 ) & 0xF ); 91 | buf[2] = ( ( alphabet.decode[start[2]] << 6 ) & 0xC0 ) | 92 | ( ( alphabet.decode[start[3]] & 0x3F ) ); 93 | 94 | int len = 3; 95 | if ( start[3] == '=' ) { 96 | len = 2; 97 | if ( start[2] == '=' ) { 98 | len = 1; 99 | } 100 | } 101 | ss.write( (const char*)buf , len ); 102 | } 103 | } 104 | 105 | string decode( const string& s ) { 106 | stringstream ss; 107 | decode( ss , s ); 108 | return ss.str(); 109 | } 110 | 111 | } 112 | 113 | -------------------------------------------------------------------------------- /src/bson/src/lib/base64.h: -------------------------------------------------------------------------------- 1 | // util/base64.h 2 | 3 | /* Copyright 2009 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | #include 23 | #include 24 | #include 25 | 26 | namespace base64 { 27 | 28 | class Alphabet { 29 | public: 30 | Alphabet() 31 | : encode((unsigned char*) 32 | "ABCDEFGHIJKLMNOPQRSTUVWXYZ" 33 | "abcdefghijklmnopqrstuvwxyz" 34 | "0123456789" 35 | "+/") 36 | , decode(new unsigned char[257]) { 37 | memset( decode.get() , 0 , 256 ); 38 | for ( int i=0; i<64; i++ ) { 39 | decode[ encode[i] ] = i; 40 | } 41 | 42 | test(); 43 | } 44 | void test() { 45 | assert( strlen( (char*)encode ) == 64 ); 46 | for ( int i=0; i<26; i++ ) 47 | assert( encode[i] == toupper( encode[i+26] ) ); 48 | } 49 | 50 | char e( int x ) { 51 | return encode[x&0x3f]; 52 | } 53 | 54 | private: 55 | const unsigned char * encode; 56 | public: 57 | boost::scoped_array decode; 58 | }; 59 | 60 | extern Alphabet alphabet; 61 | 62 | void encode( std::stringstream& ss , const char * data , int size ); 63 | std::string encode( const char * data , int size ); 64 | std::string encode( const std::string& s ); 65 | 66 | void decode( std::stringstream& ss , const std::string& s ); 67 | std::string decode( const std::string& s ); 68 | 69 | void testAlphabet(); 70 | } 71 | -------------------------------------------------------------------------------- /src/bson/src/lib/md5.hpp: -------------------------------------------------------------------------------- 1 | // md5.hpp 2 | 3 | /* Copyright 2009 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | #include "md5.h" 21 | #include 22 | #include 23 | 24 | namespace md5 { 25 | 26 | typedef unsigned char md5digest[16]; 27 | 28 | inline void md5(const void *buf, int nbytes, md5digest digest) { 29 | md5_state_t st; 30 | md5_init(&st); 31 | md5_append(&st, (const md5_byte_t *) buf, nbytes); 32 | md5_finish(&st, digest); 33 | } 34 | 35 | inline void md5(const char *str, md5digest digest) { 36 | md5(str, strlen(str), digest); 37 | } 38 | 39 | inline std::string digestToString( md5digest digest ){ 40 | static const char * letters = "0123456789abcdef"; 41 | std::stringstream ss; 42 | for ( int i=0; i<16; i++){ 43 | unsigned char c = digest[i]; 44 | ss << letters[ ( c >> 4 ) & 0xf ] << letters[ c & 0xf ]; 45 | } 46 | return ss.str(); 47 | } 48 | 49 | inline std::string md5simpledigest( const void* buf, int nbytes){ 50 | md5digest d; 51 | md5( buf, nbytes , d ); 52 | return digestToString( d ); 53 | } 54 | 55 | inline std::string md5simpledigest( std::string s ){ 56 | return md5simpledigest(s.data(), s.size()); 57 | } 58 | 59 | 60 | } // namespace md5 61 | -------------------------------------------------------------------------------- /src/bson/src/lib/nonce.cpp: -------------------------------------------------------------------------------- 1 | // nonce.cpp 2 | 3 | /* Copyright 2009 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | #ifdef _WINDOWS 18 | #define _CRT_RAND_S 19 | #endif 20 | 21 | #include "nonce.h" 22 | 23 | #ifdef _WINDOWS 24 | #include // rand_s 25 | #endif 26 | 27 | #include 28 | #include 29 | #include 30 | namespace Nonce { 31 | 32 | BOOST_STATIC_ASSERT( sizeof(nonce) == 8 ); 33 | 34 | Security::Security() { 35 | static int n; 36 | assert(++n == 1 && "Security is a singleton class"); 37 | init(); 38 | } 39 | 40 | void Security::init() { 41 | if( _initialized ) return; 42 | _initialized = true; 43 | 44 | #if defined(__linux__) || defined(__sunos__) 45 | _devrandom = new std::ifstream("/dev/urandom", std::ios::binary|std::ios::in); 46 | assert(_devrandom->is_open() && "can't open dev/urandom"); 47 | #elif defined(_WIN32) 48 | srand(time(NULL)); 49 | #else 50 | srandomdev(); 51 | #endif 52 | } 53 | 54 | nonce Security::getNonce() { 55 | static boost::mutex m; 56 | boost::mutex::scoped_lock lk(m); 57 | 58 | /* question/todo: /dev/random works on OS X. is it better 59 | to use that than random() / srandom()? 60 | */ 61 | 62 | nonce n; 63 | #if defined(__linux__) || defined(__sunos__) 64 | _devrandom->read((char*)&n, sizeof(n)); 65 | assert(!_devrandom->fail() && "devrandom failed"); 66 | #elif defined(_WIN32) 67 | unsigned a=0, b=0; 68 | assert( rand_s(&a) == 0 ); 69 | assert( rand_s(&b) == 0 ); 70 | n = (((unsigned long long)a)<<32) | b; 71 | #else 72 | n = (((unsigned long long)random())<<32) | random(); 73 | #endif 74 | return n; 75 | } 76 | unsigned getRandomNumber() { return (unsigned) security.getNonce(); } 77 | 78 | bool Security::_initialized; 79 | Security security; 80 | 81 | 82 | } // namespace mongo 83 | -------------------------------------------------------------------------------- /src/bson/src/lib/nonce.h: -------------------------------------------------------------------------------- 1 | // nonce.h 2 | 3 | /* Copyright 2009 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | #include 21 | 22 | namespace Nonce { 23 | 24 | typedef unsigned long long nonce; 25 | 26 | struct Security { 27 | Security(); 28 | 29 | nonce getNonce(); 30 | /** safe during global var initialization */ 31 | nonce getNonceInitSafe() { 32 | init(); 33 | return getNonce(); 34 | } 35 | 36 | private: 37 | std::ifstream *_devrandom; 38 | static bool _initialized; 39 | void init(); 40 | 41 | }; 42 | 43 | extern Security security; 44 | 45 | } // namespace mongo 46 | -------------------------------------------------------------------------------- /src/bson/src/ordering.h: -------------------------------------------------------------------------------- 1 | // ordering.h 2 | 3 | /* Copyright 2009 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | namespace bson { 21 | 22 | /** A precomputation of a BSON key pattern. 23 | The constructor is private to make conversion more explicit so we notice 24 | where we call make(). Over time we should push this up higher and 25 | higher. 26 | */ 27 | class Ordering { 28 | const unsigned bits; 29 | const unsigned nkeys; 30 | Ordering(unsigned b,unsigned n) : bits(b),nkeys(n) { } 31 | public: 32 | /** so, for key pattern { a : 1, b : -1 } 33 | get(0) == 1 34 | get(1) == -1 35 | */ 36 | int get(int i) const { 37 | return ((1 << i) & bits) ? -1 : 1; 38 | } 39 | 40 | // for woCompare... 41 | unsigned descending(unsigned mask) const { return bits & mask; } 42 | 43 | operator string() const { 44 | StringBuilder buf(32); 45 | for ( unsigned i=0; i 0 ? "+" : "-" ); 47 | return buf.str(); 48 | } 49 | 50 | static Ordering make(const BSONObj& obj) { 51 | unsigned b = 0; 52 | BSONObjIterator k(obj); 53 | unsigned n = 0; 54 | while( 1 ) { 55 | BSONElement e = k.next(); 56 | if( e.eoo() ) 57 | break; 58 | uassert( 13103, "too many compound keys", n <= 31 ); 59 | if( e.number() < 0 ) 60 | b |= (1 << n); 61 | n++; 62 | } 63 | return Ordering(b,n); 64 | } 65 | }; 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/bson/src/stringdata.h: -------------------------------------------------------------------------------- 1 | // stringdata.h 2 | 3 | /* Copyright 2010 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | #include 21 | #include 22 | 23 | namespace bson { 24 | 25 | using std::string; 26 | 27 | /* A StringData object wraps a 'const string&' or a 'const char*' without 28 | * copying its contents. The most common usage is as a function argument 29 | * that takes any of the two forms of strings above. Fundamentally, this 30 | * class tries go around the fact that string literals in C++ are char[N]'s. 31 | * Note that the object StringData wraps around must be alive while the 32 | * StringData is. 33 | */ 34 | 35 | class StringData { 36 | public: 37 | /** Construct a StringData, for the case where the length of 38 | * string is not known. 'c' must be a pointer to a null-terminated 39 | * string. 40 | */ 41 | StringData( const char* c ) 42 | : _data(c), _size((unsigned) strlen(c)) {} 43 | 44 | /** Construct a StringData explicitly, for the case where the length of 45 | * the string is already known. 'c' must be a pointer to a null- 46 | * terminated string, and strlenOfc must be the length that 47 | * std::strlen(c) would return, a.k.a the index of the terminator in c. 48 | */ 49 | StringData( const char* c, unsigned len ) 50 | : _data(c), _size(len) {} 51 | 52 | /** Construct a StringData, for the case of a std::string. */ 53 | StringData( const string& s ) 54 | : _data(s.c_str()), _size((unsigned) s.size()) {} 55 | 56 | // Construct a StringData explicitly, for the case of a literal whose 57 | // size is known at compile time. 58 | struct LiteralTag {}; 59 | template 60 | StringData( const char (&val)[N], LiteralTag ) 61 | : _data(&val[0]), _size(N-1) {} 62 | 63 | // accessors 64 | const char* const data() const { return _data; } 65 | const unsigned size() const { return _size; } 66 | 67 | private: 68 | const char* const _data; // is always null terminated 69 | const unsigned _size; // 'size' does not include the null terminator 70 | }; 71 | 72 | } // namespace bson 73 | -------------------------------------------------------------------------------- /src/bson/src/util/hex.h: -------------------------------------------------------------------------------- 1 | // util/hex.h 2 | 3 | /* Copyright 2009 10gen Inc. 4 | * 5 | * Licensed under the Apache License, Version 2.0 (the "License"); 6 | * you may not use this file except in compliance with the License. 7 | * You may obtain a copy of the License at 8 | * 9 | * http://www.apache.org/licenses/LICENSE-2.0 10 | * 11 | * Unless required by applicable law or agreed to in writing, software 12 | * distributed under the License is distributed on an "AS IS" BASIS, 13 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 14 | * See the License for the specific language governing permissions and 15 | * limitations under the License. 16 | */ 17 | 18 | #pragma once 19 | 20 | #include "../bsonassert.h" 21 | #include "builder.h" 22 | 23 | namespace bson { 24 | 25 | //can't use hex namespace because it conflicts with hex iostream function 26 | inline int fromHex( char c ) { 27 | if ( '0' <= c && c <= '9' ) 28 | return c - '0'; 29 | if ( 'a' <= c && c <= 'f' ) 30 | return c - 'a' + 10; 31 | if ( 'A' <= c && c <= 'F' ) 32 | return c - 'A' + 10; 33 | assert( false ); 34 | return 0xff; 35 | } 36 | inline char fromHex( const char *c ) { 37 | return (char)(( fromHex( c[ 0 ] ) << 4 ) | fromHex( c[ 1 ] )); 38 | } 39 | 40 | inline string toHex(const void* inRaw, int len) { 41 | static const char hexchars[] = "0123456789ABCDEF"; 42 | 43 | StringBuilder out; 44 | const char* in = reinterpret_cast(inRaw); 45 | for (int i=0; i> 4]; 48 | char lo = hexchars[(c & 0x0F)]; 49 | 50 | out << hi << lo; 51 | } 52 | 53 | return out.str(); 54 | } 55 | 56 | inline string toHexLower(const void* inRaw, int len) { 57 | static const char hexchars[] = "0123456789abcdef"; 58 | 59 | StringBuilder out; 60 | const char* in = reinterpret_cast(inRaw); 61 | for (int i=0; i> 4]; 64 | char lo = hexchars[(c & 0x0F)]; 65 | 66 | out << hi << lo; 67 | } 68 | 69 | return out.str(); 70 | } 71 | } 72 | -------------------------------------------------------------------------------- /src/bson/src/util/json.h: -------------------------------------------------------------------------------- 1 | /** @file json.h */ 2 | 3 | /** 4 | * Copyright (C) 2008 10gen Inc. 5 | * 6 | * This program is free software: you can redistribute it and/or modify 7 | * it under the terms of the GNU Affero General Public License, version 3, 8 | * as published by the Free Software Foundation. 9 | * 10 | * This program is distributed in the hope that it will be useful, 11 | * but WITHOUT ANY WARRANTY; without even the implied warranty of 12 | * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 13 | * GNU Affero General Public License for more details. 14 | * 15 | * You should have received a copy of the GNU Affero General Public License 16 | * along with this program. If not, see . 17 | */ 18 | 19 | #pragma once 20 | 21 | #include "../bson.h" 22 | 23 | namespace bson { 24 | 25 | /** Create a BSONObj from a JSON string. In addition 26 | to the JSON extensions extensions described here 27 | , 28 | this function accepts certain unquoted field names and allows single quotes 29 | to optionally be used when specifying field names and string values instead 30 | of double quotes. JSON unicode escape sequences (of the form \uXXXX) are 31 | converted to utf8. 32 | \throws MsgAssertionException if parsing fails. The message included with 33 | this assertion includes a rough indication of where parsing failed. 34 | */ 35 | BSONObj fromjson(const string &str); 36 | 37 | /** len will be size of JSON object in text chars. */ 38 | BSONObj fromjson(const char *str, int* len=NULL); 39 | 40 | } // namespace mongo 41 | -------------------------------------------------------------------------------- /src/bson/src/util/misc.h: -------------------------------------------------------------------------------- 1 | /* @file misc.h 2 | */ 3 | 4 | /* 5 | * Copyright 2009 10gen Inc. 6 | * 7 | * Licensed under the Apache License, Version 2.0 (the "License"); 8 | * you may not use this file except in compliance with the License. 9 | * You may obtain a copy of the License at 10 | * 11 | * http://www.apache.org/licenses/LICENSE-2.0 12 | * 13 | * Unless required by applicable law or agreed to in writing, software 14 | * distributed under the License is distributed on an "AS IS" BASIS, 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 16 | * See the License for the specific language governing permissions and 17 | * limitations under the License. 18 | */ 19 | 20 | #pragma once 21 | 22 | #include 23 | 24 | namespace bson { 25 | 26 | using namespace std; 27 | 28 | inline void time_t_to_String(time_t t, char *buf) { 29 | #if defined(_WIN32) 30 | ctime_s(buf, 32, &t); 31 | #else 32 | ctime_r(&t, buf); 33 | #endif 34 | buf[24] = 0; // don't want the \n 35 | } 36 | 37 | inline string time_t_to_String(time_t t = time(0) ) { 38 | char buf[64]; 39 | #if defined(_WIN32) 40 | ctime_s(buf, sizeof(buf), &t); 41 | #else 42 | ctime_r(&t, buf); 43 | #endif 44 | buf[24] = 0; // don't want the \n 45 | return buf; 46 | } 47 | 48 | inline string time_t_to_String_no_year(time_t t) { 49 | char buf[64]; 50 | #if defined(_WIN32) 51 | ctime_s(buf, sizeof(buf), &t); 52 | #else 53 | ctime_r(&t, buf); 54 | #endif 55 | buf[19] = 0; 56 | return buf; 57 | } 58 | 59 | inline string time_t_to_String_short(time_t t) { 60 | char buf[64]; 61 | #if defined(_WIN32) 62 | ctime_s(buf, sizeof(buf), &t); 63 | #else 64 | ctime_r(&t, buf); 65 | #endif 66 | buf[19] = 0; 67 | if( buf[0] && buf[1] && buf[2] && buf[3] ) 68 | return buf + 4; // skip day of week 69 | return buf; 70 | } 71 | 72 | struct Date_t { 73 | // TODO: make signed (and look for related TODO's) 74 | unsigned long long millis; 75 | Date_t(): millis(0) {} 76 | Date_t(unsigned long long m): millis(m) {} 77 | operator unsigned long long&() { return millis; } 78 | operator const unsigned long long&() const { return millis; } 79 | string toString() const { 80 | char buf[64]; 81 | time_t_to_String(millis/1000, buf); 82 | return buf; 83 | } 84 | }; 85 | 86 | // Like strlen, but only scans up to n bytes. 87 | // Returns -1 if no '0' found. 88 | inline int strnlen( const char *s, int n ) { 89 | for( int i = 0; i < n; ++i ) 90 | if ( !s[ i ] ) 91 | return i; 92 | return -1; 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/build.sh: -------------------------------------------------------------------------------- 1 | ################################# 2 | # Build script for EmeraldDB # 3 | ################################# 4 | #!/bin/sh 5 | rm configure.in 6 | autoscan 7 | cp configure.in.bak configure.in 8 | aclocal 9 | autoconf 10 | autoheader 11 | automake --add-missing 12 | ./configure CXXFLAGS= CFLAGS= 13 | make 14 | -------------------------------------------------------------------------------- /src/client/commandFactory.cpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | Copyright (C) 2013 SequoiaDB Software Inc. 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU Affero General Public License, version 3, 6 | as published by the Free Software Foundation. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU Affero General Public License for more details. 12 | 13 | You should have received a copy of the GNU Affero General Public License 14 | along with this program. If not, see . 15 | *******************************************************************************/ 16 | #include "commandFactory.hpp" 17 | 18 | CommandFactory::CommandFactory() 19 | { 20 | addCommand(); 21 | } 22 | 23 | ICommand * CommandFactory::getCommandProcesser(const char * pCmd) 24 | { 25 | ICommand * pProcessor = NULL; 26 | do { 27 | COMMAND_MAP::iterator iter; 28 | iter = _cmdMap.find(pCmd); 29 | if( iter != _cmdMap.end() ) 30 | { 31 | pProcessor = iter->second; 32 | } 33 | }while(0); 34 | return pProcessor; 35 | } 36 | 37 | -------------------------------------------------------------------------------- /src/client/commandFactory.hpp: -------------------------------------------------------------------------------- 1 | /****************************************************************************** 2 | Copyright (C) 2013 SequoiaDB Software Inc. 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU Affero General Public License, version 3, 6 | as published by the Free Software Foundation. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU Affero General Public License for more details. 12 | 13 | You should have received a copy of the GNU Affero General Public License 14 | along with this program. If not, see . 15 | *******************************************************************************/ 16 | #ifndef _COMMAND_FACTORY_HPP_ 17 | #define _COMMAND_FACTORY_HPP_ 18 | 19 | #include "command.hpp" 20 | #define COMMAND_BEGIN void CommandFactory::addCommand() { 21 | #define COMMAND_END } 22 | #define COMMAND_ADD(cmdName,cmdClass) { \ 23 | ICommand* pObj = new cmdClass(); \ 24 | std::string str = cmdName; \ 25 | _cmdMap.insert(COMMAND_MAP::value_type(str,pObj)); \ 26 | } \ 27 | 28 | class CommandFactory { 29 | typedef std::map COMMAND_MAP; 30 | public: 31 | CommandFactory(); 32 | ~CommandFactory(){} 33 | void addCommand(); 34 | ICommand * getCommandProcesser(const char * pcmd); 35 | private: 36 | COMMAND_MAP _cmdMap; 37 | }; 38 | 39 | #endif 40 | -------------------------------------------------------------------------------- /src/client/edb.hpp: -------------------------------------------------------------------------------- 1 | /******************************************************************************* 2 | Copyright (C) 2013 SequoiaDB Software Inc. 3 | 4 | This program is free software: you can redistribute it and/or modify 5 | it under the terms of the GNU Affero General Public License, version 3, 6 | as published by the Free Software Foundation. 7 | 8 | This program is distributed in the hope that it will be useful, 9 | but WITHOUT ANY WARRANTY; without even the implied warranty of 10 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 11 | GNU Affero General Public License for more details. 12 | 13 | You should have received a copy of the GNU Affero General Public License 14 | along with this program. If not, see . 15 | *******************************************************************************/ 16 | #ifndef _EDB_HPP_ 17 | #define _EDB_HPP_ 18 | 19 | #include "core.hpp" 20 | #include "ossSocket.hpp" 21 | #include "commandFactory.hpp" 22 | const int CMD_BUFFER_SIZE = 512; 23 | class Edb { 24 | public: 25 | Edb(){} 26 | ~Edb(){}; 27 | public: 28 | void start(void); 29 | protected: 30 | void prompt(void); 31 | private: 32 | void split(const std::string &text, char delim, std::vector &result); 33 | char* readLine(char *p, int length); 34 | int readInput(const char *pPrompt, int numIndent); 35 | private: 36 | ossSocket _sock; 37 | CommandFactory _cmdFactory; 38 | char _cmdBuffer[CMD_BUFFER_SIZE]; 39 | }; 40 | 41 | 42 | #endif 43 | -------------------------------------------------------------------------------- /src/driver/java/build.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | # define compile 4 | JAVA_HOME=../../../java/jdk_linux64 5 | JAVAC=$JAVA_HOME/bin/javac 6 | JAR=$JAVA_HOME/bin/jar 7 | 8 | #define source directory 9 | SOURCE_DIR=./src 10 | 11 | #define bin directory 12 | BIN_DIR=./bin 13 | 14 | # define target directory 15 | TARGET_DIR=../../../bin 16 | 17 | if [ ! -d $BIN_DIR ]; then 18 | mkdir $BIN_DIR 19 | fi 20 | 21 | if [ ! -d $TARGET_DIR ]; then 22 | mkdir $TARGET_DIR 23 | fi 24 | 25 | # delete all .class file 26 | find . -name "*.class" |xargs rm -rf 27 | 28 | $JAVAC `find $SOURCE_DIR -name "*.java" -print` -d $BIN_DIR 29 | 30 | cd $BIN_DIR 31 | 32 | l=`find ./ -name "*.class" -print | sed 's/^..//'` 33 | ../$JAR -cf ../$TARGET_DIR/emeralddb.jar $l 34 | cd .. 35 | 36 | # clean 37 | find ./ -name "*.class" | xargs rm -rf 38 | rm -rf $BIN_DIR 39 | -------------------------------------------------------------------------------- /src/driver/java/lib/log4j-1.2.17.jar: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/wangzhonnew/emeralddb/c00a1b8dbee07d0d52e5103ce13d53094f9f9276/src/driver/java/lib/log4j-1.2.17.jar -------------------------------------------------------------------------------- /src/driver/java/src/com/emeralddb/exception/BaseException.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 SequoiaDB Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.emeralddb.exception; 17 | 18 | import com.emeralddb.base.EmeralddbConstants; 19 | 20 | /** 21 | * @author Jacky Zhang 22 | * 23 | */ 24 | public class BaseException extends RuntimeException { 25 | 26 | /** 27 | * 28 | */ 29 | private static final long serialVersionUID = -6115487863398926195L; 30 | 31 | private EDBError error; 32 | private String infos = ""; 33 | 34 | /** 35 | * @param errorType 36 | * @throws Exception 37 | */ 38 | public BaseException(String errorType, Object... info) { 39 | error = new EDBError(); 40 | error.setErrorType(errorType); 41 | 42 | if (info != null) { 43 | for (Object obj : info) 44 | infos += (obj + " "); 45 | } else { 46 | infos = "no more exception info"; 47 | } 48 | try { 49 | error.setErrorCode(EDBErrorLookup.getErrorCodeByType(errorType)); 50 | error.setErrorDescription(EDBErrorLookup 51 | .getErrorDescriptionByType(errorType) + "\n Exception Detail:" + infos); 52 | } catch (Exception e) { 53 | error.setErrorCode(0); 54 | error.setErrorDescription(EmeralddbConstants.UNKNOWN_DESC + "\n Exception Detail:" 55 | + infos); 56 | } 57 | } 58 | 59 | /** 60 | * 61 | * @param errorCode 62 | * @throws Exception 63 | */ 64 | public BaseException(int errorCode, Object... info) { 65 | error = new EDBError(); 66 | error.setErrorCode(errorCode); 67 | if (info != null) { 68 | for (Object obj : info) 69 | infos += (obj + " "); 70 | } else { 71 | infos = "no more exception info"; 72 | } 73 | try { 74 | error.setErrorType(EDBErrorLookup.getErrorTypeByCode(errorCode)); 75 | error.setErrorDescription(EDBErrorLookup 76 | .getErrorDescriptionByCode(errorCode) + "\n Exception Detail:" + infos); 77 | } catch (Exception e) { 78 | error.setErrorType(EmeralddbConstants.UNKNOWN_DESC); 79 | error.setErrorDescription(EmeralddbConstants.UNKNOWN_DESC + "\n Exception Detail:" 80 | + infos); 81 | } 82 | } 83 | 84 | @Override 85 | public String getMessage() { 86 | return error.getErrorDescription(); 87 | } 88 | 89 | public String getErrorType() { 90 | return error.getErrorType(); 91 | } 92 | 93 | public int getErrorCode() { 94 | return error.getErrorCode(); 95 | } 96 | } 97 | -------------------------------------------------------------------------------- /src/driver/java/src/com/emeralddb/exception/EDBError.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 SequoiaDB Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.emeralddb.exception; 17 | 18 | /** 19 | * @author Jacky Zhang 20 | * 21 | */ 22 | 23 | public class EDBError { 24 | private String errorType; 25 | private int errorCode; 26 | private String errorDescription; 27 | 28 | /** 29 | * @return 30 | */ 31 | public String getErrorType() { 32 | return errorType; 33 | } 34 | 35 | /** 36 | * @param errorType 37 | */ 38 | public void setErrorType(String errorType) { 39 | this.errorType = errorType; 40 | } 41 | 42 | /** 43 | * @return 44 | */ 45 | public int getErrorCode() { 46 | return errorCode; 47 | } 48 | 49 | /** 50 | * @param errorCode 51 | */ 52 | public void setErrorCode(int errorCode) { 53 | this.errorCode = errorCode; 54 | } 55 | 56 | /** 57 | * @return 58 | */ 59 | public String getErrorDescription() { 60 | return errorDescription; 61 | } 62 | 63 | /** 64 | * @param errorDescription 65 | */ 66 | public void setErrorDescription(String errorDescription) { 67 | this.errorDescription = errorDescription; 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/driver/java/src/com/emeralddb/net/IConnection.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 SequoiaDB Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.emeralddb.net; 17 | 18 | import com.emeralddb.exception.BaseException; 19 | /** 20 | * @author Jacky Zhang 21 | * 22 | */ 23 | public interface IConnection { 24 | public void initialize() throws BaseException; 25 | public void close(); 26 | public void changeConfigOptions(ConfigOptions opts) throws BaseException; 27 | 28 | public long sendMessage(byte[] msg) throws BaseException; 29 | 30 | public byte[] receiveMessage() throws BaseException; 31 | 32 | } 33 | -------------------------------------------------------------------------------- /src/driver/java/src/com/emeralddb/net/ServerAddress.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 SequoiaDB Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.emeralddb.net; 17 | 18 | import java.net.InetAddress; 19 | import java.net.InetSocketAddress; 20 | import java.net.UnknownHostException; 21 | 22 | import com.emeralddb.exception.BaseException; 23 | 24 | /** 25 | * @author Jacky Zhang 26 | * 27 | */ 28 | public class ServerAddress { 29 | private final static String DEFAULT_HOST = "127.0.0.1"; 30 | private final static int DEFAULT_PORT = 48123; 31 | private InetSocketAddress hostAddress; 32 | private String host; 33 | private int port; 34 | 35 | /** 36 | * @return 37 | */ 38 | public InetSocketAddress getHostAddress() { 39 | return hostAddress; 40 | } 41 | 42 | /** 43 | * @return 44 | */ 45 | public String getHost() { 46 | return host; 47 | } 48 | 49 | /** 50 | * @return 51 | */ 52 | public int getPort() { 53 | return port; 54 | } 55 | 56 | /** 57 | * 58 | */ 59 | public ServerAddress() { 60 | this(new InetSocketAddress(DEFAULT_HOST, DEFAULT_PORT)); 61 | } 62 | 63 | /** 64 | * @param host 65 | * @param port 66 | * @throws UnknownHostException 67 | */ 68 | public ServerAddress(String host, int port) throws UnknownHostException { 69 | hostAddress = new InetSocketAddress(InetAddress.getByName(host).toString().split("/")[1], port); 70 | this.host = host; 71 | this.port = port; 72 | } 73 | 74 | /** 75 | * @param host 76 | * @throws UnknownHostException 77 | */ 78 | public ServerAddress(String host) throws UnknownHostException { 79 | if (host.indexOf(":") > 0) { 80 | String[] tmp = host.split(":"); 81 | this.host = tmp[0].trim(); 82 | try { 83 | this.host = InetAddress.getByName(this.host).toString().split("/")[1]; 84 | } catch (Exception e) { 85 | throw new BaseException("SDB_INVALIDARG"); 86 | } 87 | this.port = Integer.parseInt(tmp[1].trim()); 88 | } else { 89 | this.host = host; 90 | this.port = DEFAULT_PORT; 91 | } 92 | hostAddress = new InetSocketAddress(this.host, this.port); 93 | } 94 | 95 | /** 96 | * @param addr 97 | */ 98 | public ServerAddress(InetAddress addr) { 99 | this(new InetSocketAddress(addr, DEFAULT_PORT)); 100 | } 101 | 102 | /** 103 | * @param addr 104 | * @param port 105 | */ 106 | public ServerAddress(InetAddress addr, int port) { 107 | this(new InetSocketAddress(addr, port)); 108 | } 109 | 110 | /** 111 | * @param addr 112 | */ 113 | public ServerAddress(InetSocketAddress addr) { 114 | hostAddress = addr; 115 | host = addr.getHostName(); 116 | port = addr.getPort(); 117 | } 118 | } 119 | -------------------------------------------------------------------------------- /src/driver/java/src/com/emeralddb/util/HashAlgorithm.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 SequoiaDB Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.emeralddb.util; 17 | 18 | import java.io.UnsupportedEncodingException; 19 | import java.security.MessageDigest; 20 | import java.security.NoSuchAlgorithmException; 21 | /*** 22 | * 23 | * @author zhouzhengle 24 | * 25 | */ 26 | public enum HashAlgorithm { 27 | /*** 28 | * MD5-based hash algorithm used by ketama. 29 | */ 30 | KETAMA_HASH; 31 | 32 | public long hash( byte[] digest, int nTime ) { 33 | long rv = ( (long) (digest[3 + nTime*4] & 0xFF) << 24 ) 34 | | ( (long) (digest[2 + nTime*4] & 0xFF ) << 16 ) 35 | | ( (long) (digest[1 + nTime*4] & 0xFF) << 8 ) 36 | | (digest[0 + nTime*4] & 0xFF); 37 | return rv & 0xFFFFFFFFL; 38 | } 39 | 40 | /*** 41 | * Get the md5 of the given key. 42 | */ 43 | public byte[] md5(String k) { 44 | MessageDigest md5; 45 | try { 46 | md5 = MessageDigest.getInstance("MD5"); 47 | } catch( NoSuchAlgorithmException e ) { 48 | throw new RuntimeException("MD5 not supported", e); 49 | } 50 | 51 | md5.reset(); 52 | byte[] keyBytes = null; 53 | try { 54 | keyBytes = k.getBytes("UTF-8"); 55 | } catch( UnsupportedEncodingException e ) { 56 | throw new RuntimeException("Unknown string :" + k, e); 57 | } 58 | 59 | md5.update(keyBytes); 60 | return md5.digest(); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/driver/java/src/com/emeralddb/util/KetamaNodeLocator.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 SequoiaDB Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.emeralddb.util; 17 | 18 | import java.util.List; 19 | import java.util.SortedMap; 20 | import java.util.TreeMap; 21 | import com.emeralddb.net.ServerAddress; 22 | public final class KetamaNodeLocator { 23 | private TreeMap _ketamaNodes; 24 | private HashAlgorithm _hashAlg; 25 | private int _numReps = 160; 26 | 27 | public KetamaNodeLocator(List nodeList, HashAlgorithm alg, int nodeCopies) { 28 | _hashAlg = alg; 29 | _ketamaNodes = new TreeMap(); 30 | 31 | _numReps = nodeCopies; 32 | 33 | for(ServerAddress node : nodeList) { 34 | for(int i=0; i<_numReps/4; i++) { 35 | byte[] digest = _hashAlg.md5(node.getHost() + ":" + node.getPort() + i); 36 | for(int h=0; h<4; h++) { 37 | long m = _hashAlg.hash(digest,h); 38 | _ketamaNodes.put(m, node); 39 | } 40 | } 41 | } 42 | } 43 | 44 | public ServerAddress getPrimary(final String str) { 45 | byte[] digest = _hashAlg.md5(str); 46 | ServerAddress rv = getNodeForKey(_hashAlg.hash(digest, 0)); 47 | return rv; 48 | } 49 | 50 | ServerAddress getNodeForKey(long hash) { 51 | final ServerAddress rv; 52 | Long key = hash; 53 | if(_ketamaNodes.isEmpty()) { 54 | return null; 55 | } 56 | if(!_ketamaNodes.containsKey(key)) { 57 | SortedMap tailMap = _ketamaNodes.tailMap(key); 58 | if(tailMap.isEmpty()) { 59 | key = _ketamaNodes.firstKey(); 60 | } else { 61 | key = tailMap.firstKey(); 62 | } 63 | } 64 | rv = _ketamaNodes.get(key); 65 | return rv; 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/driver/java/src/com/emeralddb/util/KetamaNodeLocatorTest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Copyright (C) 2012 SequoiaDB Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.emeralddb.util; 17 | 18 | import java.net.UnknownHostException; 19 | import java.util.ArrayList; 20 | import java.util.HashMap; 21 | import java.util.List; 22 | import java.util.Map; 23 | import java.util.Random; 24 | 25 | import com.emeralddb.net.ServerAddress; 26 | 27 | public class KetamaNodeLocatorTest { 28 | static Random ran = new Random(); 29 | 30 | private static final Integer EXE_TIMES = 100000; 31 | private static final Integer NODE_COUNT = 5; 32 | private static final Integer VIRTUAL_NODE_COUNT = 160; 33 | 34 | public static void main(String [] args) { 35 | KetamaNodeLocatorTest test = new KetamaNodeLocatorTest(); 36 | 37 | Map nodeRecord = new HashMap(); 38 | 39 | List all = test.getServerAddress(NODE_COUNT); 40 | List allKeys = test.getAllString(); 41 | KetamaNodeLocator locator = new KetamaNodeLocator(all, HashAlgorithm.KETAMA_HASH,VIRTUAL_NODE_COUNT ); 42 | 43 | for(String key : allKeys) { 44 | ServerAddress sa = locator.getPrimary(key); 45 | Integer times = nodeRecord.get(sa); 46 | if(times == null) { 47 | nodeRecord.put(sa, 1); 48 | } else { 49 | nodeRecord.put(sa, times+1); 50 | } 51 | } 52 | 53 | System.out.println("Nodes count: " + NODE_COUNT + ", Keys count: " + EXE_TIMES + ", Normal percent : " + (float)100/NODE_COUNT + "%"); 54 | System.out.println("-------------------------------boundary--------"); 55 | for(Map.Entry entry : nodeRecord.entrySet()) { 56 | System.out.println("Node name:" + entry.getKey().getPort() + "-Times:" + entry.getValue() + " - Percent: " + (float)entry.getValue()/EXE_TIMES*100 + "%"); 57 | } 58 | } 59 | 60 | private List getAllString() { 61 | List allStrings = new ArrayList(EXE_TIMES); 62 | for(int i=0; i getServerAddress(int nodeCount) { 77 | try { 78 | List nodes = new ArrayList(); 79 | ServerAddress sa = new ServerAddress("192.168.20.107", 48123); 80 | nodes.add(sa); 81 | sa = new ServerAddress("192.168.20.107", 48124); 82 | nodes.add(sa); 83 | sa = new ServerAddress("192.168.20.107", 48125); 84 | nodes.add(sa); 85 | sa = new ServerAddress("192.168.20.107", 48126); 86 | nodes.add(sa); 87 | sa = new ServerAddress("192.168.20.107", 48127); 88 | nodes.add(sa); 89 | return nodes; 90 | } catch(UnknownHostException e ) { 91 | return null; 92 | } 93 | } 94 | } 95 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/FieldNamingStrategy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | import java.lang.reflect.Field; 20 | 21 | /** 22 | * A mechanism for providing custom field naming in Gson. This allows the client code to translate 23 | * field names into a particular convention that is not supported as a normal Java field 24 | * declaration rules. For example, Java does not support "-" characters in a field name. 25 | * 26 | * @author Inderjeet Singh 27 | * @author Joel Leitch 28 | * @since 1.3 29 | */ 30 | public interface FieldNamingStrategy { 31 | 32 | /** 33 | * Translates the field name into its JSON field name representation. 34 | * 35 | * @param f the field object that we are translating 36 | * @return the translated field name. 37 | * @since 1.3 38 | */ 39 | public String translateName(Field f); 40 | } 41 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/JsonDeserializationContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | import java.lang.reflect.Type; 20 | 21 | /** 22 | * Context for deserialization that is passed to a custom deserializer during invocation of its 23 | * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)} 24 | * method. 25 | * 26 | * @author Inderjeet Singh 27 | * @author Joel Leitch 28 | */ 29 | public interface JsonDeserializationContext { 30 | 31 | /** 32 | * Invokes default deserialization on the specified object. It should never be invoked on 33 | * the element received as a parameter of the 34 | * {@link JsonDeserializer#deserialize(JsonElement, Type, JsonDeserializationContext)} method. Doing 35 | * so will result in an infinite loop since Gson will in-turn call the custom deserializer again. 36 | * 37 | * @param json the parse tree. 38 | * @param typeOfT type of the expected return value. 39 | * @param The type of the deserialized object. 40 | * @return An object of type typeOfT. 41 | * @throws JsonParseException if the parse tree does not contain expected data. 42 | */ 43 | public T deserialize(JsonElement json, Type typeOfT) throws JsonParseException; 44 | } -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/JsonIOException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson; 17 | 18 | /** 19 | * This exception is raised when Gson was unable to read an input stream 20 | * or write to one. 21 | * 22 | * @author Inderjeet Singh 23 | * @author Joel Leitch 24 | */ 25 | public final class JsonIOException extends JsonParseException { 26 | private static final long serialVersionUID = 1L; 27 | 28 | public JsonIOException(String msg) { 29 | super(msg); 30 | } 31 | 32 | public JsonIOException(String msg, Throwable cause) { 33 | super(msg, cause); 34 | } 35 | 36 | /** 37 | * Creates exception with the specified cause. Consider using 38 | * {@link #JsonIOException(String, Throwable)} instead if you can describe what happened. 39 | * 40 | * @param cause root exception that caused this exception to be thrown. 41 | */ 42 | public JsonIOException(Throwable cause) { 43 | super(cause); 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/JsonNull.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | /** 20 | * A class representing a Json {@code null} value. 21 | * 22 | * @author Inderjeet Singh 23 | * @author Joel Leitch 24 | * @since 1.2 25 | */ 26 | public final class JsonNull extends JsonElement { 27 | /** 28 | * singleton for JsonNull 29 | * 30 | * @since 1.8 31 | */ 32 | public static final JsonNull INSTANCE = new JsonNull(); 33 | 34 | /** 35 | * Creates a new JsonNull object. 36 | * Deprecated since Gson version 1.8. Use {@link #INSTANCE} instead 37 | */ 38 | @Deprecated 39 | public JsonNull() { 40 | // Do nothing 41 | } 42 | 43 | @Override public JsonNull deepCopy() { 44 | return INSTANCE; 45 | } 46 | 47 | /** 48 | * All instances of JsonNull have the same hash code since they are indistinguishable 49 | */ 50 | @Override 51 | public int hashCode() { 52 | return JsonNull.class.hashCode(); 53 | } 54 | 55 | /** 56 | * All instances of JsonNull are the same 57 | */ 58 | @Override 59 | public boolean equals(Object other) { 60 | return this == other || other instanceof JsonNull; 61 | } 62 | } 63 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/JsonParseException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | /** 20 | * This exception is raised if there is a serious issue that occurs during parsing of a Json 21 | * string. One of the main usages for this class is for the Gson infrastructure. If the incoming 22 | * Json is bad/malicious, an instance of this exception is raised. 23 | * 24 | *

This exception is a {@link RuntimeException} because it is exposed to the client. Using a 25 | * {@link RuntimeException} avoids bad coding practices on the client side where they catch the 26 | * exception and do nothing. It is often the case that you want to blow up if there is a parsing 27 | * error (i.e. often clients do not know how to recover from a {@link JsonParseException}.

28 | * 29 | * @author Inderjeet Singh 30 | * @author Joel Leitch 31 | */ 32 | public class JsonParseException extends RuntimeException { 33 | static final long serialVersionUID = -4086729973971783390L; 34 | 35 | /** 36 | * Creates exception with the specified message. If you are wrapping another exception, consider 37 | * using {@link #JsonParseException(String, Throwable)} instead. 38 | * 39 | * @param msg error message describing a possible cause of this exception. 40 | */ 41 | public JsonParseException(String msg) { 42 | super(msg); 43 | } 44 | 45 | /** 46 | * Creates exception with the specified message and cause. 47 | * 48 | * @param msg error message describing what happened. 49 | * @param cause root exception that caused this exception to be thrown. 50 | */ 51 | public JsonParseException(String msg, Throwable cause) { 52 | super(msg, cause); 53 | } 54 | 55 | /** 56 | * Creates exception with the specified cause. Consider using 57 | * {@link #JsonParseException(String, Throwable)} instead if you can describe what happened. 58 | * 59 | * @param cause root exception that caused this exception to be thrown. 60 | */ 61 | public JsonParseException(Throwable cause) { 62 | super(cause); 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/JsonParser.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson; 17 | 18 | import java.io.IOException; 19 | import java.io.Reader; 20 | import java.io.StringReader; 21 | 22 | import com.google.gson.internal.Streams; 23 | import com.google.gson.stream.JsonReader; 24 | import com.google.gson.stream.JsonToken; 25 | import com.google.gson.stream.MalformedJsonException; 26 | 27 | /** 28 | * A parser to parse Json into a parse tree of {@link JsonElement}s 29 | * 30 | * @author Inderjeet Singh 31 | * @author Joel Leitch 32 | * @since 1.3 33 | */ 34 | public final class JsonParser { 35 | 36 | /** 37 | * Parses the specified JSON string into a parse tree 38 | * 39 | * @param json JSON text 40 | * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON 41 | * @throws JsonParseException if the specified text is not valid JSON 42 | * @since 1.3 43 | */ 44 | public JsonElement parse(String json) throws JsonSyntaxException { 45 | return parse(new StringReader(json)); 46 | } 47 | 48 | /** 49 | * Parses the specified JSON string into a parse tree 50 | * 51 | * @param json JSON text 52 | * @return a parse tree of {@link JsonElement}s corresponding to the specified JSON 53 | * @throws JsonParseException if the specified text is not valid JSON 54 | * @since 1.3 55 | */ 56 | public JsonElement parse(Reader json) throws JsonIOException, JsonSyntaxException { 57 | try { 58 | JsonReader jsonReader = new JsonReader(json); 59 | JsonElement element = parse(jsonReader); 60 | if (!element.isJsonNull() && jsonReader.peek() != JsonToken.END_DOCUMENT) { 61 | throw new JsonSyntaxException("Did not consume the entire document."); 62 | } 63 | return element; 64 | } catch (MalformedJsonException e) { 65 | throw new JsonSyntaxException(e); 66 | } catch (IOException e) { 67 | throw new JsonIOException(e); 68 | } catch (NumberFormatException e) { 69 | throw new JsonSyntaxException(e); 70 | } 71 | } 72 | 73 | /** 74 | * Returns the next value from the JSON stream as a parse tree. 75 | * 76 | * @throws JsonParseException if there is an IOException or if the specified 77 | * text is not valid JSON 78 | * @since 1.6 79 | */ 80 | public JsonElement parse(JsonReader json) throws JsonIOException, JsonSyntaxException { 81 | boolean lenient = json.isLenient(); 82 | json.setLenient(true); 83 | try { 84 | return Streams.parse(json); 85 | } catch (StackOverflowError e) { 86 | throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); 87 | } catch (OutOfMemoryError e) { 88 | throw new JsonParseException("Failed parsing JSON source: " + json + " to Json", e); 89 | } finally { 90 | json.setLenient(lenient); 91 | } 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/JsonSerializationContext.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | import java.lang.reflect.Type; 20 | 21 | /** 22 | * Context for serialization that is passed to a custom serializer during invocation of its 23 | * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. 24 | * 25 | * @author Inderjeet Singh 26 | * @author Joel Leitch 27 | */ 28 | public interface JsonSerializationContext { 29 | 30 | /** 31 | * Invokes default serialization on the specified object. 32 | * 33 | * @param src the object that needs to be serialized. 34 | * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}. 35 | */ 36 | public JsonElement serialize(Object src); 37 | 38 | /** 39 | * Invokes default serialization on the specified object passing the specific type information. 40 | * It should never be invoked on the element received as a parameter of the 41 | * {@link JsonSerializer#serialize(Object, Type, JsonSerializationContext)} method. Doing 42 | * so will result in an infinite loop since Gson will in-turn call the custom serializer again. 43 | * 44 | * @param src the object that needs to be serialized. 45 | * @param typeOfSrc the actual genericized type of src object. 46 | * @return a tree of {@link JsonElement}s corresponding to the serialized form of {@code src}. 47 | */ 48 | public JsonElement serialize(Object src, Type typeOfSrc); 49 | } 50 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/JsonSyntaxException.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2010 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson; 17 | 18 | /** 19 | * This exception is raised when Gson attempts to read (or write) a malformed 20 | * JSON element. 21 | * 22 | * @author Inderjeet Singh 23 | * @author Joel Leitch 24 | */ 25 | public final class JsonSyntaxException extends JsonParseException { 26 | 27 | private static final long serialVersionUID = 1L; 28 | 29 | public JsonSyntaxException(String msg) { 30 | super(msg); 31 | } 32 | 33 | public JsonSyntaxException(String msg, Throwable cause) { 34 | super(msg, cause); 35 | } 36 | 37 | /** 38 | * Creates exception with the specified cause. Consider using 39 | * {@link #JsonSyntaxException(String, Throwable)} instead if you can 40 | * describe what actually happened. 41 | * 42 | * @param cause root exception that caused this exception to be thrown. 43 | */ 44 | public JsonSyntaxException(Throwable cause) { 45 | super(cause); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/LongSerializationPolicy.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2009 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson; 18 | 19 | /** 20 | * Defines the expected format for a {@code long} or {@code Long} type when its serialized. 21 | * 22 | * @since 1.3 23 | * 24 | * @author Inderjeet Singh 25 | * @author Joel Leitch 26 | */ 27 | public enum LongSerializationPolicy { 28 | /** 29 | * This is the "default" serialization policy that will output a {@code long} object as a JSON 30 | * number. For example, assume an object has a long field named "f" then the serialized output 31 | * would be: 32 | * {@code {"f":123}}. 33 | */ 34 | DEFAULT() { 35 | public JsonElement serialize(Long value) { 36 | return new JsonPrimitive(value); 37 | } 38 | }, 39 | 40 | /** 41 | * Serializes a long value as a quoted string. For example, assume an object has a long field 42 | * named "f" then the serialized output would be: 43 | * {@code {"f":"123"}}. 44 | */ 45 | STRING() { 46 | public JsonElement serialize(Long value) { 47 | return new JsonPrimitive(String.valueOf(value)); 48 | } 49 | }; 50 | 51 | /** 52 | * Serialize this {@code value} using this serialization policy. 53 | * 54 | * @param value the long value to be serialized into a {@link JsonElement} 55 | * @return the serialized version of {@code value} 56 | */ 57 | public abstract JsonElement serialize(Long value); 58 | } 59 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/annotations/SerializedName.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.annotations; 18 | 19 | import java.lang.annotation.ElementType; 20 | import java.lang.annotation.Retention; 21 | import java.lang.annotation.RetentionPolicy; 22 | import java.lang.annotation.Target; 23 | 24 | /** 25 | * An annotation that indicates this member should be serialized to JSON with 26 | * the provided name value as its field name. 27 | * 28 | *

This annotation will override any {@link com.google.gson.FieldNamingPolicy}, including 29 | * the default field naming policy, that may have been set on the {@link com.google.gson.Gson} 30 | * instance. A different naming policy can set using the {@code GsonBuilder} class. See 31 | * {@link com.google.gson.GsonBuilder#setFieldNamingPolicy(com.google.gson.FieldNamingPolicy)} 32 | * for more information.

33 | * 34 | *

Here is an example of how this annotation is meant to be used:

35 | *
36 |  * public class SomeClassWithFields {
37 |  *   @SerializedName("name") private final String someField;
38 |  *   private final String someOtherField;
39 |  *
40 |  *   public SomeClassWithFields(String a, String b) {
41 |  *     this.someField = a;
42 |  *     this.someOtherField = b;
43 |  *   }
44 |  * }
45 |  * 
46 | * 47 | *

The following shows the output that is generated when serializing an instance of the 48 | * above example class:

49 | *
50 |  * SomeClassWithFields objectToSerialize = new SomeClassWithFields("a", "b");
51 |  * Gson gson = new Gson();
52 |  * String jsonRepresentation = gson.toJson(objectToSerialize);
53 |  * System.out.println(jsonRepresentation);
54 |  *
55 |  * ===== OUTPUT =====
56 |  * {"name":"a","someOtherField":"b"}
57 |  * 
58 | * 59 | *

NOTE: The value you specify in this annotation must be a valid JSON field name.

60 | * 61 | * @see com.google.gson.FieldNamingPolicy 62 | * 63 | * @author Inderjeet Singh 64 | * @author Joel Leitch 65 | */ 66 | @Retention(RetentionPolicy.RUNTIME) 67 | @Target(ElementType.FIELD) 68 | public @interface SerializedName { 69 | 70 | /** 71 | * @return the desired name of the field when it is serialized 72 | */ 73 | String value(); 74 | } 75 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/annotations/Since.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.annotations; 18 | 19 | import java.lang.annotation.ElementType; 20 | import java.lang.annotation.Retention; 21 | import java.lang.annotation.RetentionPolicy; 22 | import java.lang.annotation.Target; 23 | 24 | /** 25 | * An annotation that indicates the version number since a member or a type has been present. 26 | * This annotation is useful to manage versioning of your Json classes for a web-service. 27 | * 28 | *

29 | * This annotation has no effect unless you build {@link com.google.gson.Gson} with a 30 | * {@link com.google.gson.GsonBuilder} and invoke 31 | * {@link com.google.gson.GsonBuilder#setVersion(double)} method. 32 | * 33 | *

Here is an example of how this annotation is meant to be used:

34 | *
35 |  * public class User {
36 |  *   private String firstName;
37 |  *   private String lastName;
38 |  *   @Since(1.0) private String emailAddress;
39 |  *   @Since(1.0) private String password;
40 |  *   @Since(1.1) private Address address;
41 |  * }
42 |  * 
43 | * 44 | *

If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()} 45 | * methods will use all the fields for serialization and deserialization. However, if you created 46 | * Gson with {@code Gson gson = new GsonBuilder().setVersion(1.0).create()} then the 47 | * {@code toJson()} and {@code fromJson()} methods of Gson will exclude the {@code address} field 48 | * since it's version number is set to {@code 1.1}.

49 | * 50 | * @author Inderjeet Singh 51 | * @author Joel Leitch 52 | */ 53 | @Retention(RetentionPolicy.RUNTIME) 54 | @Target({ElementType.FIELD, ElementType.TYPE}) 55 | public @interface Since { 56 | /** 57 | * the value indicating a version number since this member 58 | * or type has been present. 59 | */ 60 | double value(); 61 | } 62 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/annotations/Until.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.annotations; 18 | 19 | import java.lang.annotation.ElementType; 20 | import java.lang.annotation.Retention; 21 | import java.lang.annotation.RetentionPolicy; 22 | import java.lang.annotation.Target; 23 | 24 | /** 25 | * An annotation that indicates the version number until a member or a type should be present. 26 | * Basically, if Gson is created with a version number that exceeds the value stored in the 27 | * {@code Until} annotation then the field will be ignored from the JSON output. This annotation 28 | * is useful to manage versioning of your JSON classes for a web-service. 29 | * 30 | *

31 | * This annotation has no effect unless you build {@link com.google.gson.Gson} with a 32 | * {@link com.google.gson.GsonBuilder} and invoke 33 | * {@link com.google.gson.GsonBuilder#setVersion(double)} method. 34 | * 35 | *

Here is an example of how this annotation is meant to be used:

36 | *
37 |  * public class User {
38 |  *   private String firstName;
39 |  *   private String lastName;
40 |  *   @Until(1.1) private String emailAddress;
41 |  *   @Until(1.1) private String password;
42 |  * }
43 |  * 
44 | * 45 | *

If you created Gson with {@code new Gson()}, the {@code toJson()} and {@code fromJson()} 46 | * methods will use all the fields for serialization and deserialization. However, if you created 47 | * Gson with {@code Gson gson = new GsonBuilder().setVersion(1.2).create()} then the 48 | * {@code toJson()} and {@code fromJson()} methods of Gson will exclude the {@code emailAddress} 49 | * and {@code password} fields from the example above, because the version number passed to the 50 | * GsonBuilder, {@code 1.2}, exceeds the version number set on the {@code Until} annotation, 51 | * {@code 1.1}, for those fields. 52 | * 53 | * @author Inderjeet Singh 54 | * @author Joel Leitch 55 | * @since 1.3 56 | */ 57 | @Retention(RetentionPolicy.RUNTIME) 58 | @Target({ElementType.FIELD, ElementType.TYPE}) 59 | public @interface Until { 60 | 61 | /** 62 | * the value indicating a version number until this member 63 | * or type should be ignored. 64 | */ 65 | double value(); 66 | } 67 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/annotations/package-info.java: -------------------------------------------------------------------------------- 1 | /** 2 | * This package provides annotations that can be used with {@link com.google.gson.Gson}. 3 | * 4 | * @author Inderjeet Singh, Joel Leitch 5 | */ 6 | package com.google.gson.annotations; -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/$Gson$Preconditions.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal; 18 | 19 | /** 20 | * A simple utility class used to check method Preconditions. 21 | * 22 | *

23 |  * public long divideBy(long value) {
24 |  *   Preconditions.checkArgument(value != 0);
25 |  *   return this.value / value;
26 |  * }
27 |  * 
28 | * 29 | * @author Inderjeet Singh 30 | * @author Joel Leitch 31 | */ 32 | public final class $Gson$Preconditions { 33 | public static T checkNotNull(T obj) { 34 | if (obj == null) { 35 | throw new NullPointerException(); 36 | } 37 | return obj; 38 | } 39 | 40 | public static void checkArgument(boolean condition) { 41 | if (!condition) { 42 | throw new IllegalArgumentException(); 43 | } 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/JsonReaderInternalAccess.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal; 18 | 19 | import com.google.gson.stream.JsonReader; 20 | import java.io.IOException; 21 | 22 | /** 23 | * Internal-only APIs of JsonReader available only to other classes in Gson. 24 | */ 25 | public abstract class JsonReaderInternalAccess { 26 | public static JsonReaderInternalAccess INSTANCE; 27 | 28 | /** 29 | * Changes the type of the current property name token to a string value. 30 | */ 31 | public abstract void promoteNameToValue(JsonReader reader) throws IOException; 32 | } 33 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/LazilyParsedNumber.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | package com.google.gson.internal; 17 | 18 | import java.io.ObjectStreamException; 19 | import java.math.BigDecimal; 20 | import java.math.BigInteger; 21 | 22 | /** 23 | * This class holds a number value that is lazily converted to a specific number type 24 | * 25 | * @author Inderjeet Singh 26 | */ 27 | @SuppressWarnings("serial") 28 | public final class LazilyParsedNumber extends Number { 29 | private final String value; 30 | 31 | public LazilyParsedNumber(String value) { 32 | this.value = value; 33 | } 34 | 35 | @Override 36 | public int intValue() { 37 | try { 38 | return Integer.parseInt(value); 39 | } catch (NumberFormatException e) { 40 | try { 41 | return (int) Long.parseLong(value); 42 | } catch (NumberFormatException nfe) { 43 | return new BigInteger(value).intValue(); 44 | } 45 | } 46 | } 47 | 48 | @Override 49 | public long longValue() { 50 | try { 51 | return Long.parseLong(value); 52 | } catch (NumberFormatException e) { 53 | return new BigInteger(value).longValue(); 54 | } 55 | } 56 | 57 | @Override 58 | public float floatValue() { 59 | return Float.parseFloat(value); 60 | } 61 | 62 | @Override 63 | public double doubleValue() { 64 | return Double.parseDouble(value); 65 | } 66 | 67 | @Override 68 | public String toString() { 69 | return value; 70 | } 71 | 72 | /** 73 | * If somebody is unlucky enough to have to serialize one of these, serialize 74 | * it as a BigDecimal so that they won't need Gson on the other side to 75 | * deserialize it. 76 | */ 77 | private Object writeReplace() throws ObjectStreamException { 78 | return new BigDecimal(value); 79 | } 80 | } -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/ObjectConstructor.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2008 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal; 18 | 19 | /** 20 | * Defines a generic object construction factory. The purpose of this class 21 | * is to construct a default instance of a class that can be used for object 22 | * navigation while deserialization from its JSON representation. 23 | * 24 | * @author Inderjeet Singh 25 | * @author Joel Leitch 26 | */ 27 | public interface ObjectConstructor { 28 | 29 | /** 30 | * Returns a new instance. 31 | */ 32 | public T construct(); 33 | } -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/bind/ArrayTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.TypeAdapter; 21 | import com.google.gson.TypeAdapterFactory; 22 | import java.io.IOException; 23 | import java.lang.reflect.Array; 24 | import java.lang.reflect.GenericArrayType; 25 | import java.lang.reflect.Type; 26 | import java.util.ArrayList; 27 | import java.util.List; 28 | 29 | import com.google.gson.internal.$Gson$Types; 30 | import com.google.gson.reflect.TypeToken; 31 | import com.google.gson.stream.JsonReader; 32 | import com.google.gson.stream.JsonToken; 33 | import com.google.gson.stream.JsonWriter; 34 | 35 | /** 36 | * Adapt an array of objects. 37 | */ 38 | public final class ArrayTypeAdapter extends TypeAdapter { 39 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { 40 | @SuppressWarnings({"unchecked", "rawtypes"}) 41 | public TypeAdapter create(Gson gson, TypeToken typeToken) { 42 | Type type = typeToken.getType(); 43 | if (!(type instanceof GenericArrayType || type instanceof Class && ((Class) type).isArray())) { 44 | return null; 45 | } 46 | 47 | Type componentType = $Gson$Types.getArrayComponentType(type); 48 | TypeAdapter componentTypeAdapter = gson.getAdapter(TypeToken.get(componentType)); 49 | return new ArrayTypeAdapter( 50 | gson, componentTypeAdapter, $Gson$Types.getRawType(componentType)); 51 | } 52 | }; 53 | 54 | private final Class componentType; 55 | private final TypeAdapter componentTypeAdapter; 56 | 57 | public ArrayTypeAdapter(Gson context, TypeAdapter componentTypeAdapter, Class componentType) { 58 | this.componentTypeAdapter = 59 | new TypeAdapterRuntimeTypeWrapper(context, componentTypeAdapter, componentType); 60 | this.componentType = componentType; 61 | } 62 | 63 | public Object read(JsonReader in) throws IOException { 64 | if (in.peek() == JsonToken.NULL) { 65 | in.nextNull(); 66 | return null; 67 | } 68 | 69 | List list = new ArrayList(); 70 | in.beginArray(); 71 | while (in.hasNext()) { 72 | E instance = componentTypeAdapter.read(in); 73 | list.add(instance); 74 | } 75 | in.endArray(); 76 | Object array = Array.newInstance(componentType, list.size()); 77 | for (int i = 0; i < list.size(); i++) { 78 | Array.set(array, i, list.get(i)); 79 | } 80 | return array; 81 | } 82 | 83 | @SuppressWarnings("unchecked") 84 | @Override public void write(JsonWriter out, Object array) throws IOException { 85 | if (array == null) { 86 | out.nullValue(); 87 | return; 88 | } 89 | 90 | out.beginArray(); 91 | for (int i = 0, length = Array.getLength(array); i < length; i++) { 92 | E value = (E) Array.get(array, i); 93 | componentTypeAdapter.write(out, value); 94 | } 95 | out.endArray(); 96 | } 97 | } 98 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/bind/DateTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.JsonSyntaxException; 21 | import com.google.gson.TypeAdapter; 22 | import com.google.gson.TypeAdapterFactory; 23 | import com.google.gson.reflect.TypeToken; 24 | import com.google.gson.stream.JsonReader; 25 | import com.google.gson.stream.JsonToken; 26 | import com.google.gson.stream.JsonWriter; 27 | import java.io.IOException; 28 | import java.text.DateFormat; 29 | import java.text.ParseException; 30 | import java.text.SimpleDateFormat; 31 | import java.util.Date; 32 | import java.util.Locale; 33 | import java.util.TimeZone; 34 | 35 | /** 36 | * Adapter for Date. Although this class appears stateless, it is not. 37 | * DateFormat captures its time zone and locale when it is created, which gives 38 | * this class state. DateFormat isn't thread safe either, so this class has 39 | * to synchronize its read and write methods. 40 | */ 41 | public final class DateTypeAdapter extends TypeAdapter { 42 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { 43 | @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal 44 | public TypeAdapter create(Gson gson, TypeToken typeToken) { 45 | return typeToken.getRawType() == Date.class ? (TypeAdapter) new DateTypeAdapter() : null; 46 | } 47 | }; 48 | 49 | private final DateFormat enUsFormat 50 | = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT, Locale.US); 51 | private final DateFormat localFormat 52 | = DateFormat.getDateTimeInstance(DateFormat.DEFAULT, DateFormat.DEFAULT); 53 | private final DateFormat iso8601Format = buildIso8601Format(); 54 | 55 | private static DateFormat buildIso8601Format() { 56 | DateFormat iso8601Format = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'", Locale.US); 57 | iso8601Format.setTimeZone(TimeZone.getTimeZone("UTC")); 58 | return iso8601Format; 59 | } 60 | 61 | @Override public Date read(JsonReader in) throws IOException { 62 | if (in.peek() == JsonToken.NULL) { 63 | in.nextNull(); 64 | return null; 65 | } 66 | return deserializeToDate(in.nextString()); 67 | } 68 | 69 | private synchronized Date deserializeToDate(String json) { 70 | try { 71 | return localFormat.parse(json); 72 | } catch (ParseException ignored) { 73 | } 74 | try { 75 | return enUsFormat.parse(json); 76 | } catch (ParseException ignored) { 77 | } 78 | try { 79 | return iso8601Format.parse(json); 80 | } catch (ParseException e) { 81 | throw new JsonSyntaxException(json, e); 82 | } 83 | } 84 | 85 | @Override public synchronized void write(JsonWriter out, Date value) throws IOException { 86 | if (value == null) { 87 | out.nullValue(); 88 | return; 89 | } 90 | String dateFormatAsString = enUsFormat.format(value); 91 | out.value(dateFormatAsString); 92 | } 93 | } 94 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/bind/ObjectTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.TypeAdapter; 21 | import com.google.gson.TypeAdapterFactory; 22 | import com.google.gson.internal.StringMap; 23 | import com.google.gson.reflect.TypeToken; 24 | import com.google.gson.stream.JsonReader; 25 | import com.google.gson.stream.JsonToken; 26 | import com.google.gson.stream.JsonWriter; 27 | import java.io.IOException; 28 | import java.util.ArrayList; 29 | import java.util.List; 30 | import java.util.Map; 31 | 32 | /** 33 | * Adapts types whose static type is only 'Object'. Uses getClass() on 34 | * serialization and a primitive/Map/List on deserialization. 35 | */ 36 | public final class ObjectTypeAdapter extends TypeAdapter { 37 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { 38 | @SuppressWarnings("unchecked") 39 | public TypeAdapter create(Gson gson, TypeToken type) { 40 | if (type.getRawType() == Object.class) { 41 | return (TypeAdapter) new ObjectTypeAdapter(gson); 42 | } 43 | return null; 44 | } 45 | }; 46 | 47 | private final Gson gson; 48 | 49 | private ObjectTypeAdapter(Gson gson) { 50 | this.gson = gson; 51 | } 52 | 53 | @Override public Object read(JsonReader in) throws IOException { 54 | JsonToken token = in.peek(); 55 | switch (token) { 56 | case BEGIN_ARRAY: 57 | List list = new ArrayList(); 58 | in.beginArray(); 59 | while (in.hasNext()) { 60 | list.add(read(in)); 61 | } 62 | in.endArray(); 63 | return list; 64 | 65 | case BEGIN_OBJECT: 66 | Map map = new StringMap(); 67 | in.beginObject(); 68 | while (in.hasNext()) { 69 | map.put(in.nextName(), read(in)); 70 | } 71 | in.endObject(); 72 | return map; 73 | 74 | case STRING: 75 | return in.nextString(); 76 | 77 | case NUMBER: 78 | return in.nextDouble(); 79 | 80 | case BOOLEAN: 81 | return in.nextBoolean(); 82 | 83 | case NULL: 84 | in.nextNull(); 85 | return null; 86 | 87 | } 88 | throw new IllegalStateException(); 89 | } 90 | 91 | @SuppressWarnings("unchecked") 92 | @Override public void write(JsonWriter out, Object value) throws IOException { 93 | if (value == null) { 94 | out.nullValue(); 95 | return; 96 | } 97 | 98 | TypeAdapter typeAdapter = (TypeAdapter) gson.getAdapter(value.getClass()); 99 | if (typeAdapter instanceof ObjectTypeAdapter) { 100 | out.beginObject(); 101 | out.endObject(); 102 | return; 103 | } 104 | 105 | typeAdapter.write(out, value); 106 | } 107 | } 108 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/bind/SqlDateTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.JsonSyntaxException; 21 | import com.google.gson.TypeAdapter; 22 | import com.google.gson.TypeAdapterFactory; 23 | import com.google.gson.reflect.TypeToken; 24 | import com.google.gson.stream.JsonReader; 25 | import com.google.gson.stream.JsonToken; 26 | import com.google.gson.stream.JsonWriter; 27 | import java.io.IOException; 28 | import java.text.DateFormat; 29 | import java.text.ParseException; 30 | import java.text.SimpleDateFormat; 31 | 32 | /** 33 | * Adapter for java.sql.Date. Although this class appears stateless, it is not. 34 | * DateFormat captures its time zone and locale when it is created, which gives 35 | * this class state. DateFormat isn't thread safe either, so this class has 36 | * to synchronize its read and write methods. 37 | */ 38 | public final class SqlDateTypeAdapter extends TypeAdapter { 39 | public static final TypeAdapterFactory FACTORY = new TypeAdapterFactory() { 40 | @SuppressWarnings("unchecked") // we use a runtime check to make sure the 'T's equal 41 | public TypeAdapter create(Gson gson, TypeToken typeToken) { 42 | return typeToken.getRawType() == java.sql.Date.class 43 | ? (TypeAdapter) new SqlDateTypeAdapter() : null; 44 | } 45 | }; 46 | 47 | private final DateFormat format = new SimpleDateFormat("MMM d, yyyy"); 48 | 49 | @Override 50 | public synchronized java.sql.Date read(JsonReader in) throws IOException { 51 | if (in.peek() == JsonToken.NULL) { 52 | in.nextNull(); 53 | return null; 54 | } 55 | try { 56 | final long utilDate = format.parse(in.nextString()).getTime(); 57 | return new java.sql.Date(utilDate); 58 | } catch (ParseException e) { 59 | throw new JsonSyntaxException(e); 60 | } 61 | } 62 | 63 | @Override 64 | public synchronized void write(JsonWriter out, java.sql.Date value) throws IOException { 65 | out.value(value == null ? null : format.format(value)); 66 | } 67 | } 68 | -------------------------------------------------------------------------------- /src/driver/java/src/com/google/gson/internal/bind/TimeTypeAdapter.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Copyright (C) 2011 Google Inc. 3 | * 4 | * Licensed under the Apache License, Version 2.0 (the "License"); 5 | * you may not use this file except in compliance with the License. 6 | * You may obtain a copy of the License at 7 | * 8 | * http://www.apache.org/licenses/LICENSE-2.0 9 | * 10 | * Unless required by applicable law or agreed to in writing, software 11 | * distributed under the License is distributed on an "AS IS" BASIS, 12 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 | * See the License for the specific language governing permissions and 14 | * limitations under the License. 15 | */ 16 | 17 | package com.google.gson.internal.bind; 18 | 19 | import com.google.gson.Gson; 20 | import com.google.gson.JsonSyntaxException; 21 | import com.google.gson.TypeAdapter; 22 | import com.google.gson.TypeAdapterFactory; 23 | import com.google.gson.reflect.TypeToken; 24 | import com.google.gson.stream.JsonReader; 25 | import com.google.gson.stream.JsonToken; 26 | import com.google.gson.stream.JsonWriter; 27 | import java.io.IOException; 28 | import java.sql.Time; 29 | import java.text.DateFormat; 30 | import java.text.ParseException; 31 | import java.text.SimpleDateFormat; 32 | import java.util.Date; 33 | 34 | /** 35 | * Adapter for Time. Although this class appears stateless, it is not. 36 | * DateFormat captures its time zone and locale when it is created, which gives 37 | * this class state. DateFormat isn't thread safe either, so this class has 38 | * to synchronize its read and write methods. 39 | */ 40 | public final class TimeTypeAdapter extends TypeAdapter