Skip to content
Browse files

repo cleanup

  • Loading branch information...
0 parents commit 328cdc7e01965dd3ca3240fcd8bf3f64dcdf8ccf @gwhalin gwhalin committed
118 build.xml
@@ -0,0 +1,118 @@
+<?xml version="1.0" encoding="ISO-8859-1"?>
+<project name="java_memcached" default="package" basedir=".">
+
+ <property name="project.title" value="java memcached client" />
+ <property name="code.dir" value="src/com/danga/MemCached" />
+ <property name="doc.dir" value="doc" />
+ <property name="src.dir" value="src" />
+ <property name="build.dir" value="classes" />
+
+ <property environment="env"/>
+ <property file="build.properties"/>
+ <property name="project" value="java_memcached"/>
+
+ <path id="project.class.path">
+ <pathelement path = "lib/log4j.jar"/>
+ </path>
+
+ <!-- package release -->
+ <target name="package" depends="clean, setup, log4j, logger, pkg-compile, jar, javadoc">
+ <tar tarfile="java_memcached-${ver}.tar.gz" basedir="." includes="java_memcached-${ver}/**" compression="gzip"/>
+ <zip destfile="java_memcached-${ver}.zip" basedir="." includes="java_memcached-${ver}/**"/>
+ <copy file="java_memcached-${ver}/java_memcached-${ver}.jar" todir="."/>
+
+ <checksum file="java_memcached-${ver}.tar.gz"/>
+ <checksum file="java_memcached-${ver}.zip"/>
+ <checksum file="java_memcached-${ver}.jar"/>
+ <delete dir="java_memcached-${ver}" />
+
+ <tar tarfile="java_memcached-${ver}.tar" basedir="." includes="java_memcached-${ver}.*"/>
+ </target>
+
+ <target name="clean">
+ <delete dir="${build.dir}"/>
+ <delete dir="java_memcached-${ver}" />
+ <delete file="java_memcached-${ver}.tar.gz"/>
+ <delete file="java_memcached-${ver}.zip"/>
+ <delete file="java_memcached-${ver}.jar"/>
+ <delete file="java_memcached-${ver}.tar.gz.MD5"/>
+ <delete file="java_memcached-${ver}.zip.MD5"/>
+ <delete file="java_memcached-${ver}.jar.MD5"/>
+ </target>
+
+ <target name="setup">
+ <mkdir dir="java_memcached-${ver}"/>
+ <mkdir dir="java_memcached-${ver}/javadocs"/>
+ <mkdir dir="java_memcached-${ver}/src/com/danga/MemCached"/>
+ <mkdir dir="java_memcached-${ver}/classes"/>
+ <mkdir dir="java_memcached-${ver}/doc"/>
+
+ <!-- copy source -->
+ <copy todir="java_memcached-${ver}/src/com/danga/MemCached">
+ <fileset dir="${code.dir}" defaultexcludes="true" excludes="**/*.xml **/*.swp **/*.swo"/>
+ </copy>
+
+ <!-- copy doc dir -->
+ <copy todir="java_memcached-${ver}/doc">
+ <fileset dir="${doc.dir}" defaultexcludes="true" excludes="**/*.swp **/*.swo"/>
+ </copy>
+
+ <!-- copy license to root -->
+ <copy file="${doc.dir}/LICENSE.txt" todir="java_memcached-${ver}"/>
+
+ <!-- copy changelog to root -->
+ <copy file="${doc.dir}/CHANGELOG.txt" todir="java_memcached-${ver}"/>
+ </target>
+
+ <!-- if logger is log4j then need to filter to make sure import exists -->
+ <target name="log4j" if="log4j" depends="clean, setup">
+ <replace dir="java_memcached-${ver}/src/com/danga/MemCached" token="//import org.apache.log4j.Logger;" value="import org.apache.log4j.Logger;">
+ <include name="**/*.java"/>
+ </replace>
+ </target>
+
+ <target name="logger" unless="log4j" depends="clean, setup">
+ <replace dir="java_memcached-${ver}/src/com/danga/MemCached" token="import org.apache.log4j.Logger;" value="//import org.apache.log4j.Logger;">
+ <include name="**/*.java"/>
+ </replace>
+ </target>
+
+ <!-- javadocs -->
+ <target name="javadoc" depends="clean, setup, log4j, logger">
+ <delete>
+ <fileset dir="java_memcached-${ver}/javadocs" />
+ </delete>
+
+ <javadoc sourcepath="java_memcached-${ver}/src"
+ destdir="java_memcached-${ver}/javadocs"
+ packagenames= "com.danga.*"
+ author= "true"
+ private="true"
+ version="true"
+ defaultexcludes="yes"
+ use="true"
+ windowtitle="java memcached client api documentation"
+ doctitle="&lt;h1&gt;${project.title} documentation (Version ${ver})&lt;/h1&gt;"
+ bottom="Copyright &#169; 2005 - greg whalin">
+ </javadoc>
+ </target>
+
+ <!-- compilation target for packeging operations -->
+ <target name="pkg-compile" depends="clean, setup, log4j, logger">
+ <javac debug="yes" srcdir="java_memcached-${ver}/src" destdir="java_memcached-${ver}/classes" deprecation="true">
+ <classpath refid="project.class.path"/>
+ </javac>
+ </target>
+
+ <target name="jar" depends="pkg-compile">
+ <jar compress="yes" jarfile="java_memcached-${ver}/java_memcached-${ver}.jar" basedir="java_memcached-${ver}/classes"/>
+ </target>
+
+ <!-- compilation target for dev work -->
+ <target name="compile">
+ <mkdir dir="${build.dir}"/>
+ <javac debug="yes" srcdir="${src.dir}" destdir="${build.dir}" deprecation="true" source="1.4">
+ <classpath refid="project.class.path"/>
+ </javac>
+ </target>
+</project>
146 doc/CHANGELOG.txt
@@ -0,0 +1,146 @@
+20 Mar 2005 (whalin)
+ -- released as version 1.2.1
+ -- make non-blocking connect optional
+ -- better ant scripts for dev work and packaging
+ -- moved into dedicated subversion repo
+
+19 Jan 2005
+ -- bugfix to remove tmp array copy in String deoding (Popescu)
+
+10 Jan 2005
+ -- released as version 1.2
+ -- spawn thread for initial socket connection so we can enforce a shorter
+ timeout on connections (whalin)
+
+03 Jan 2005
+ -- add custom serialization for Date objects
+ for greater space savings (whalin)
+
+13 Dec 2004
+ -- custom serialize primitive objects for greater
+ space savings (burton)
+
+12 Dec 2004
+ -- set maint thread as a daemon thread (k. burton)
+
+29 Nov 2004
+ -- released as version 1.1
+ -- switched to LGPL from GPL (whalin)
+
+18 Sept 2004
+ --- released as version 1.0
+ -- built generic logging class so can remove dependancy on other loggers
+ (still easy for client to use their own logger) (whalin)
+ -- fixed bad case for maxcreate when poolmultiplier was greater than
+ minConn (defaults to minConn now) (thanks to Daryn @ Spam Arrest)
+ -- fixed bad loop logic when creating new connections when conns <
+ minConn. (thanks to Daryn @ Spam Arrest)
+ -- retagged as a release 1.0
+
+27 July 2004
+ -- released as version 0.9.8a
+ -- change default hashing to native as it is faster (whalin)
+
+26 July 2004
+ -- released as version 0.9.8
+ -- added flushAll method, which allows invalidating the entire cache on
+ all servers (or subset). (whalin)
+ -- added stats methods to pull back statistics from the caching servers
+ (or subset). Data is pulled back in data structure for end user to
+ format. (whalin)
+ -- fixup to counter code (whalin)
+ -- add in new hashing code based on CRC32 (whalin)
+
+01 Jun 2004
+ -- released as version 0.9.7
+ -- clear pool for a given host when we detect it is dead. (whalin)
+ -- changed failver code to rehash in a better manner (more efficient when
+ a server dies) (russo)
+ -- add optional custom hashing method, which should be compatable with
+ other memcached clients (perl/php/python, etc), but will be slower
+ Java's built in hashCode for String (due to String pooling). (whalin,
+ russo)
+ -- fixed Java to actually return modulus (instead of remainder) when
+ selecting a bucket (russo)
+ -- fixed a typo in the getNagle method (whalin)
+
+26 May 2004
+ -- released as version 0.9.6
+ -- Fixed bug where reading from socket when server dies will cause tight
+ loop. Also cleaned up error handling to throw exceptions in more
+ failed situations. (whalin)
+
+25 May 2004
+ -- released as version 0.9.5
+ -- Heavy cleanup of client code to better deal with error conditions, use
+ java naming conventions, and remove some of the overloaded convenience
+ methods. Also changed how client deals with pulling objects from
+ cache when not serialized to be more type safe.
+ -- Created connection pool to manage connections to various caching servers
+ maintaining persistent connections.
+ -- Changed SockIO to be internal static class to the pool.
+ -- Added support for more socket options (nagle, timeout).
+ -- Removed deprecated stream operations.
+ -- Heavyily javadoc'd
+ -- Added in useage of log4j (could use J2SE logger as well)
+ -- NOTE: Not backwards compatible with earlier versions!!!
+
+12 Oct 2003
+ -- released as version 0.9.1
+ -- Altered the SockIO helper class, so it no longer allows accessing
+ the streams it contains directly, instead it has methods
+ with identical signatures to the methods that were called
+ on the streams... This makes the client code prettier.
+ -- Changed looped non blocking read to blocking read, for getting
+ items from the server. This probably reduces CPU usage in
+ cases where the retrieval would block, and cleans up the
+ code a bit. We're blocking on retrieval anyhow.
+ -- Made get() not call get_multi(), and added single socket
+ optimization. This parallels recent changes to the perl
+ client
+ -- Changed a few for loops to use iterators instead, since it's
+ probably marginally more efficient, and it's probably
+ better coding practice.
+ -- Actually spell checked. :)
+
+29 Sep 2003
+ -- released as version 0.9.0
+ -- Renumbered to reflect that it's not been realworld tested
+ -- changed package to danga.com.MemCached (thanks)
+ -- added dates to changelog
+ -- added .txt to text files
+ -- added to official memcached site :)
+
+28 Sep 2003
+ -- released as version 1.0
+ -- Adjusted namespacing for SockIO, it shouldn't have been public; is now package level.
+ As a bonus, this means I don't have to Javadoc it. :)
+ -- Finished adding complete Javadoc to MemCachedClient.
+ -- spellchecked
+ -- added a couple versions of function variations that I missed. for example, some that
+ didn't take an int directly as a hash value, and i missed a get_multi w/out hashes.
+ -- removed java.net.Socket reference from MemCachedClient, SockIO has a new constructor which
+ takes hostname and port number
+ -- switched to three part version number
+
+27 Sep 2003
+ -- released as version 0.3
+ -- Compression, for strings/stringified numbers, this is compatible w/ perl
+ Serialized objects are incompatible w/ perl for obvious reasons. :)
+ -- Added PORTABILITY file, to include information about using the client
+ with various JVM's
+ -- Updated string parsing to StreamTokenizer rather than regexp's in an
+ effort to get sablevm to like the client
+
+24 Sep 2003
+ -- released as version 0.2
+ -- Serialization works
+ -- Possible BUG: Only the lower byte of the characters of keys are sent
+ This is only a problem if the memcache server can handle
+ unicode keys. (I haven't checked)
+ -- Server Failures handled gracefully
+ -- Partial Javadoc
+
+23 Sep 2003
+ -- Initial Release 0.1
+ -- Storing and Retrieving numbers and strings works
6 doc/CVS/Entries
@@ -0,0 +1,6 @@
+/LICENSE.txt/1.1/Mon Nov 29 18:11:59 2004//
+/PORTABILITY.txt/1.2/Wed Aug 4 16:28:46 2004//
+/README.txt/1.2/Wed Aug 4 16:28:46 2004//
+/TODO.txt/1.5/Mon Jan 17 19:03:01 2005//
+/CHANGELOG.txt/1.13/Sun Feb 6 17:22:59 2005//
+D
1 doc/CVS/Repository
@@ -0,0 +1 @@
+chapstick_java/src/com/danga/MemCached/doc
1 doc/CVS/Root
@@ -0,0 +1 @@
+:ext:cvs.dev.meetup.com:/usr/local/cvs
504 doc/LICENSE.txt
@@ -0,0 +1,504 @@
+ GNU LESSER GENERAL PUBLIC LICENSE
+ Version 2.1, February 1999
+
+ Copyright (C) 1991, 1999 Free Software Foundation, Inc.
+ 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ Everyone is permitted to copy and distribute verbatim copies
+ of this license document, but changing it is not allowed.
+
+[This is the first released version of the Lesser GPL. It also counts
+ as the successor of the GNU Library Public License, version 2, hence
+ the version number 2.1.]
+
+ Preamble
+
+ The licenses for most software are designed to take away your
+freedom to share and change it. By contrast, the GNU General Public
+Licenses are intended to guarantee your freedom to share and change
+free software--to make sure the software is free for all its users.
+
+ This license, the Lesser General Public License, applies to some
+specially designated software packages--typically libraries--of the
+Free Software Foundation and other authors who decide to use it. You
+can use it too, but we suggest you first think carefully about whether
+this license or the ordinary General Public License is the better
+strategy to use in any particular case, based on the explanations below.
+
+ When we speak of free software, we are referring to freedom of use,
+not price. Our General Public Licenses are designed to make sure that
+you have the freedom to distribute copies of free software (and charge
+for this service if you wish); that you receive source code or can get
+it if you want it; that you can change the software and use pieces of
+it in new free programs; and that you are informed that you can do
+these things.
+
+ To protect your rights, we need to make restrictions that forbid
+distributors to deny you these rights or to ask you to surrender these
+rights. These restrictions translate to certain responsibilities for
+you if you distribute copies of the library or if you modify it.
+
+ For example, if you distribute copies of the library, whether gratis
+or for a fee, you must give the recipients all the rights that we gave
+you. You must make sure that they, too, receive or can get the source
+code. If you link other code with the library, you must provide
+complete object files to the recipients, so that they can relink them
+with the library after making changes to the library and recompiling
+it. And you must show them these terms so they know their rights.
+
+ We protect your rights with a two-step method: (1) we copyright the
+library, and (2) we offer you this license, which gives you legal
+permission to copy, distribute and/or modify the library.
+
+ To protect each distributor, we want to make it very clear that
+there is no warranty for the free library. Also, if the library is
+modified by someone else and passed on, the recipients should know
+that what they have is not the original version, so that the original
+author's reputation will not be affected by problems that might be
+introduced by others.
+
+ Finally, software patents pose a constant threat to the existence of
+any free program. We wish to make sure that a company cannot
+effectively restrict the users of a free program by obtaining a
+restrictive license from a patent holder. Therefore, we insist that
+any patent license obtained for a version of the library must be
+consistent with the full freedom of use specified in this license.
+
+ Most GNU software, including some libraries, is covered by the
+ordinary GNU General Public License. This license, the GNU Lesser
+General Public License, applies to certain designated libraries, and
+is quite different from the ordinary General Public License. We use
+this license for certain libraries in order to permit linking those
+libraries into non-free programs.
+
+ When a program is linked with a library, whether statically or using
+a shared library, the combination of the two is legally speaking a
+combined work, a derivative of the original library. The ordinary
+General Public License therefore permits such linking only if the
+entire combination fits its criteria of freedom. The Lesser General
+Public License permits more lax criteria for linking other code with
+the library.
+
+ We call this license the "Lesser" General Public License because it
+does Less to protect the user's freedom than the ordinary General
+Public License. It also provides other free software developers Less
+of an advantage over competing non-free programs. These disadvantages
+are the reason we use the ordinary General Public License for many
+libraries. However, the Lesser license provides advantages in certain
+special circumstances.
+
+ For example, on rare occasions, there may be a special need to
+encourage the widest possible use of a certain library, so that it becomes
+a de-facto standard. To achieve this, non-free programs must be
+allowed to use the library. A more frequent case is that a free
+library does the same job as widely used non-free libraries. In this
+case, there is little to gain by limiting the free library to free
+software only, so we use the Lesser General Public License.
+
+ In other cases, permission to use a particular library in non-free
+programs enables a greater number of people to use a large body of
+free software. For example, permission to use the GNU C Library in
+non-free programs enables many more people to use the whole GNU
+operating system, as well as its variant, the GNU/Linux operating
+system.
+
+ Although the Lesser General Public License is Less protective of the
+users' freedom, it does ensure that the user of a program that is
+linked with the Library has the freedom and the wherewithal to run
+that program using a modified version of the Library.
+
+ The precise terms and conditions for copying, distribution and
+modification follow. Pay close attention to the difference between a
+"work based on the library" and a "work that uses the library". The
+former contains code derived from the library, whereas the latter must
+be combined with the library in order to run.
+
+ GNU LESSER GENERAL PUBLIC LICENSE
+ TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
+
+ 0. This License Agreement applies to any software library or other
+program which contains a notice placed by the copyright holder or
+other authorized party saying it may be distributed under the terms of
+this Lesser General Public License (also called "this License").
+Each licensee is addressed as "you".
+
+ A "library" means a collection of software functions and/or data
+prepared so as to be conveniently linked with application programs
+(which use some of those functions and data) to form executables.
+
+ The "Library", below, refers to any such software library or work
+which has been distributed under these terms. A "work based on the
+Library" means either the Library or any derivative work under
+copyright law: that is to say, a work containing the Library or a
+portion of it, either verbatim or with modifications and/or translated
+straightforwardly into another language. (Hereinafter, translation is
+included without limitation in the term "modification".)
+
+ "Source code" for a work means the preferred form of the work for
+making modifications to it. For a library, complete source code means
+all the source code for all modules it contains, plus any associated
+interface definition files, plus the scripts used to control compilation
+and installation of the library.
+
+ Activities other than copying, distribution and modification are not
+covered by this License; they are outside its scope. The act of
+running a program using the Library is not restricted, and output from
+such a program is covered only if its contents constitute a work based
+on the Library (independent of the use of the Library in a tool for
+writing it). Whether that is true depends on what the Library does
+and what the program that uses the Library does.
+
+ 1. You may copy and distribute verbatim copies of the Library's
+complete source code as you receive it, in any medium, provided that
+you conspicuously and appropriately publish on each copy an
+appropriate copyright notice and disclaimer of warranty; keep intact
+all the notices that refer to this License and to the absence of any
+warranty; and distribute a copy of this License along with the
+Library.
+
+ You may charge a fee for the physical act of transferring a copy,
+and you may at your option offer warranty protection in exchange for a
+fee.
+
+ 2. You may modify your copy or copies of the Library or any portion
+of it, thus forming a work based on the Library, and copy and
+distribute such modifications or work under the terms of Section 1
+above, provided that you also meet all of these conditions:
+
+ a) The modified work must itself be a software library.
+
+ b) You must cause the files modified to carry prominent notices
+ stating that you changed the files and the date of any change.
+
+ c) You must cause the whole of the work to be licensed at no
+ charge to all third parties under the terms of this License.
+
+ d) If a facility in the modified Library refers to a function or a
+ table of data to be supplied by an application program that uses
+ the facility, other than as an argument passed when the facility
+ is invoked, then you must make a good faith effort to ensure that,
+ in the event an application does not supply such function or
+ table, the facility still operates, and performs whatever part of
+ its purpose remains meaningful.
+
+ (For example, a function in a library to compute square roots has
+ a purpose that is entirely well-defined independent of the
+ application. Therefore, Subsection 2d requires that any
+ application-supplied function or table used by this function must
+ be optional: if the application does not supply it, the square
+ root function must still compute square roots.)
+
+These requirements apply to the modified work as a whole. If
+identifiable sections of that work are not derived from the Library,
+and can be reasonably considered independent and separate works in
+themselves, then this License, and its terms, do not apply to those
+sections when you distribute them as separate works. But when you
+distribute the same sections as part of a whole which is a work based
+on the Library, the distribution of the whole must be on the terms of
+this License, whose permissions for other licensees extend to the
+entire whole, and thus to each and every part regardless of who wrote
+it.
+
+Thus, it is not the intent of this section to claim rights or contest
+your rights to work written entirely by you; rather, the intent is to
+exercise the right to control the distribution of derivative or
+collective works based on the Library.
+
+In addition, mere aggregation of another work not based on the Library
+with the Library (or with a work based on the Library) on a volume of
+a storage or distribution medium does not bring the other work under
+the scope of this License.
+
+ 3. You may opt to apply the terms of the ordinary GNU General Public
+License instead of this License to a given copy of the Library. To do
+this, you must alter all the notices that refer to this License, so
+that they refer to the ordinary GNU General Public License, version 2,
+instead of to this License. (If a newer version than version 2 of the
+ordinary GNU General Public License has appeared, then you can specify
+that version instead if you wish.) Do not make any other change in
+these notices.
+
+ Once this change is made in a given copy, it is irreversible for
+that copy, so the ordinary GNU General Public License applies to all
+subsequent copies and derivative works made from that copy.
+
+ This option is useful when you wish to copy part of the code of
+the Library into a program that is not a library.
+
+ 4. You may copy and distribute the Library (or a portion or
+derivative of it, under Section 2) in object code or executable form
+under the terms of Sections 1 and 2 above provided that you accompany
+it with the complete corresponding machine-readable source code, which
+must be distributed under the terms of Sections 1 and 2 above on a
+medium customarily used for software interchange.
+
+ If distribution of object code is made by offering access to copy
+from a designated place, then offering equivalent access to copy the
+source code from the same place satisfies the requirement to
+distribute the source code, even though third parties are not
+compelled to copy the source along with the object code.
+
+ 5. A program that contains no derivative of any portion of the
+Library, but is designed to work with the Library by being compiled or
+linked with it, is called a "work that uses the Library". Such a
+work, in isolation, is not a derivative work of the Library, and
+therefore falls outside the scope of this License.
+
+ However, linking a "work that uses the Library" with the Library
+creates an executable that is a derivative of the Library (because it
+contains portions of the Library), rather than a "work that uses the
+library". The executable is therefore covered by this License.
+Section 6 states terms for distribution of such executables.
+
+ When a "work that uses the Library" uses material from a header file
+that is part of the Library, the object code for the work may be a
+derivative work of the Library even though the source code is not.
+Whether this is true is especially significant if the work can be
+linked without the Library, or if the work is itself a library. The
+threshold for this to be true is not precisely defined by law.
+
+ If such an object file uses only numerical parameters, data
+structure layouts and accessors, and small macros and small inline
+functions (ten lines or less in length), then the use of the object
+file is unrestricted, regardless of whether it is legally a derivative
+work. (Executables containing this object code plus portions of the
+Library will still fall under Section 6.)
+
+ Otherwise, if the work is a derivative of the Library, you may
+distribute the object code for the work under the terms of Section 6.
+Any executables containing that work also fall under Section 6,
+whether or not they are linked directly with the Library itself.
+
+ 6. As an exception to the Sections above, you may also combine or
+link a "work that uses the Library" with the Library to produce a
+work containing portions of the Library, and distribute that work
+under terms of your choice, provided that the terms permit
+modification of the work for the customer's own use and reverse
+engineering for debugging such modifications.
+
+ You must give prominent notice with each copy of the work that the
+Library is used in it and that the Library and its use are covered by
+this License. You must supply a copy of this License. If the work
+during execution displays copyright notices, you must include the
+copyright notice for the Library among them, as well as a reference
+directing the user to the copy of this License. Also, you must do one
+of these things:
+
+ a) Accompany the work with the complete corresponding
+ machine-readable source code for the Library including whatever
+ changes were used in the work (which must be distributed under
+ Sections 1 and 2 above); and, if the work is an executable linked
+ with the Library, with the complete machine-readable "work that
+ uses the Library", as object code and/or source code, so that the
+ user can modify the Library and then relink to produce a modified
+ executable containing the modified Library. (It is understood
+ that the user who changes the contents of definitions files in the
+ Library will not necessarily be able to recompile the application
+ to use the modified definitions.)
+
+ b) Use a suitable shared library mechanism for linking with the
+ Library. A suitable mechanism is one that (1) uses at run time a
+ copy of the library already present on the user's computer system,
+ rather than copying library functions into the executable, and (2)
+ will operate properly with a modified version of the library, if
+ the user installs one, as long as the modified version is
+ interface-compatible with the version that the work was made with.
+
+ c) Accompany the work with a written offer, valid for at
+ least three years, to give the same user the materials
+ specified in Subsection 6a, above, for a charge no more
+ than the cost of performing this distribution.
+
+ d) If distribution of the work is made by offering access to copy
+ from a designated place, offer equivalent access to copy the above
+ specified materials from the same place.
+
+ e) Verify that the user has already received a copy of these
+ materials or that you have already sent this user a copy.
+
+ For an executable, the required form of the "work that uses the
+Library" must include any data and utility programs needed for
+reproducing the executable from it. However, as a special exception,
+the materials to be distributed need not include anything that is
+normally distributed (in either source or binary form) with the major
+components (compiler, kernel, and so on) of the operating system on
+which the executable runs, unless that component itself accompanies
+the executable.
+
+ It may happen that this requirement contradicts the license
+restrictions of other proprietary libraries that do not normally
+accompany the operating system. Such a contradiction means you cannot
+use both them and the Library together in an executable that you
+distribute.
+
+ 7. You may place library facilities that are a work based on the
+Library side-by-side in a single library together with other library
+facilities not covered by this License, and distribute such a combined
+library, provided that the separate distribution of the work based on
+the Library and of the other library facilities is otherwise
+permitted, and provided that you do these two things:
+
+ a) Accompany the combined library with a copy of the same work
+ based on the Library, uncombined with any other library
+ facilities. This must be distributed under the terms of the
+ Sections above.
+
+ b) Give prominent notice with the combined library of the fact
+ that part of it is a work based on the Library, and explaining
+ where to find the accompanying uncombined form of the same work.
+
+ 8. You may not copy, modify, sublicense, link with, or distribute
+the Library except as expressly provided under this License. Any
+attempt otherwise to copy, modify, sublicense, link with, or
+distribute the Library is void, and will automatically terminate your
+rights under this License. However, parties who have received copies,
+or rights, from you under this License will not have their licenses
+terminated so long as such parties remain in full compliance.
+
+ 9. You are not required to accept this License, since you have not
+signed it. However, nothing else grants you permission to modify or
+distribute the Library or its derivative works. These actions are
+prohibited by law if you do not accept this License. Therefore, by
+modifying or distributing the Library (or any work based on the
+Library), you indicate your acceptance of this License to do so, and
+all its terms and conditions for copying, distributing or modifying
+the Library or works based on it.
+
+ 10. Each time you redistribute the Library (or any work based on the
+Library), the recipient automatically receives a license from the
+original licensor to copy, distribute, link with or modify the Library
+subject to these terms and conditions. You may not impose any further
+restrictions on the recipients' exercise of the rights granted herein.
+You are not responsible for enforcing compliance by third parties with
+this License.
+
+ 11. If, as a consequence of a court judgment or allegation of patent
+infringement or for any other reason (not limited to patent issues),
+conditions are imposed on you (whether by court order, agreement or
+otherwise) that contradict the conditions of this License, they do not
+excuse you from the conditions of this License. If you cannot
+distribute so as to satisfy simultaneously your obligations under this
+License and any other pertinent obligations, then as a consequence you
+may not distribute the Library at all. For example, if a patent
+license would not permit royalty-free redistribution of the Library by
+all those who receive copies directly or indirectly through you, then
+the only way you could satisfy both it and this License would be to
+refrain entirely from distribution of the Library.
+
+If any portion of this section is held invalid or unenforceable under any
+particular circumstance, the balance of the section is intended to apply,
+and the section as a whole is intended to apply in other circumstances.
+
+It is not the purpose of this section to induce you to infringe any
+patents or other property right claims or to contest validity of any
+such claims; this section has the sole purpose of protecting the
+integrity of the free software distribution system which is
+implemented by public license practices. Many people have made
+generous contributions to the wide range of software distributed
+through that system in reliance on consistent application of that
+system; it is up to the author/donor to decide if he or she is willing
+to distribute software through any other system and a licensee cannot
+impose that choice.
+
+This section is intended to make thoroughly clear what is believed to
+be a consequence of the rest of this License.
+
+ 12. If the distribution and/or use of the Library is restricted in
+certain countries either by patents or by copyrighted interfaces, the
+original copyright holder who places the Library under this License may add
+an explicit geographical distribution limitation excluding those countries,
+so that distribution is permitted only in or among countries not thus
+excluded. In such case, this License incorporates the limitation as if
+written in the body of this License.
+
+ 13. The Free Software Foundation may publish revised and/or new
+versions of the Lesser General Public License from time to time.
+Such new versions will be similar in spirit to the present version,
+but may differ in detail to address new problems or concerns.
+
+Each version is given a distinguishing version number. If the Library
+specifies a version number of this License which applies to it and
+"any later version", you have the option of following the terms and
+conditions either of that version or of any later version published by
+the Free Software Foundation. If the Library does not specify a
+license version number, you may choose any version ever published by
+the Free Software Foundation.
+
+ 14. If you wish to incorporate parts of the Library into other free
+programs whose distribution conditions are incompatible with these,
+write to the author to ask for permission. For software which is
+copyrighted by the Free Software Foundation, write to the Free
+Software Foundation; we sometimes make exceptions for this. Our
+decision will be guided by the two goals of preserving the free status
+of all derivatives of our free software and of promoting the sharing
+and reuse of software generally.
+
+ NO WARRANTY
+
+ 15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
+WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
+EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
+OTHER PARTIES PROVIDE THE LIBRARY "AS IS" WITHOUT WARRANTY OF ANY
+KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE
+IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
+PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE
+LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
+THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
+
+ 16. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN
+WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY
+AND/OR REDISTRIBUTE THE LIBRARY AS PERMITTED ABOVE, BE LIABLE TO YOU
+FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR
+CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OR INABILITY TO USE THE
+LIBRARY (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
+RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A
+FAILURE OF THE LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), EVEN IF
+SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
+DAMAGES.
+
+ END OF TERMS AND CONDITIONS
+
+ How to Apply These Terms to Your New Libraries
+
+ If you develop a new library, and you want it to be of the greatest
+possible use to the public, we recommend making it free software that
+everyone can redistribute and change. You can do so by permitting
+redistribution under these terms (or, alternatively, under the terms of the
+ordinary General Public License).
+
+ To apply these terms, attach the following notices to the library. It is
+safest to attach them to the start of each source file to most effectively
+convey the exclusion of warranty; and each file should have at least the
+"copyright" line and a pointer to where the full notice is found.
+
+ <one line to give the library's name and a brief idea of what it does.>
+ Copyright (C) <year> <name of author>
+
+ This library is free software; you can redistribute it and/or
+ modify it under the terms of the GNU Lesser General Public
+ License as published by the Free Software Foundation; either
+ version 2.1 of the License, or (at your option) any later version.
+
+ This library is distributed in the hope that it will be useful,
+ but WITHOUT ANY WARRANTY; without even the implied warranty of
+ MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
+ Lesser General Public License for more details.
+
+ You should have received a copy of the GNU Lesser General Public
+ License along with this library; if not, write to the Free Software
+ Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+
+Also add information on how to contact you by electronic and paper mail.
+
+You should also get your employer (if you work as a programmer) or your
+school, if any, to sign a "copyright disclaimer" for the library, if
+necessary. Here is a sample; alter the names:
+
+ Yoyodyne, Inc., hereby disclaims all copyright interest in the
+ library `Frob' (a library for tweaking knobs) written by James Random Hacker.
+
+ <signature of Ty Coon>, 1 April 1990
+ Ty Coon, President of Vice
+
+That's all there is to it!
+
+
6 doc/PORTABILITY.txt
@@ -0,0 +1,6 @@
+This file lists the portability status of this client. Please send me any
+additional information (greg@meetup.com).
+
+The newest release has only been tested on:
+
+Sun's JRE 1.4.2 on Linux/i86
4 doc/README.txt
@@ -0,0 +1,4 @@
+WARNING!
+
+This version is not compatable with versions prior to version 0.9.2
+Please see javadocs for examples on how to use.
6 doc/TODO.txt
@@ -0,0 +1,6 @@
+To Do:
+
+- make reconnection after a server failure an optional value
+- back socket connection thread w/ a thread pool
+- Try different compression streams as gzip stream is slow. (JNI??)
+- Try to improve CRC32 hashing performance (java.zip.CRC32 is slooooow)
BIN lib/log4j.jar
Binary file not shown.
201 src/com/danga/MemCached/Logger.java
@@ -0,0 +1,201 @@
+/**
+ * MemCached Java Client Logger
+ * Copyright (c) 2005
+ *
+ * This module is Copyright (c) 2005 Greg Whalin
+ * All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later
+ * version.
+ *
+ * This library is distributed in the hope that it will be
+ * useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * @author Greg Whalin <greg@meetup.com>
+ * @version 1.2
+ */
+package com.danga.MemCached;
+
+import java.util.*;
+
+/**
+ * This is a generic logger class for use in logging.
+ *
+ * This can easily be swapped out for any other logging package in the main code.
+ * For now, this is just a quick and dirty logger which will allow you to specify
+ * log levels, but only wraps system.out.println.
+ *
+ * @author Greg Whalin <greg@meetup.com>
+ * @version 1.2
+ */
+public class Logger {
+
+ public static final int LEVEL_DEBUG = 0;
+ public static final int LEVEL_INFO = 1;
+ public static final int LEVEL_WARN = 2;
+ public static final int LEVEL_ERROR = 3;
+ public static final int LEVEL_FATAL = 4;
+
+ private static Map loggers = new Hashtable();
+
+ private String name;
+ private int level;
+ private boolean initialized = false;
+
+ public void setLevel(int level) { this.level = level; }
+ public int getLevel() { return this.level; }
+
+ protected Logger(String name, int level) {
+ this.name = name;
+ this.level = level;
+ this.initialized = true;
+ }
+
+ protected Logger(String name) {
+ this.name = name;
+ this.level = LEVEL_INFO;
+ this.initialized = true;
+ }
+
+ /**
+ * Gets a Logger obj for given name and level.
+ *
+ * @param name
+ * @param level
+ * @return
+ */
+ public static Logger getLogger(String name, int level) {
+ Logger log = getLogger(name);
+ if (log.getLevel() != level)
+ log.setLevel(level);
+
+ return log;
+ }
+
+ /**
+ * Gets a Logger obj for given name
+ * and sets default level.
+ *
+ * @param name
+ * @return
+ */
+ public static Logger getLogger(String name) {
+
+ Logger log = null;
+ if (loggers.containsKey(name)) {
+ log = (Logger) loggers.get(name);
+
+ } else {
+ log = new Logger(name);
+ }
+
+ return log;
+ }
+
+ /**
+ * logs mesg to std out and prints stack trace if exception passed in
+ *
+ * @param mesg
+ * @param ex
+ */
+ private void log(String mesg, Exception ex) {
+ System.out.println(name + " " + new Date() + " - " + mesg);
+ if (ex != null)
+ ex.printStackTrace(System.out);
+ }
+
+ /**
+ * logs a debug mesg
+ *
+ * @param mesg
+ * @param ex
+ */
+ public void debug(String mesg, Exception ex) {
+ if (this.level > LEVEL_DEBUG)
+ return;
+
+ log(mesg, ex);
+ }
+
+ public void debug(String mesg) {
+ debug(mesg, null);
+ }
+
+ /**
+ * logs info mesg
+ *
+ * @param mesg
+ * @param ex
+ */
+ public void info(String mesg, Exception ex) {
+ if (this.level > LEVEL_INFO)
+ return;
+
+ log(mesg, ex);
+ }
+
+ public void info(String mesg) {
+ info(mesg, null);
+ }
+
+ /**
+ * logs warn mesg
+ *
+ * @param mesg
+ * @param ex
+ */
+ public void warn(String mesg, Exception ex) {
+ if (this.level > LEVEL_WARN)
+ return;
+
+ log(mesg, ex);
+ }
+
+ public void warn(String mesg) {
+ warn(mesg, null);
+ }
+
+ /**
+ * logs error mesg
+ *
+ * @param mesg
+ * @param ex
+ */
+ public void error(String mesg, Exception ex) {
+ if (this.level > LEVEL_ERROR)
+ return;
+
+ log(mesg, ex);
+ }
+
+ public void error(String mesg) {
+ error(mesg, null);
+ }
+
+ /**
+ * logs fatal mesg
+ *
+ * @param mesg
+ * @param ex
+ */
+ public void fatal(String mesg, Exception ex) {
+ if (this.level > LEVEL_FATAL)
+ return;
+
+ log(mesg, ex);
+ }
+
+ public void fatal(String mesg) {
+ fatal(mesg, null);
+ }
+}
1,364 src/com/danga/MemCached/MemCachedClient.java
@@ -0,0 +1,1364 @@
+/**
+ * MemCached Java client
+ * Copyright (c) 2005
+ *
+ * This module is Copyright (c) 2005 Greg Whalin, Richard Russo
+ * All rights reserved.
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later
+ * version.
+ *
+ * This library is distributed in the hope that it will be
+ * useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * @author Greg Whalin <greg@meetup.com>
+ * @author Richard 'toast' Russo <russor@msoe.edu>
+ * @author Kevin Burton <burton@peerfear.org>
+ * @version 1.2
+ */
+package com.danga.MemCached;
+
+import java.util.*;
+import java.util.zip.*;
+import java.io.*;
+
+import org.apache.log4j.Logger;
+
+/**
+ * This is a Java client for the memcached server available from
+ * <a href="http:/www.danga.com/memcached/">http://www.danga.com/memcached/</a>.
+ * <br/>
+ * Supports setting, adding, replacing, deleting compressed/uncompressed and<br/>
+ * serialized (can be stored as string if object is native class) objects to memcached.<br/>
+ * <br/>
+ * Now pulls SockIO objects from SockIOPool, which is a connection pool. The server failover<br/>
+ * has also been moved into the SockIOPool class.<br/>
+ * This pool needs to be initialized prior to the client working. See javadocs from SockIOPool.<br/>
+ * <br/>
+ * Some examples of use follow.<br/>
+ * <h3>To create cache client object and set params:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ *
+ * // compression is enabled by default
+ * mc.setCompressEnable(true);
+ *
+ * // set compression threshhold to 4 KB (default: 15 KB)
+ * mc.setCompressThreshold(4096);
+ *
+ * // turn on storing primitive types as a string representation
+ * // Should not do this in most cases.
+ * mc.setPrimitiveAsString(true);
+ * </pre>
+ * <h3>To store an object:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "cacheKey1";
+ * Object value = SomeClass.getObject();
+ * mc.set(key, value);
+ * </pre>
+ * <h3>To store an object using a custom server hashCode:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "cacheKey1";
+ * Object value = SomeClass.getObject();
+ * Integer hash = new Integer(45);
+ * mc.set(key, value, hash);
+ * </pre>
+ * The set method shown above will always set the object in the cache.<br/>
+ * The add and replace methods do the same, but with a slight difference.<br/>
+ * <ul>
+ * <li>add -- will store the object only if the server does not have an entry for this key</li>
+ * <li>replace -- will store the object only if the server already has an entry for this key</li>
+ * </ul>
+ * <h3>To delete a cache entry:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "cacheKey1";
+ * mc.delete(key);
+ * </pre>
+ * <h3>To delete a cache entry using a custom hash code:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "cacheKey1";
+ * Integer hash = new Integer(45);
+ * mc.delete(key, hashCode);
+ * </pre>
+ * <h3>To store a counter and then increment or decrement that counter:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "counterKey";
+ * mc.storeCounter(key, new Integer(100));
+ * System.out.println("counter after adding 1: " mc.incr(key));
+ * System.out.println("counter after adding 5: " mc.incr(key, 5));
+ * System.out.println("counter after subtracting 4: " mc.decr(key, 4));
+ * System.out.println("counter after subtracting 1: " mc.decr(key));
+ * </pre>
+ * <h3>To store a counter and then increment or decrement that counter with custom hash:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "counterKey";
+ * Integer hash = new Integer(45);
+ * mc.storeCounter(key, new Integer(100), hash);
+ * System.out.println("counter after adding 1: " mc.incr(key, 1, hash));
+ * System.out.println("counter after adding 5: " mc.incr(key, 5, hash));
+ * System.out.println("counter after subtracting 4: " mc.decr(key, 4, hash));
+ * System.out.println("counter after subtracting 1: " mc.decr(key, 1, hash));
+ * </pre>
+ * <h3>To retrieve an object from the cache:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "key";
+ * Object value = mc.get(key);
+ * </pre>
+ * <h3>To retrieve an object from the cache with custom hash:</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String key = "key";
+ * Integer hash = new Integer(45);
+ * Object value = mc.get(key, hash);
+ * </pre>
+ * <h3>To retrieve an multiple objects from the cache</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String[] keys = { "key", "key1", "key2" };
+ * Object value = mc.getMulti(keys);
+ * </pre>
+ * <h3>To retrieve an multiple objects from the cache with custom hashing</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * String[] keys = { "key", "key1", "key2" };
+ * Integer[] hashes = { new Integer(45), new Integer(32), new Integer(44) };
+ * Object value = mc.getMulti(keys, hashes);
+ * </pre>
+ * <h3>To flush all items in server(s)</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * mc.flushAll();
+ * </pre>
+ * <h3>To get stats from server(s)</h3>
+ * <pre>
+ * MemCachedClient mc = new MemCachedClient();
+ * Map stats = mc.stats();
+ * </pre>
+ *
+ * @author greg whalin <greg@meetup.com>
+ * @author Richard 'toast' Russo <russor@msoe.edu>
+ * @author Kevin Burton <burton@peerfear.org>
+ * @version 1.2
+ */
+public class MemCachedClient {
+
+ // logger
+ private static Logger log =
+ Logger.getLogger(MemCachedClient.class.getName());
+
+ // return codes
+ private static final String VALUE = "VALUE"; // start of value line from server
+ private static final String STATS = "STAT"; // start of stats line from server
+ private static final String DELETED = "DELETED"; // successful deletion
+ private static final String NOTFOUND = "NOT_FOUND"; // record not found for delete or incr/decr
+ private static final String STORED = "STORED"; // successful store of data
+ private static final String NOTSTORED = "NOT_STORED"; // data not stored
+ private static final String OK = "OK"; // success
+ private static final String END = "END"; // end of data from server
+ private static final String ERROR = "ERROR"; // invalid command name from client
+ private static final String CLIENT_ERROR = "CLIENT_ERROR"; // client error in input line - invalid protocol
+ private static final String SERVER_ERROR = "SERVER_ERROR"; // server error
+
+ // values for cache flags
+ //
+ // using 8 (1 << 3) so other clients don't try to unpickle/unstore/whatever
+ // things that are serialized... I don't think they'd like it. :)
+ private static final int F_COMPRESSED = 2;
+ private static final int F_SERIALIZED = 8;
+
+ // flags
+ private boolean primitiveAsString;
+ private boolean compressEnable;
+ private long compressThreshold;
+ private String defaultEncoding;
+
+ /**
+ * Creates a new instance of MemCachedClient.
+ */
+ public MemCachedClient() {
+ init();
+ }
+
+ /**
+ * Initializes client object to defaults.
+ *
+ * This enables compression and sets compression threshhold to 15 KB.
+ */
+ private void init() {
+ this.primitiveAsString = false;
+ this.compressEnable = true;
+ this.compressThreshold = 15360;
+ this.defaultEncoding = "UTF-8";
+ }
+
+ /**
+ * Enables storing primitive types as their String values.
+ *
+ * @param primitiveAsString if true, then store all primitives as their string value.
+ */
+ public void setPrimitiveAsString(boolean primitiveAsString) {
+ this.primitiveAsString = primitiveAsString;
+ }
+
+ /**
+ * Sets default String encoding when storing primitives as Strings.
+ * Default is UTF-8.
+ *
+ * @param defaultEncoding
+ */
+ public void setDefaultEncoding(String defaultEncoding) {
+ this.defaultEncoding = defaultEncoding;
+ }
+
+ /**
+ * Enable storing compressed data, provided it meets the threshold requirements.
+ *
+ * If enabled, data will be stored in compressed form if it is<br/>
+ * longer than the threshold length set with setCompressThreshold(int)<br/>
+ *<br/>
+ * The default is that compression is enabled.<br/>
+ *<br/>
+ * Even if compression is disabled, compressed data will be automatically<br/>
+ * decompressed.
+ *
+ * @param compressEnable <CODE>true</CODE> to enable compression, <CODE>false</CODE> to disable compression
+ */
+ public void setCompressEnable(boolean compressEnable) {
+ this.compressEnable = compressEnable;
+ }
+
+ /**
+ * Sets the required length for data to be considered for compression.
+ *
+ * If the length of the data to be stored is not equal or larger than this value, it will
+ * not be compressed.
+ *
+ * This defaults to 15 KB.
+ *
+ * @param compressThreshold required length of data to consider compression
+ */
+ public void setCompressThreshold(long compressThreshold) {
+ this.compressThreshold = compressThreshold;
+ }
+
+ /**
+ * Deletes an object from cache given cache key.
+ *
+ * @param key the key to be removed
+ * @return <code>true</code>, if the data was deleted successfully
+ */
+ public boolean delete(String key) {
+ return delete(key, null, null);
+ }
+
+ /**
+ * Deletes an object from cache given cache key and expiration date.
+ *
+ * @param key the key to be removed
+ * @param expiry when to expire the record.
+ * @return <code>true</code>, if the data was deleted successfully
+ */
+ public boolean delete(String key, Date expiry) {
+ return delete(key, null, expiry);
+ }
+
+ /**
+ * Deletes an object from cache given cache key, a delete time, and an optional hashcode.
+ *
+ * The item is immediately made non retrievable.<br/>
+ * Keep in mind {@link #add(String, Object) add} and {@link #replace(String, Object) replace}<br/>
+ * will fail when used with the same key will fail, until the server reaches the<br/>
+ * specified time. However, {@link #set(String, Object) set} will succeed,<br/>
+ * and the new value will not be deleted.
+ *
+ * @param key the key to be removed
+ * @param hashCode if not null, then the int hashcode to use
+ * @param expiry when to expire the record.
+ * @return <code>true</code>, if the data was deleted successfully
+ */
+ public boolean delete(String key, Integer hashCode, Date expiry) {
+
+ // get SockIO obj from hash or from key
+ SockIOPool.SockIO sock = SockIOPool.getInstance().getSock(key, hashCode);
+
+ // return false if unable to get SockIO obj
+ if (sock == null)
+ return false;
+
+ // build command
+ StringBuffer command = new StringBuffer("delete " + key);
+ if (expiry != null) {
+ command.append(" " + expiry.getTime() / 1000);
+ }
+ command.append("\r\n");
+
+ try {
+ sock.write(command.toString().getBytes());
+ sock.flush();
+
+ // if we get appropriate response back, then we return true
+ String line = sock.readLine();
+ if (DELETED.equals(line)) {
+ log.info("++++ deletion of key: " + key + " from cache was a success");
+
+ // return sock to pool and bail here
+ sock.close();
+ return true;
+
+ } else if (NOTFOUND.equals(line)) {
+ log.info("++++ deletion of key: " + key + " from cache failed as the key was not found");
+
+ } else {
+ log.error("++++ error deleting key: " + key);
+ log.error(line);
+ }
+ }
+ catch (IOException e) {
+ // exception thrown
+ log.error("++++ exception thrown while writing bytes to server on delete");
+ log.error(e.getMessage(), e);
+
+ try {
+ sock.trueClose();
+ }
+ catch(IOException ioe) {
+ log.error("++++ failed to close socket : " + sock.toString());
+ }
+
+ sock = null;
+ }
+
+ if (sock != null)
+ sock.close();
+ return false;
+ }
+
+ /**
+ * Stores data on the server; only the key and the value are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @return true, if the data was successfully stored
+ */
+ public boolean set(String key, Object value) {
+ return set("set", key, value, null, null, primitiveAsString);
+ }
+
+ /**
+ * Stores data on the server; only the key and the value are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param hashCode if not null, then the int hashcode to use
+ * @return true, if the data was successfully stored
+ */
+ public boolean set(String key, Object value, Integer hashCode) {
+ return set("set", key, value, null, hashCode, primitiveAsString);
+ }
+
+ /**
+ * Stores data on the server; the key, value, and an expiration time are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param expiry when to expire the record
+ * @return true, if the data was successfully stored
+ */
+ public boolean set(String key, Object value, Date expiry) {
+ return set("set", key, value, expiry, null, primitiveAsString);
+ }
+
+ /**
+ * Stores data on the server; the key, value, and an expiration time are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param expiry when to expire the record
+ * @param hashCode if not null, then the int hashcode to use
+ * @return true, if the data was successfully stored
+ */
+ public boolean set(String key, Object value, Date expiry, Integer hashCode) {
+ return set("set", key, value, expiry, hashCode, primitiveAsString);
+ }
+
+ /**
+ * Adds data to the server; only the key and the value are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @return true, if the data was successfully stored
+ */
+ public boolean add(String key, Object value) {
+ return set("add", key, value, null, null, primitiveAsString);
+ }
+
+ /**
+ * Adds data to the server; the key, value, and an optional hashcode are passed in.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param hashCode if not null, then the int hashcode to use
+ * @return true, if the data was successfully stored
+ */
+ public boolean add(String key, Object value, Integer hashCode) {
+ return set("add", key, value, null, hashCode, primitiveAsString);
+ }
+
+ /**
+ * Adds data to the server; the key, value, and an expiration time are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param expiry when to expire the record
+ * @return true, if the data was successfully stored
+ */
+ public boolean add(String key, Object value, Date expiry) {
+ return set("add", key, value, expiry, null, primitiveAsString);
+ }
+
+ /**
+ * Adds data to the server; the key, value, and an expiration time are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param expiry when to expire the record
+ * @param hashCode if not null, then the int hashcode to use
+ * @return true, if the data was successfully stored
+ */
+ public boolean add(String key, Object value, Date expiry, Integer hashCode) {
+ return set("add", key, value, expiry, hashCode, primitiveAsString);
+ }
+
+ /**
+ * Updates data on the server; only the key and the value are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @return true, if the data was successfully stored
+ */
+ public boolean replace(String key, Object value) {
+ return set("replace", key, value, null, null, primitiveAsString);
+ }
+
+ /**
+ * Updates data on the server; only the key and the value and an optional hash are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param hashCode if not null, then the int hashcode to use
+ * @return true, if the data was successfully stored
+ */
+ public boolean replace(String key, Object value, Integer hashCode) {
+ return set("replace", key, value, null, hashCode, primitiveAsString);
+ }
+
+ /**
+ * Updates data on the server; the key, value, and an expiration time are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param expiry when to expire the record
+ * @return true, if the data was successfully stored
+ */
+ public boolean replace(String key, Object value, Date expiry) {
+ return set("replace", key, value, expiry, null, primitiveAsString);
+ }
+
+ /**
+ * Updates data on the server; the key, value, and an expiration time are specified.
+ *
+ * @param key key to store data under
+ * @param value value to store
+ * @param expiry when to expire the record
+ * @param hashCode if not null, then the int hashcode to use
+ * @return true, if the data was successfully stored
+ */
+ public boolean replace(String key, Object value, Date expiry, Integer hashCode) {
+ return set("replace", key, value, expiry, hashCode, primitiveAsString);
+ }
+
+ /**
+ * Stores data to cache.
+ *
+ * If data does not already exist for this key on the server, or if the key is being<br/>
+ * deleted, the specified value will not be stored.<br/>
+ * The server will automatically delete the value when the expiration time has been reached.<br/>
+ * <br/>
+ * If compression is enabled, and the data is longer than the compression threshold<br/>
+ * the data will be stored in compressed form.<br/>
+ * <br/>
+ * As of the current release, all objects stored will use java serialization.
+ *
+ * @param cmdname action to take (set, add, replace)
+ * @param key key to store cache under
+ * @param value object to cache
+ * @param expiry expiration
+ * @param hashCode if not null, then the int hashcode to use
+ * @param asString store this object as a string?
+ * @return true/false indicating success
+ */
+ private boolean set(String cmdname, String key, Object value, Date expiry, Integer hashCode, boolean asString) {
+
+ // get SockIO obj
+ SockIOPool.SockIO sock = SockIOPool.getInstance().getSock(key, hashCode);
+
+ if (sock == null)
+ return false;
+
+ if (expiry == null)
+ expiry = new Date(0);
+
+ // store flags
+ int flags = 0;
+
+ // byte array to hold data
+ byte[] val;
+
+ if (NativeHandler.isHandled(value)) {
+
+ if (asString) {
+ // useful for sharing data between java and non-java
+ // and also for storing ints for the increment method
+ log.info("++++ storing data as a string for key: " + key + " for class: " + value.getClass().getName());
+ try {
+ val = value.toString().getBytes(defaultEncoding);
+ }
+ catch (UnsupportedEncodingException ue) {
+ log.error("invalid encoding type used: " + defaultEncoding);
+ sock.close();
+ return false;
+ }
+ }
+ else {
+ log.info( "Storing with native handler..." );
+
+ try {
+ val = NativeHandler.encode( value );
+ }
+ catch (Exception e) {
+ log.error("Failed to native handle obj", e);
+
+ sock.close();
+ return false;
+ }
+ }
+ }
+ else {
+ // always serialize for non-primitive types
+ log.info("++++ serializing for key: " + key + " for class: " + value.getClass().getName());
+ try {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream();
+ (new ObjectOutputStream(bos)).writeObject(value);
+ val = bos.toByteArray();
+ flags |= F_SERIALIZED;
+ }
+ catch (IOException e) {
+ // if we fail to serialize, then
+ // we bail
+ log.error("failed to serialize obj", e);
+ log.error(value.toString());
+
+ // return socket to pool and bail
+ sock.close();
+ return false;
+ }
+ }
+
+ // now try to compress if we want to
+ // and if the length is over the threshold
+ if (compressEnable && val.length > compressThreshold) {
+ log.info("++++ trying to compress data");
+ log.info("++++ size prior to compression: " + val.length);
+
+ try {
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(val.length);
+ GZIPOutputStream gos = new GZIPOutputStream(bos);
+ gos.write(val, 0, val.length);
+ gos.finish();
+
+ // store it and set compression flag
+ val = bos.toByteArray();
+ flags |= F_COMPRESSED;
+
+ log.info("++++ compression succeeded, size after: " + val.length);
+
+ }
+ catch (IOException e) {
+ log.error("IOException while compressing stream: " + e.getMessage());
+ log.error("storing data uncompressed");
+ }
+ }
+
+ // now write the data to the cache server
+ try {
+ String cmd = cmdname + " " + key + " " + flags + " "
+ + expiry.getTime() / 1000 + " " + val.length + "\r\n";
+ sock.write(cmd.getBytes());
+ sock.write(val);
+ sock.write("\r\n".getBytes());
+ sock.flush();
+
+ // get result code
+ String line = sock.readLine();
+ log.info("++++ memcache cmd (result code): " + cmd + " (" + line + ")");
+
+ if (STORED.equals(line)) {
+ log.info("++++ data successfully stored for key: " + key);
+ sock.close();
+ return true;
+
+ }
+ else if (NOTSTORED.equals(line)) {
+ log.info("++++ data not stored in cache for key: " + key);
+
+ }
+ else {
+ log.error("++++ error storing data in cache for key: " + key + " -- length: " + val.length);
+ log.error(line);
+ }
+ }
+ catch (IOException e) {
+ // exception thrown
+ log.error("++++ exception thrown while writing bytes to server on delete");
+ log.error(e.getMessage(), e);
+
+ try {
+ sock.trueClose();
+ }
+ catch (IOException ioe) {
+ log.error("++++ failed to close socket : " + sock.toString());
+ }
+
+ sock = null;
+ }
+
+ if (sock != null)
+ sock.close();
+
+ return false;
+ }
+
+ /**
+ * Store a counter to memcached given a key
+ *
+ * @param key cache key
+ * @param counter number to store
+ * @return true/false indicating success
+ */
+ public boolean storeCounter(String key, long counter) {
+ return set("set", key, new Long(counter), null, null, true);
+ }
+
+ /**
+ * Store a counter to memcached given a key
+ *
+ * @param key cache key
+ * @param counter number to store
+ * @return true/false indicating success
+ */
+ public boolean storeCounter(String key, Long counter) {
+ return set("set", key, counter, null, null, true);
+ }
+
+ /**
+ * Store a counter to memcached given a key
+ *
+ * @param key cache key
+ * @param counter number to store
+ * @param hashCode if not null, then the int hashcode to use
+ * @return true/false indicating success
+ */
+ public boolean storeCounter(String key, Long counter, Integer hashCode) {
+ return set("set", key, counter, null, hashCode, true);
+ }
+
+ /**
+ * Returns value in counter at given key as long.
+ *
+ * @param key cache ket
+ * @return counter value or -1 if not found
+ */
+ public long getCounter(String key) {
+ return getCounter(key, null);
+ }
+
+ /**
+ * Returns value in counter at given key as long.
+ *
+ * @param key cache ket
+ * @param hashCode if not null, then the int hashcode to use
+ * @return counter value or -1 if not found
+ */
+ public long getCounter(String key, Integer hashCode) {
+ long counter = -1;
+ try {
+ counter = ((Long) get(key, hashCode)).longValue();
+ }
+ catch (Exception ex) {
+ // not found or error getting out
+ log.error("counter not found at key: " + key);
+ }
+
+ return counter;
+ }
+
+ /**
+ * Increment the value at the specified key by 1, and then return it.
+ *
+ * @param key key where the data is stored
+ * @return -1, if the key is not found, the value after incrementing otherwise
+ */
+ public long incr(String key) {
+ return incrdecr("incr", key, 1, null);
+ }
+
+ /**
+ * Increment the value at the specified key by passed in val.
+ *
+ * @param key key where the data is stored
+ * @param inc how much to increment by
+ * @return -1, if the key is not found, the value after incrementing otherwise
+ */
+ public long incr(String key, long inc) {
+ return incrdecr("incr", key, inc, null);
+ }
+
+ /**
+ * Increment the value at the specified key by the specified increment, and then return it.
+ *
+ * @param key key where the data is stored
+ * @param inc how much to increment by
+ * @param hashCode if not null, then the int hashcode to use
+ * @return -1, if the key is not found, the value after incrementing otherwise
+ */
+ public long incr(String key, long inc, Integer hashCode) {
+ return incrdecr("incr", key, inc, hashCode);
+ }
+
+ /**
+ * Decrement the value at the specified key by 1, and then return it.
+ *
+ * @param key key where the data is stored
+ * @return -1, if the key is not found, the value after incrementing otherwise
+ */
+ public long decr(String key) {
+ return incrdecr("decr", key, 1, null);
+ }
+
+ /**
+ * Decrement the value at the specified key by passed in value, and then return it.
+ *
+ * @param key key where the data is stored
+ * @param inc how much to increment by
+ * @return -1, if the key is not found, the value after incrementing otherwise
+ */
+ public long decr(String key, long inc) {
+ return incrdecr("decr", key, inc, null);
+ }
+
+ /**
+ * Decrement the value at the specified key by the specified increment, and then return it.
+ *
+ * @param key key where the data is stored
+ * @param inc how much to increment by
+ * @param hashCode if not null, then the int hashcode to use
+ * @return -1, if the key is not found, the value after incrementing otherwise
+ */
+ public long decr(String key, long inc, Integer hashCode) {
+ return incrdecr("decr", key, inc, hashCode);
+ }
+
+ /**
+ * Increments/decrements the value at the specified key by inc.
+ *
+ * Note that the server uses a 32-bit unsigned integer, and checks for<br/>
+ * underflow. In the event of underflow, the result will be zero. Because<br/>
+ * Java lacks unsigned types, the value is returned as a 64-bit integer.<br/>
+ * The server will only decrement a value if it already exists;<br/>
+ * if a value is not found, -1 will be returned.
+ *
+ * @param cmdname increment/decrement
+ * @param key cache key
+ * @param inc amount to incr or decr
+ * @param hashCode if not null, then the int hashcode to use
+ * @return new value or -1 if not exist
+ */
+ private long incrdecr(String cmdname, String key, long inc, Integer hashCode) {
+
+ // get SockIO obj for given cache key
+ SockIOPool.SockIO sock = SockIOPool.getInstance().getSock(key, hashCode);
+
+ if (sock == null)
+ return -1;
+
+ try {
+ String cmd = cmdname + " " + key + " " + inc + "\r\n";
+ log.debug("++++ memcache incr/decr command: " + cmd);
+
+ sock.write(cmd.getBytes());
+ sock.flush();
+
+ // get result back
+ String line = sock.readLine();
+
+ if (line.matches("\\d+")) {
+
+ // return sock to pool and return result
+ sock.close();
+ return Long.parseLong(line);
+
+ } else if (NOTFOUND.equals(line)) {
+ log.info("++++ key not found to incr/decr for key: " + key);
+
+ } else {
+ log.error("error incr/decr key: " + key);
+ }
+ }
+ catch (IOException e) {
+ // exception thrown
+ log.error("++++ exception thrown while writing bytes to server on incr/decr");
+ log.error(e.getMessage(), e);
+
+ try {
+ sock.trueClose();
+ }
+ catch(IOException ioe) {
+ log.error("++++ failed to close socket : " + sock.toString());
+ }
+
+ sock = null;
+ }
+
+ if (sock != null)
+ sock.close();
+ return -1;
+ }
+
+ /**
+ * Retrieve a key from the server, using a specific hash.
+ *
+ * If the data was compressed or serialized when compressed, it will automatically<br/>
+ * be decompressed or serialized, as appropriate. (Inclusive or)<br/>
+ *<br/>
+ * Non-serialized data will be returned as a string, so explicit conversion to<br/>
+ * numeric types will be necessary, if desired<br/>
+ *
+ * @param key key where data is stored
+ * @return the object that was previously stored, or null if it was not previously stored
+ */
+ public Object get(String key) {
+ return get(key, null);
+ }
+
+ /**
+ * Retrieve a key from the server, using a specific hash.
+ *
+ * If the data was compressed or serialized when compressed, it will automatically<br/>
+ * be decompressed or serialized, as appropriate. (Inclusive or)<br/>
+ *<br/>
+ * Non-serialized data will be returned as a string, so explicit conversion to<br/>
+ * numeric types will be necessary, if desired<br/>
+ *
+ * @param key key where data is stored
+ * @param hashCode if not null, then the int hashcode to use
+ * @return the object that was previously stored, or null if it was not previously stored
+ */
+ public Object get(String key, Integer hashCode) {
+
+ // get SockIO obj using cache key
+ SockIOPool.SockIO sock = SockIOPool.getInstance().getSock(key, hashCode);
+
+ if (sock == null)
+ return null;
+
+ try {
+ String cmd = "get " + key + "\r\n";
+ log.debug("++++ memcache get command: " + cmd);
+
+ sock.write(cmd.getBytes());
+ sock.flush();
+
+ // build empty map
+ // and fill it from server
+ Map hm = new HashMap();
+ loadItems(sock, hm);
+
+ // debug code
+ log.debug("++++ memcache: got back " + hm.size() + " results");
+
+ // return the value for this key if we found it
+ // else return null
+ sock.close();
+ return hm.get(key);
+
+ }
+ catch (IOException e) {
+ // exception thrown
+ log.error("++++ exception thrown while trying to get object from cache for key: " + key);
+ log.error(e.getMessage(), e);
+
+ try {
+ sock.trueClose();
+ }
+ catch(IOException ioe) {
+ log.error("++++ failed to close socket : " + sock.toString());
+ }
+ sock = null;
+ }
+
+ if (sock != null)
+ sock.close();
+
+ return null;
+ }
+
+ /**
+ * Retrieve multiple objects from the memcache.
+ *
+ * This is recommended over repeated calls to {@link #get(String) get()}, since it<br/>
+ * is more efficient.<br/>
+ *
+ * @param keys String array of keys to retrieve
+ * @return Object array ordered in same order as key array containing results
+ */
+ public Object[] getMultiArray(String[] keys) {
+ return getMultiArray(keys, null);
+ }
+
+ /**
+ * Retrieve multiple objects from the memcache.
+ *
+ * This is recommended over repeated calls to {@link #get(String) get()}, since it<br/>
+ * is more efficient.<br/>
+ *
+ * @param keys String array of keys to retrieve
+ * @param hashCodes if not null, then the Integer array of hashCodes
+ * @return Object array ordered in same order as key array containing results
+ */
+ public Object[] getMultiArray(String[] keys, Integer[] hashCodes) {
+
+ Map data = getMulti(keys, hashCodes);
+
+ Object[] res = new Object[keys.length];
+ for (int i = 0; i < keys.length; i++) {
+ res[i] = data.get(keys[i]);
+ }
+
+ return res;
+ }
+
+ /**
+ * Retrieve multiple objects from the memcache.
+ *
+ * This is recommended over repeated calls to {@link #get(String) get()}, since it<br/>
+ * is more efficient.<br/>
+ *
+ * @param keys String array of keys to retrieve
+ * @return a hashmap with entries for each key is found by the server,
+ * keys that are not found are not entered into the hashmap, but attempting to
+ * retrieve them from the hashmap gives you null.
+ */
+ public Map getMulti(String[] keys) {
+ return getMulti(keys, null);
+ }
+
+ /**
+ * Retrieve multiple keys from the memcache.
+ *
+ * This is recommended over repeated calls to {@link #get(String) get()}, since it<br/>
+ * is more efficient.<br/>
+ *
+ * @param keys keys to retrieve
+ * @param hashCodes if not null, then the Integer array of hashCodes
+ * @return a hashmap with entries for each key is found by the server,
+ * keys that are not found are not entered into the hashmap, but attempting to
+ * retrieve them from the hashmap gives you null.
+ */
+ public Map getMulti(String[] keys, Integer[] hashCodes) {
+ Map sockKeys = new HashMap();
+
+ for (int i = 0; i < keys.length; ++i) {
+
+ Integer hash = null;
+ if (hashCodes != null && hashCodes.length > i) {
+ hash = hashCodes[i];
+ }
+
+ // get SockIO obj from cache key
+ SockIOPool.SockIO sock = SockIOPool.getInstance().getSock(keys[i], hash);
+
+ if (sock == null)
+ continue;
+
+ // store in map and list if not already
+ if (!sockKeys.containsKey(sock.getHost())) {
+ sockKeys.put(sock.getHost(), new StringBuffer());
+ }
+
+ ((StringBuffer) sockKeys.get(sock.getHost())).append(" " + keys[i]);
+
+ // return to pool
+ sock.close();
+ }
+
+ log.info( "multi get socket count : " + sockKeys.size() );
+
+ // now query memcache
+ Map ret = new HashMap();
+ for (Iterator i = sockKeys.keySet().iterator(); i.hasNext();) {
+ // get SockIO obj from hostname
+ String host = (String) i.next();
+ SockIOPool.SockIO sock = SockIOPool.getInstance().getConnection(host);
+
+ try {
+ String cmd = "get" + (StringBuffer) sockKeys.get(host) + "\r\n";
+ log.debug("++++ memcache getMulti cmd: " + cmd);
+ sock.write(cmd.getBytes());
+ sock.flush();
+ loadItems(sock, ret);
+ }
+ catch (IOException e) {
+ // exception thrown
+ log.error("++++ exception thrown while getting from cache on getMulti");
+ log.error(e.getMessage(), e);
+
+ // clear this sockIO obj from the list
+ // and from the map containing keys
+ i.remove();
+ try {
+ sock.trueClose();
+ }
+ catch(IOException ioe) {
+ log.error("++++ failed to close socket : " + sock.toString());
+ }
+ sock = null;
+ }
+
+ // Return socket to pool
+ if (sock != null)
+ sock.close();
+ }
+
+ log.debug("++++ memcache: got back " + ret.size() + " results");
+ return ret;
+ }
+
+ /**
+ * This method loads the data from cache into a Map.
+ *
+ * Pass a SockIO object which is ready to receive data and a HashMap<br/>
+ * to store the results.
+ *
+ * @param sock socket waiting to pass back data
+ * @param hm hashmap to store data into
+ * @throws IOException if io exception happens while reading from socket
+ */
+ private void loadItems(SockIOPool.SockIO sock, Map hm) throws IOException {
+ while (true) {
+ String line = sock.readLine();
+ log.debug("++++ line: " + line);
+
+ if (line.startsWith(VALUE)) {
+ String[] info = line.split(" ");
+ String key = info[1];
+ int flag = Integer.parseInt(info[2]);
+ int length = Integer.parseInt(info[3]);
+
+ log.debug("++++ key: " + key);
+ log.debug("++++ flags: " + flag);
+ log.debug("++++ length: " + length);
+
+ // read obj into buffer
+ byte[] buf = new byte[length];
+ sock.read(buf);
+ sock.clearEOL();
+
+ // ready object
+ Object o;
+
+ // check for compression
+ if ((flag & F_COMPRESSED) != 0) {
+ try {
+ // read the input stream, and write to a byte array output stream since
+ // we have to read into a byte array, but we don't know how large it
+ // will need to be, and we don't want to resize it a bunch
+ GZIPInputStream gzi = new GZIPInputStream(new ByteArrayInputStream(buf));
+ ByteArrayOutputStream bos = new ByteArrayOutputStream(buf.length);
+
+ int count;
+ byte[] tmp = new byte[2048];
+ while ((count = gzi.read(tmp)) != -1) {
+ bos.write(tmp, 0, count);
+ }
+
+ // store uncompressed back to buffer
+ buf = bos.toByteArray();
+ gzi.close();
+ }
+ catch (IOException e) {
+ log.error("++++ IOException thrown while trying to uncompress input stream for key: " + key);
+ log.error(e.getMessage(), e);
+ throw new NestedIOException("++++ IOException thrown while trying to uncompress input stream for key: " + key, e);
+ }
+ }
+
+ // we can only take out serialized objects
+ if ((flag & F_SERIALIZED) == 0) {
+ if (primitiveAsString) {
+ // pulling out string value
+ log.info("++++ retrieving object and stuffing into a string.");
+ o = new String(buf, defaultEncoding);
+ }
+ else {
+ // decoding object
+ try {
+ o = NativeHandler.decode( buf );
+ }
+ catch ( Exception e ) {
+ log.error( "++++ Exception thrown while trying to deserialize for key: " + key, e );
+ throw new NestedIOException( e );
+ }
+ }
+ }
+ else {
+ // deserialize if the data is serialized
+ ObjectInputStream ois = new ObjectInputStream(new ByteArrayInputStream(buf));
+ try {
+ o = ois.readObject();
+ log.info("++++ deserializing " + o.getClass());
+ }
+ catch (ClassNotFoundException e) {
+ log.error("++++ ClassNotFoundException thrown while trying to deserialize for key: " + key, e);
+ throw new NestedIOException("+++ failed while trying to deserialize for key: " + key, e);
+ }
+ }
+
+ // store the object into the cache
+ hm.put(key, o);
+ }
+ else if (END.equals(line)) {
+ log.debug("++++ finished reading from cache server");
+ break;
+ }
+ }
+ }
+
+ /**
+ * Invalidates the entire cache.
+ *
+ * Will return true only if succeeds in clearing all servers.
+ *
+ * @return success true/false
+ */
+ public boolean flushAll() {
+ return flushAll(null);
+ }
+
+ /**
+ * Invalidates the entire cache.
+ *
+ * Will return true only if succeeds in clearing all servers.
+ * If pass in null, then will try to flush all servers.
+ *
+ * @param servers optional array of host(s) to flush (host:port)
+ * @return success true/false
+ */
+ public boolean flushAll(String[] servers) {
+
+ // get SockIOPool instance
+ SockIOPool pool = SockIOPool.getInstance();
+
+ // return false if unable to get SockIO obj
+ if (pool == null) {
+ log.error("++++ unable to get SockIOPool instance");
+ return false;
+ }
+
+ // get all servers and iterate over them
+ servers = (servers == null)
+ ? pool.getServers()
+ : servers;
+
+ // if no servers, then return early
+ if (servers == null || servers.length <= 0) {
+ log.error("++++ no servers to flush");
+ return false;
+ }
+
+ boolean success = true;
+
+ for (int i = 0; i < servers.length; i++) {
+
+ SockIOPool.SockIO sock = pool.getConnection(servers[i]);
+ if (sock == null) {
+ log.error("++++ unable to get connection to : " + servers[i]);
+ success = false;
+ continue;
+ }
+
+ // build command
+ String command = "flush_all\r\n";
+
+ try {
+ sock.write(command.getBytes());
+ sock.flush();
+
+ // if we get appropriate response back, then we return true
+ String line = sock.readLine();
+ success = (OK.equals(line))
+ ? success && true
+ : false;
+ }
+ catch (IOException e) {
+ // exception thrown
+ log.error("++++ exception thrown while writing bytes to server on delete");
+ log.error(e.getMessage(), e);
+
+ try {
+ sock.trueClose();
+ }
+ catch (IOException ioe) {
+ log.error("++++ failed to close socket : " + sock.toString());
+ }
+
+ success = false;
+ sock = null;
+ }
+
+ if (sock != null)
+ sock.close();
+ }
+
+ return success;
+ }
+
+ /**
+ * Retrieves stats for all servers.
+ *
+ * Returns a map keyed on the servername.
+ * The value is another map which contains stats
+ * with stat name as key and value as value.
+ *
+ * @return Stats map
+ */
+ public Map stats() {
+ return stats(null);
+ }
+
+ /**
+ * Retrieves stats for passed in servers (or all servers).
+ *
+ * Returns a map keyed on the servername.
+ * The value is another map which contains stats
+ * with stat name as key and value as value.
+ *
+ * @param servers string array of servers to retrieve stats from, or all if this is null
+ * @return Stats map
+ */
+ public Map stats(String[] servers) {
+
+ // get SockIOPool instance
+ SockIOPool pool = SockIOPool.getInstance();
+
+ // return false if unable to get SockIO obj
+ if (pool == null) {
+ log.error("++++ unable to get SockIOPool instance");
+ return null;
+ }
+
+ // get all servers and iterate over them
+ servers = (servers == null)
+ ? pool.getServers()
+ : servers;
+
+ // if no servers, then return early
+ if (servers == null || servers.length <= 0) {
+ log.error("++++ no servers to check stats");
+ return null;
+ }
+
+ // array of stats Maps
+ Map statsMaps = new HashMap();
+
+ for (int i = 0; i < servers.length; i++) {
+
+ SockIOPool.SockIO sock = pool.getConnection(servers[i]);
+ if (sock == null) {
+ log.error("++++ unable to get connection to : " + servers[i]);
+ continue;
+ }
+
+ // build command
+ String command = "stats\r\n";
+
+ try {
+ sock.write(command.getBytes());
+ sock.flush();
+
+ // map to hold key value pairs
+ Map stats = new HashMap();
+
+ // loop over results
+ while (true) {
+ String line = sock.readLine();
+ log.debug("++++ line: " + line);
+
+ if (line.startsWith(STATS)) {
+ String[] info = line.split(" ");
+ String key = info[1];
+ String value = info[2];
+
+ log.debug("++++ key : " + key);
+ log.debug("++++ value: " + value);
+
+ stats.put(key, value);
+
+ }
+ else if (END.equals(line)) {
+ // finish when we get end from server
+ log.debug("++++ finished reading from cache server");
+ break;
+ }
+
+ statsMaps.put(servers[i], stats);
+ }
+ }
+ catch (IOException e) {
+ // exception thrown
+ log.error("++++ exception thrown while writing bytes to server on delete");
+ log.error(e.getMessage(), e);
+
+ try {
+ sock.trueClose();
+ }
+ catch (IOException ioe) {
+ log.error("++++ failed to close socket : " + sock.toString());
+ }
+
+ sock = null;
+ }
+
+ if (sock != null)
+ sock.close();
+ }
+
+ return statsMaps;
+ }
+}
514 src/com/danga/MemCached/NativeHandler.java
@@ -0,0 +1,514 @@
+/**
+ * MemCached Java client
+ * Copyright (c) 2005
+ *
+ * This library is free software; you can redistribute it and/or
+ * modify it under the terms of the GNU Lesser General Public
+ * License as published by the Free Software Foundation; either
+ * version 2.1 of the License, or (at your option) any later
+ * version.
+ *
+ * This library is distributed in the hope that it will be
+ * useful, but WITHOUT ANY WARRANTY; without even the implied
+ * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
+ * PURPOSE. See the GNU Lesser General Public License for more
+ * details.
+ *
+ * You should have received a copy of the GNU Lesser General Public
+ * License along with this library; if not, write to the Free Software
+ * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
+ *
+ * @author Kevin A. Burton <burton@peerfear.org>
+ * @author Greg Whalin <greg@meetup.com>
+ * @version 1.2
+ */
+package com.danga.MemCached;
+
+import java.util.Date;
+
+/**
+ * Handle encoding standard Java types directly which can result in significant
+ * memory savings:
+ *
+ * Currently the Memcached driver for Java supports the setSerialize() option.
+ * This can increase performance in some situations but has a few issues:
+ *
+ * Code that performs class casting will throw ClassCastExceptions when
+ * setSerialize is enabled. For example:
+ *
+ * mc.set( "foo", new Integer( 1 ) ); Integer output = (Integer)mc.get("foo");
+ *
+ * Will work just file when setSerialize is true but when its false will just throw
+ * a ClassCastException.
+ *
+ * Also internally it doesn't support Boolean and since toString is called wastes a
+ * lot of memory and causes additional performance issue. For example an Integer
+ * can take anywhere from 1 byte to 10 bytes.
+ *
+ * Due to the way the memcached slab allocator works it seems like a LOT of wasted
+ * memory to store primitive types as serialized objects (from a performance and
+ * memory perspective). In our applications we have millions of small objects and
+ * wasted memory would become a big problem.
+ *
+ * For example a Serialized Boolean takes 47 bytes which means it will fit into the
+ * 64byte LRU. Using 1 byte means it will fit into the 8 byte LRU thus saving 8x
+ * the memory. This also saves the CPU performance since we don't have to
+ * serialize bytes back and forth and we can compute the byte[] value directly.
+ *
+ * One problem would be when the user calls get() because doing so would require
+ * the app to know the type of the object stored as a bytearray inside memcached
+ * (since the user will probably cast).
+ *
+ * If we assume the basic types are interned we could use the first byte as the
+ * type with the remaining bytes as the value. Then on get() we could read the
+ * first byte to determine the type and then construct the correct object for it.
+ * This would prevent the ClassCastException I talked about above.
+ *
+ * We could remove the setSerialize() option and just assume that standard VM types
+ * are always internd in this manner.
+ *
+ * mc.set( "foo", new Boolean.TRUE ); Boolean b = (Boolean)mc.get( "foo" );
+ *
+ * And the type casts would work because internally we would create a new Boolean
+ * to return back to the client.
+ *
+ * This would reduce memory footprint and allow for a virtual implementation of the
+ * Externalizable interface which is much faster than Serialzation.
+ *
+ * Currently the memory improvements would be:
+ *
+ * java.lang.Boolean - 8x performance improvement (now just two bytes)
+ * java.lang.Integer - 16x performance improvement (now just 5 bytes)
+ *
+ * Most of the other primitive types would benefit from this optimization.
+ * java.lang.Character being another obvious example.
+ *
+ * I know it seems like I'm being really picky here but for our application I'd
+ * save 1G of memory right off the bat. We'd go down from 1.152G of memory used
+ * down to 144M of memory used which is much better IMO.
+ *
+ *
+ * @author <a href="mailto:burton@peerfear.org">Kevin A. Burton</a>
+ * @author Greg Whalin <greg@meetup.com>
+ */
+public class NativeHandler {
+
+ // http://java.sun.com/docs/books/tutorial/native1.1/integrating/types.html
+