libnetty-java-3.1.0.CR1.orig/0000755000175000017500000000000011316313154015061 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/LICENSE.txt0000644000175000017500000006351111046712476016724 0ustar deckerdecker GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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. Copyright (C) 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., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 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. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libnetty-java-3.1.0.CR1.orig/NOTICE.txt0000644000175000017500000001022211146507775016617 0ustar deckerdecker The Netty Project ================= Please visit the Netty web site for more information: * http://www.jboss.org/netty/ Copyright (C) 2008, Red Hat Middleware LLC, and individual contributors by the @author tags. See the COPYRIGHT.txt in the distribution for a full listing of individual contributors. This product 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 product 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., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 USA Also, please refer to each LICENSE..txt file, which is located in the 'license' directory of the distribution file, for the license terms of the components that this product depends on. ------------------------------------------------------------------------------- This product contains the extensions to Java Collections Framework which has been derived from the works by JSR-166 EG, Doug Lea, and Jason T. Greene: * LICENSE: * license/LICENSE.jsr177y.txt (Public Domain) * HOMEPAGE: * http://gee.cs.oswego.edu/cgi-bin/viewcvs.cgi/jsr166/ * http://viewvc.jboss.org/cgi-bin/viewvc.cgi/jbosscache/experimental/jsr166/ This product contains a modified version of Robert Harder's Public Domain Base64 Encoder and Decoder, which can be obtained at: * LICENSE: * license/LICENSE.base64.txt (Public Domain) * HOMEPAGE: * http://iharder.sourceforge.net/current/java/base64/ This product optionally depends on 'XNIO', a simplified low-level I/O layer, which can be obtained at: * LICENSE: * license/LICENSE.xnio.txt (GNU LGPL 2.1) * HOMEPAGE: * http://www.jboss.org/xnio/ This product optionally depends on 'Protocol Buffers', Google's data interchange format, which can be obtained at: * LICENSE: * license/LICENSE.protobuf.txt (New BSD License) * HOMEPAGE: * http://code.google.com/p/protobuf/ This product optionally depends on 'SLF4J', a simple logging facade for Java, which can be obtained at: * LICENSE: * license/LICENSE.slf4j.txt (MIT License) * HOMEPAGE: * http://www.slf4j.org/ This product optionally depends on 'Apache Commons Logging', a logging framework, which can be obtained at: * LICENSE: * license/LICENSE.commons-logging.txt (Apache License 2.0) * HOMEPAGE: * http://commons.apache.org/logging/ This product optionally depends on 'Apache Log4J', a logging framework, which can be obtained at: * LICENSE: * license/LICENSE.log4j.txt (Apache License 2.0) * HOMEPAGE: * http://logging.apache.org/log4j/ This product optionally depends on 'JBoss Logging', a logging framework, which can be obtained at: * LICENSE: * license/LICENSE.jboss-logging.txt (GNU LGPL 2.1) * HOMEPAGE: * http://anonsvn.jboss.org/repos/common/common-logging-spi/ This product optionally depends on 'JBoss Microcontainer', which can be obtained at: * LICENSE: * license/LICENSE.jboss-microcontainer.txt (GNU LGPL 2.1) * HOMEPAGE: * http://www.jboss.org/jbossmc/ This product optionally depends on 'Apache Felix', an open source OSGi framework implementation, which can be obtained at: * LICENSE: * license/LICENSE.felix.txt (Apache License 2.0) * HOMEPAGE: * http://felix.apache.org/ This product optionally depends on 'Google Guice', a lightweight dependency injection framework, which can be obtained at: * LICENSE: * license/LICENSE.guice.txt (Apache License 2.0) * HOMEPAGE: * http://code.google.com/p/google-guice/ This product optionally depends on 'Spring Framework', which can be obtained at: * LICENSE: * license/LICENSE.spring.txt (Apache License 2.0) * HOMEPAGE: * http://www.springframework.org/ libnetty-java-3.1.0.CR1.orig/.fbfilter.xml0000644000175000017500000000272211171470731017465 0ustar deckerdecker libnetty-java-3.1.0.CR1.orig/pom.xml0000644000175000017500000005637211216752306016420 0ustar deckerdecker 4.0.0 org.jboss.netty netty bundle 3.1.0.CR1 The Netty Project http://www.jboss.org/netty/ The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance and high scalability protocol servers and clients. In other words, Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server. JBoss, by Red Hat http://www.jboss.org/ GNU Lesser General Public License http://www.gnu.org/licenses/lgpl.html 2008 scm:svn:http://anonsvn.jboss.org/repos/netty/tags/netty-3.1.0.CR1 scm:svn:https://svn.jboss.org/repos/netty/tags/netty-3.1.0.CR1 org.jboss.xnio xnio-api 1.2.0.GA compile true org.jboss.xnio xnio-nio 1.2.0.GA compile true com.google.protobuf protobuf-java 2.0.3 compile true javax.servlet servlet-api 2.5 compile true org.jboss.microcontainer jboss-kernel 2.0.2.GA compile true org.apache.felix org.osgi.core 1.2.0 compile true org.apache.felix org.osgi.compendium 1.2.0 compile true org.apache.felix javax.servlet org.apache.felix org.osgi.foundation com.google.code.guice guice 1.0 compile true org.springframework spring 2.0.8 compile true org.slf4j slf4j-api 1.5.6 compile true commons-logging commons-logging 1.1.1 compile true org.jboss.logging jboss-logging-spi 2.0.5.GA compile true log4j log4j 1.2.15 compile mail javax.mail jms javax.jms jmxtools com.sun.jdmk jmxri com.sun.jmx true junit junit 4.5 test org.easymock easymock 2.4 test org.easymock easymockclassextension 2.4 test org.slf4j slf4j-simple 1.5.6 test false maven-compiler-plugin 2.0.2 UTF-8 1.5 1.5 true true true maven-resources-plugin 2.3 UTF-8 maven-surefire-plugin 2.4.3 never **/Abstract* **/TestUtil* org.apache.felix maven-bundle-plugin 2.0.0 true ${project.groupId} ${project.url} ${project.groupId}.container.osgi.NettyBundleActivator !${project.groupId}.example.*, !${project.groupId}.logging.*, !${project.groupId}.util.internal.*, ${project.groupId}.*;version=${project.version} ${project.groupId}.example.*, ${project.groupId}.logging.*, ${project.groupId}.util.internal.*, *;resolution:=optional maven-source-plugin 2.1 attach-source package jar true maven-antrun-plugin 1.3 write-version compile run add-license package run org.apache.ant ant 1.7.1 org.apache.ant ant-launcher 1.7.1 ant-contrib ant-contrib 1.0b2 ant ant maven-javadoc-plugin 2.5 generate-javadoc package javadoc org.jboss.apiviz.APIviz org.jboss.apiviz apiviz 1.3.0.GA false ${basedir}/src/javadoc/stylesheet.css true ${project.build.directory}/api ${project.build.directory}/api api UTF-8 UTF-8 true true true true ${basedir}/src/javadoc/overview.html ${project.name} ${project.version} API Reference ${project.name} ${project.version} API Reference -link http://java.sun.com/javase/6/docs/api/ -link http://docs.jboss.org/xnio/latest/api/ -link http://code.google.com/apis/protocolbuffers/docs/reference/java/ -link http://java.sun.com/products/servlet/2.5/docs/servlet-2_5-mr2/ -link http://www.osgi.org/javadoc/r4v41/ -link http://google-guice.googlecode.com/svn/trunk/javadoc/ -link http://static.springframework.org/spring/docs/2.5.x/api/ -link http://www.slf4j.org/apidocs/ -link http://commons.apache.org/logging/commons-logging-1.1.1/apidocs/ -link http://logging.apache.org/log4j/1.2/apidocs/ -group "Low-level data representation" ${project.groupId}.buffer* -group "Central interface for all I/O operations" ${project.groupId}.channel* -group "Client & Server bootstrapping utilities" ${project.groupId}.bootstrap* -group "Reusable I/O event interceptors" ${project.groupId}.handler* -group "IoC (Dependency Injection) container integration" ${project.groupId}.container* -group "Miscellaneous" ${project.groupId}.logging*:${project.groupId}.util* -sourceclasspath ${project.build.outputDirectory} -nopackagediagram UTF-8 en_US ${project.groupId}.example*:${project.groupId}.util.internal* maven-jxr-plugin 2.1 generate-xref package jxr UTF-8 UTF-8 true ${project.build.directory}/xref ${project.build.directory}/api ${basedir}/src/xref/stylesheet.css org.jboss.maven.plugins maven-jdocbook-plugin 2.1.2 generate-docbook package resources generate org.jboss jbossorg-docbook-xslt 1.1.0 org.jboss jbossorg-jdocbook-style 1.1.0 jdocbook-style master.xml ${basedir}/src/docbook ${basedir}/src/docbook css/**/* ${basedir}/src/docbook images/**/* html file:///${basedir}/src/docbook/xslt/xhtml.xsl index.html html_single file:///${basedir}/src/docbook/xslt/xhtml-single.xsl index.html eclipse file:///${basedir}/src/docbook/xslt/eclipse.xsl index.html pdf file:///${basedir}/src/docbook/xslt/pdf.xsl netty.pdf true saxon 1.72.0 maven-assembly-plugin 2.2-beta-3 generate-distribution package single ${basedir}/src/assembly/default.xml ${attach-distribution} true gnu maven-release-plugin 2.0-beta-9 https://svn.jboss.org/repos/netty/tags false -Prelease org.apache.maven.plugins maven-eclipse-plugin 2.6 true true false never true interval:10080 jboss.release JBoss releases http://repository.jboss.org/maven2 false never true interval:10080 jboss.release JBoss releases http://repository.jboss.org/maven2 repository.jboss.org JBoss.org Release Distribution Repository dav:https://svn.jboss.org/repos/repository.jboss.org/maven2 snapshots.jboss.org JBoss.org Development Snapshot Repository dav:https://snapshots.jboss.org/maven2 release true org.apache.maven.plugins maven-deploy-plugin 2.4 true libnetty-java-3.1.0.CR1.orig/.fbprefs0000644000175000017500000002077211153454345016530 0ustar deckerdecker#FindBugs User Preferences #Wed Mar 04 19:28:55 KST 2009 detectorAppendingToAnObjectOutputStream=AppendingToAnObjectOutputStream|true detectorBCPMethodReturnCheck=BCPMethodReturnCheck|true detectorBadAppletConstructor=BadAppletConstructor|true detectorBadResultSetAccess=BadResultSetAccess|true detectorBadSyntaxForRegularExpression=BadSyntaxForRegularExpression|true detectorBadUseOfReturnValue=BadUseOfReturnValue|true detectorBadlyOverriddenAdapter=BadlyOverriddenAdapter|true detectorBooleanReturnNull=BooleanReturnNull|true detectorBuildInterproceduralCallGraph=BuildInterproceduralCallGraph|true detectorBuildObligationPolicyDatabase=BuildObligationPolicyDatabase|true detectorCallToUnsupportedMethod=CallToUnsupportedMethod|true detectorCalledMethods=CalledMethods|true detectorCheckCalls=CheckCalls|false detectorCheckExpectedWarnings=CheckExpectedWarnings|false detectorCheckImmutableAnnotation=CheckImmutableAnnotation|true detectorCheckTypeQualifiers=CheckTypeQualifiers|true detectorCloneIdiom=CloneIdiom|true detectorComparatorIdiom=ComparatorIdiom|true detectorConfusedInheritance=ConfusedInheritance|true detectorConfusionBetweenInheritedAndOuterMethod=ConfusionBetweenInheritedAndOuterMethod|true detectorCrossSiteScripting=CrossSiteScripting|true detectorDoInsideDoPrivileged=DoInsideDoPrivileged|true detectorDontCatchIllegalMonitorStateException=DontCatchIllegalMonitorStateException|true detectorDontUseEnum=DontUseEnum|true detectorDroppedException=DroppedException|true detectorDumbMethodInvocations=DumbMethodInvocations|true detectorDumbMethods=DumbMethods|true detectorDuplicateBranches=DuplicateBranches|true detectorEmptyZipFileEntry=EmptyZipFileEntry|true detectorEqStringTest=EqStringTest|true detectorEqualsOperandShouldHaveClassCompatibleWithThis=EqualsOperandShouldHaveClassCompatibleWithThis|true detectorFieldItemSummary=FieldItemSummary|true detectorFinalizerNullsFields=FinalizerNullsFields|true detectorFindBadCast=FindBadCast|true detectorFindBadCast2=FindBadCast2|true detectorFindBadEqualsImplementation=FindBadEqualsImplementation|true detectorFindBadForLoop=FindBadForLoop|true detectorFindBugsSummaryStats=FindBugsSummaryStats|true detectorFindCircularDependencies=FindCircularDependencies|false detectorFindDeadLocalStores=FindDeadLocalStores|true detectorFindDoubleCheck=FindDoubleCheck|true detectorFindEmptySynchronizedBlock=FindEmptySynchronizedBlock|true detectorFindFieldSelfAssignment=FindFieldSelfAssignment|true detectorFindFinalizeInvocations=FindFinalizeInvocations|true detectorFindFloatEquality=FindFloatEquality|true detectorFindFloatMath=FindFloatMath|false detectorFindHEmismatch=FindHEmismatch|true detectorFindInconsistentSync2=FindInconsistentSync2|true detectorFindJSR166LockMonitorenter=FindJSR166LockMonitorenter|true detectorFindLocalSelfAssignment2=FindLocalSelfAssignment2|true detectorFindMaskedFields=FindMaskedFields|true detectorFindMismatchedWaitOrNotify=FindMismatchedWaitOrNotify|true detectorFindNakedNotify=FindNakedNotify|true detectorFindNonSerializableStoreIntoSession=FindNonSerializableStoreIntoSession|true detectorFindNonSerializableValuePassedToWriteObject=FindNonSerializableValuePassedToWriteObject|true detectorFindNonShortCircuit=FindNonShortCircuit|true detectorFindNullDeref=FindNullDeref|true detectorFindNullDerefsInvolvingNonShortCircuitEvaluation=FindNullDerefsInvolvingNonShortCircuitEvaluation|true detectorFindOpenStream=FindOpenStream|true detectorFindPuzzlers=FindPuzzlers|true detectorFindRefComparison=FindRefComparison|true detectorFindReturnRef=FindReturnRef|true detectorFindRunInvocations=FindRunInvocations|true detectorFindSelfComparison=FindSelfComparison|true detectorFindSelfComparison2=FindSelfComparison2|true detectorFindSleepWithLockHeld=FindSleepWithLockHeld|true detectorFindSpinLoop=FindSpinLoop|true detectorFindSqlInjection=FindSqlInjection|true detectorFindTwoLockWait=FindTwoLockWait|true detectorFindUncalledPrivateMethods=FindUncalledPrivateMethods|true detectorFindUnconditionalWait=FindUnconditionalWait|true detectorFindUninitializedGet=FindUninitializedGet|true detectorFindUnrelatedTypesInGenericContainer=FindUnrelatedTypesInGenericContainer|true detectorFindUnreleasedLock=FindUnreleasedLock|true detectorFindUnsatisfiedObligation=FindUnsatisfiedObligation|true detectorFindUnsyncGet=FindUnsyncGet|true detectorFindUselessControlFlow=FindUselessControlFlow|true detectorFormatStringChecker=FormatStringChecker|true detectorHugeSharedStringConstants=HugeSharedStringConstants|true detectorIDivResultCastToDouble=IDivResultCastToDouble|true detectorIncompatMask=IncompatMask|true detectorInconsistentAnnotations=InconsistentAnnotations|true detectorInefficientMemberAccess=InefficientMemberAccess|true detectorInefficientToArray=InefficientToArray|true detectorInfiniteLoop=InfiniteLoop|true detectorInfiniteRecursiveLoop=InfiniteRecursiveLoop|true detectorInfiniteRecursiveLoop2=InfiniteRecursiveLoop2|true detectorInheritanceUnsafeGetResource=InheritanceUnsafeGetResource|true detectorInitializationChain=InitializationChain|true detectorInstantiateStaticClass=InstantiateStaticClass|true detectorInvalidJUnitTest=InvalidJUnitTest|true detectorIteratorIdioms=IteratorIdioms|true detectorLazyInit=LazyInit|true detectorLoadOfKnownNullValue=LoadOfKnownNullValue|true detectorLockedFields=LockedFields|true detectorMethodReturnCheck=MethodReturnCheck|true detectorMethods=Methods|true detectorMultithreadedInstanceAccess=MultithreadedInstanceAccess|true detectorMutableLock=MutableLock|true detectorMutableStaticFields=MutableStaticFields|true detectorNaming=Naming|true detectorNoise=Noise|false detectorNoiseNullDeref=NoiseNullDeref|false detectorNoteAnnotationRetention=NoteAnnotationRetention|true detectorNoteCheckReturnValue=NoteCheckReturnValue|true detectorNoteCheckReturnValueAnnotations=NoteCheckReturnValueAnnotations|true detectorNoteDirectlyRelevantTypeQualifiers=NoteDirectlyRelevantTypeQualifiers|true detectorNoteJCIPAnnotation=NoteJCIPAnnotation|true detectorNoteNonNullAnnotations=NoteNonNullAnnotations|true detectorNoteNonnullReturnValues=NoteNonnullReturnValues|true detectorNoteSuppressedWarnings=NoteSuppressedWarnings|true detectorNoteUnconditionalParamDerefs=NoteUnconditionalParamDerefs|true detectorNumberConstructor=NumberConstructor|true detectorOverridingEqualsNotSymmetrical=OverridingEqualsNotSymmetrical|true detectorPreferZeroLengthArrays=PreferZeroLengthArrays|true detectorPublicSemaphores=PublicSemaphores|true detectorQuestionableBooleanAssignment=QuestionableBooleanAssignment|true detectorReadReturnShouldBeChecked=ReadReturnShouldBeChecked|true detectorRedundantInterfaces=RedundantInterfaces|true detectorReflectiveClasses=ReflectiveClasses|true detectorRepeatedConditionals=RepeatedConditionals|true detectorResolveAllReferences=ResolveAllReferences|true detectorRuntimeExceptionCapture=RuntimeExceptionCapture|true detectorSerializableIdiom=SerializableIdiom|true detectorStartInConstructor=StartInConstructor|true detectorStaticCalendarDetector=StaticCalendarDetector|true detectorStringConcatenation=StringConcatenation|true detectorSuperfluousInstanceOf=SuperfluousInstanceOf|true detectorSuspiciousThreadInterrupted=SuspiciousThreadInterrupted|true detectorSwitchFallthrough=SwitchFallthrough|true detectorSynchronizationOnSharedBuiltinConstant=SynchronizationOnSharedBuiltinConstant|true detectorSynchronizeAndNullCheckField=SynchronizeAndNullCheckField|true detectorSynchronizeOnClassLiteralNotGetClass=SynchronizeOnClassLiteralNotGetClass|true detectorSynchronizingOnContentsOfFieldToProtectField=SynchronizingOnContentsOfFieldToProtectField|true detectorTestASM=TestASM|false detectorTestDataflowAnalysis=TestDataflowAnalysis|false detectorTestingGround=TestingGround|false detectorTrainFieldStoreTypes=TrainFieldStoreTypes|true detectorTrainNonNullAnnotations=TrainNonNullAnnotations|true detectorTrainUnconditionalDerefParams=TrainUnconditionalDerefParams|true detectorURLProblems=URLProblems|true detectorUncallableMethodOfAnonymousClass=UncallableMethodOfAnonymousClass|true detectorUnnecessaryMath=UnnecessaryMath|true detectorUnreadFields=UnreadFields|true detectorUseObjectEquals=UseObjectEquals|true detectorUselessSubclassMethod=UselessSubclassMethod|true detectorVarArgsProblems=VarArgsProblems|true detectorVolatileUsage=VolatileUsage|true detectorWaitInLoop=WaitInLoop|true detectorWrongMapIterator=WrongMapIterator|true detectorXMLFactoryBypass=XMLFactoryBypass|true detector_threshold=3 effort=max excludefilter0=.fbfilter.xml filter_settings=Low|BAD_PRACTICE,CORRECTNESS,EXPERIMENTAL,I18N,MALICIOUS_CODE,MT_CORRECTNESS,PERFORMANCE,SECURITY,STYLE|false filter_settings_neg=NOISE| run_at_full_build=true libnetty-java-3.1.0.CR1.orig/license/0000755000175000017500000000000011316313120016474 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/license/LICENSE.log4j.txt0000644000175000017500000002367611126305105021356 0ustar deckerdecker Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS libnetty-java-3.1.0.CR1.orig/license/LICENSE.protobuf.txt0000644000175000017500000000330411126305105022161 0ustar deckerdeckerCopyright 2008, Google Inc. All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Google Inc. nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. Code generated by the Protocol Buffer compiler is owned by the owner of the input file used when generating it. This code is not standalone and requires a support library to be linked with it. This support library is itself covered by the above license. libnetty-java-3.1.0.CR1.orig/license/LICENSE.spring.txt0000644000175000017500000002367611145276215021653 0ustar deckerdecker Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS libnetty-java-3.1.0.CR1.orig/license/LICENSE.jsr166y.txt0000644000175000017500000000307011126305105021545 0ustar deckerdeckerThe person or persons who have associated work with this document (the "Dedicator" or "Certifier") hereby either (a) certifies that, to the best of his knowledge, the work of authorship identified is in the public domain of the country from which the work is published, or (b) hereby dedicates whatever copyright the dedicators holds in the work of authorship identified below (the "Work") to the public domain. A certifier, moreover, dedicates any copyright interest he may have in the associated work, and for these purposes, is described as a "dedicator" below. A certifier has taken reasonable steps to verify the copyright status of this work. Certifier recognizes that his good faith efforts may not shield him from liability if in fact the work certified is not in the public domain. Dedicator makes this dedication for the benefit of the public at large and to the detriment of the Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuity of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work. Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived. libnetty-java-3.1.0.CR1.orig/license/LICENSE.jboss-logging.txt0000644000175000017500000006351111126305105023073 0ustar deckerdecker GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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. Copyright (C) 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., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 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. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libnetty-java-3.1.0.CR1.orig/license/LICENSE.xnio.txt0000644000175000017500000006351111146507775021327 0ustar deckerdecker GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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. Copyright (C) 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., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 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. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libnetty-java-3.1.0.CR1.orig/license/LICENSE.jboss-microcontainer.txt0000644000175000017500000006351111145276215024473 0ustar deckerdecker GNU LESSER GENERAL PUBLIC LICENSE Version 2.1, February 1999 Copyright (C) 1991, 1999 Free Software Foundation, Inc. 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 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. Copyright (C) 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., 51 Franklin Street, 5th Floor, Boston, MA 02110-1301 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. , 1 April 1990 Ty Coon, President of Vice That's all there is to it! libnetty-java-3.1.0.CR1.orig/license/LICENSE.slf4j.txt0000644000175000017500000000226311126305105021346 0ustar deckerdecker/* * Copyright (c) 2004-2007 QOS.ch * All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ libnetty-java-3.1.0.CR1.orig/license/LICENSE.felix.txt0000644000175000017500000002367611145276215021460 0ustar deckerdecker Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS libnetty-java-3.1.0.CR1.orig/license/LICENSE.guice.txt0000644000175000017500000002367611145276215021445 0ustar deckerdecker Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS libnetty-java-3.1.0.CR1.orig/license/LICENSE.base64.txt0000644000175000017500000000307011126305105021405 0ustar deckerdeckerThe person or persons who have associated work with this document (the "Dedicator" or "Certifier") hereby either (a) certifies that, to the best of his knowledge, the work of authorship identified is in the public domain of the country from which the work is published, or (b) hereby dedicates whatever copyright the dedicators holds in the work of authorship identified below (the "Work") to the public domain. A certifier, moreover, dedicates any copyright interest he may have in the associated work, and for these purposes, is described as a "dedicator" below. A certifier has taken reasonable steps to verify the copyright status of this work. Certifier recognizes that his good faith efforts may not shield him from liability if in fact the work certified is not in the public domain. Dedicator makes this dedication for the benefit of the public at large and to the detriment of the Dedicator's heirs and successors. Dedicator intends this dedication to be an overt act of relinquishment in perpetuate of all present and future rights under copyright law, whether vested or contingent, in the Work. Dedicator understands that such relinquishment of all rights includes the relinquishment of all rights to enforce (by lawsuit or otherwise) those copyrights in the Work. Dedicator recognizes that, once placed in the public domain, the Work may be freely reproduced, distributed, transmitted, used, modified, built upon, or otherwise exploited by anyone for any purpose, commercial or non-commercial, and in any way, including by methods that have not yet been invented or conceived. libnetty-java-3.1.0.CR1.orig/license/LICENSE.commons-logging.txt0000644000175000017500000002367611126305105023436 0ustar deckerdecker Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS libnetty-java-3.1.0.CR1.orig/COPYRIGHT.txt0000644000175000017500000000140611215661302017172 0ustar deckerdeckerThe Netty Project - Copyright (C) 2008, Red Hat Middleware LLC, and individual contributors, and is licensed under the GNU LGPL (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. A summary of the individual contributors is given below. Any omission should be sent to Trustin Lee . SVN Login(s) Name ------------------------------------------------------------------------------- ataylor Andy Taylor beve Daniel Bevenius trustin Trustin Heuiseung Lee ------------------------------------------------------------------------------- * JBoss is a registered trademark of Red Hat Middleware LLC. libnetty-java-3.1.0.CR1.orig/src/0000755000175000017500000000000011316313154015650 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/site/0000755000175000017500000000000011316313154016614 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/site/template.vm0000644000175000017500000000272011046720374021002 0ustar deckerdecker#* JBoss, Home of Professional Open Source Copyright 2008, Red Hat Middleware LLC, and individual contributors by the @author tags. See the COPYRIGHT.txt in the distribution for a full listing of individual contributors. This 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 software 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 software; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA, or see the FSF site: http://www.fsf.org. *# $project.name - Redirecting... Please click here if not redirected automatically. libnetty-java-3.1.0.CR1.orig/src/javadoc/0000755000175000017500000000000011316313154017257 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/javadoc/overview.html0000644000175000017500000000147211167642412022025 0ustar deckerdecker The Netty Project API Reference

The Netty project is an effort to provide an asynchronous event-driven network application framework and tools for rapid development of maintainable high performance and high scalability protocol servers and clients. In other words, Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP/IP socket server.

libnetty-java-3.1.0.CR1.orig/src/javadoc/stylesheet.css0000644000175000017500000000431311216740252022165 0ustar deckerdecker* { font-family: "Lucida Grande", Geneva, Verdana, "Liberation Sans", Helvetica, Arial, sans-serif; } body { background-color: #FFFFFF; color:#000000; font-size: 10pt; } a:link {color:#0033cc;} a:visited {color:#0044cc;} tt, tt *, pre, pre *, code, code * { font-family: "Liberation Mono", "DejaVu Sans Mono", Consolas, Monaco, "Lucida Console", "Courier New", monospace; } /* Headings */ h1, h2, h3, h4, h5, h6 { color:#4a5d75; line-height:130%; margin-top:0em; font-family:'Lucida Grande', Geneva, Verdana, Arial, sans-serif; background-color:transparent; } h1 { font-size:2em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h2 { font-size:1.6em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h3 { font-size:1.3em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h4 { font-size:1.1em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h5 { font-size:1em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } /* Tables */ table { border-collapse: collapse; border-color: black; } th { text-align: left; background: #CCCCFF; color:#000000; padding: 3px 6px; border-color: black; } td { vertical-align: top; padding: 3px 6px; border-color: black; } /* Table colors */ .TableHeadingColor { background: #CCCCFF; /* Dark mauve */ color:#000000; } .TableHeadingColor TH * { font-size: 1.2em !important; } .TableSubHeadingColor { background: #EEEEFF; /* Light mauve */ color:#000000 } .TableRowColor { background: #FFFFFF; /* White */ color:#000000 } /* Font used in left-hand frame lists */ .FrameTitleFont { font-size: 100%; color:#000000 } .FrameHeadingFont { font-size: 90%; color:#000000 } .FrameItemFont { font-size: 90%; color:#000000 } /* Navigation bar fonts and colors */ .NavBarCell1 { background-color:#EEEEFF; color:#000000} /* Light mauve */ .NavBarCell1Rev { background-color:#00008B; color:#FFFFFF} /* Dark Blue */ .NavBarFont1 { color:#000000;color:#000000;} .NavBarFont1Rev { color:#FFFFFF;color:#FFFFFF;} .NavBarCell2 { background-color:#FFFFFF; color:#000000} .NavBarCell3 { background-color:#FFFFFF; color:#000000} libnetty-java-3.1.0.CR1.orig/src/docbook/0000755000175000017500000000000011316313126017267 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/docbook/module/0000755000175000017500000000000011316313126020554 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/docbook/module/transport.xml0000644000175000017500000000046211064705014023335 0ustar deckerdecker %CustomDTD; ]> Transports To be written... libnetty-java-3.1.0.CR1.orig/src/docbook/module/codec.xml0000644000175000017500000000047111064705014022356 0ustar deckerdecker %CustomDTD; ]> Encoders and Decoders To be written... libnetty-java-3.1.0.CR1.orig/src/docbook/module/appendix.xml0000644000175000017500000000047611064705014023116 0ustar deckerdecker %CustomDTD; ]> Additional Resources To be written... libnetty-java-3.1.0.CR1.orig/src/docbook/module/preface.xml0000644000175000017500000000700111157663600022711 0ustar deckerdecker %CustomDTD; ]> Preface This guide provides an introduction to Netty and what it is about.
The Problem Nowadays we use general purpose applications or libraries to communicate with each other. For example, we often use an HTTP client library to retrieve information from a web server and to invoke a remote procedure call via web services. However, a general purpose protocol or its implementation sometimes does not scale very well. It is like we don't use a general purpose HTTP server to exchange huge files, e-mail messages, and near-realtime messages such as financial information and multiplayer game data. What's required is a highly optimized protocol implementation which is dedicated to a special purpose. For example, you might want to implement an HTTP server which is optimized for AJAX-based chat application, media streaming, or large file transfer. You could even want to design and implement a whole new protocol which is precisely tailored to your need. Another inevitable case is when you have to deal with a legacy proprietary protocol to ensure the interoperability with an old system. What matters in this case is how quickly we can implement that protocol while not sacrificing the stability and performance of the resulting application.
The Solution The Netty project is an effort to provide an asynchronous event-driven network application framework and tooling for the rapid development of maintainable high-performance · high-scalability protocol servers and clients. In other words, Netty is a NIO client server framework which enables quick and easy development of network applications such as protocol servers and clients. It greatly simplifies and streamlines network programming such as TCP and UDP socket server development. 'Quick and easy' does not mean that a resulting application will suffer from a maintainability or a performance issue. Netty has been designed carefully with the experiences earned from the implementation of a lot of protocols such as FTP, SMTP, HTTP, and various binary and text-based legacy protocols. As a result, Netty has succeeded to find a way to achieve ease of development, performance, stability, and flexibility without a compromise. Some users might already have found other network application framework that claims to have the same advantage, and you might want to ask what makes Netty so different from them. The answer is the philosophy where it is built on. Netty is designed to give you the most comfortable experience both in terms of the API and the implementation from the day one. It is not something tangible but you will realize that this philosophy will make your life much easier as you read this guide and play with Netty.
libnetty-java-3.1.0.CR1.orig/src/docbook/module/threading.xml0000644000175000017500000000047111064705014023246 0ustar deckerdecker %CustomDTD; ]> Thread Management To be written... libnetty-java-3.1.0.CR1.orig/src/docbook/module/security.xml0000644000175000017500000000047011064705014023147 0ustar deckerdecker %CustomDTD; ]> Securing the Wire To be written... libnetty-java-3.1.0.CR1.orig/src/docbook/module/architecture.xml0000644000175000017500000003430211175564104023771 0ustar deckerdecker %CustomDTD; ]> Architectural Overview The Architecture Diagram of Netty In this chapter, we will examine what core functionalities are provided in Netty and how they constitute a complete network application development stack on top of the core. Please keep this diagram in mind as you read this chapter.
Rich Buffer Data Structure Netty uses its own buffer API instead of NIO ByteBuffer to represent a sequence of bytes. This approach has significant advantage over using ByteBuffer. Netty's new buffer type, &ChannelBuffer; has been designed from ground up to address the problems of ByteBuffer and to meet the daily needs of network application developers. To list a few cool features: You can define your buffer type if necessary. Transparent zero copy is achieved by built-in composite buffer type. A dynamic buffer type is provided out-of-the-box, whose capacity is expanded on demand, just like StringBuffer. There's no need to call flip() anymore. It is often faster than ByteBuffer. For more information, please refer to the org.jboss.netty.buffer package description.
Universal Asynchronous I/O API Traditional I/O APIs in Java provided different types and methods for different transport types. For example, java.net.Socket and java.net.DatagramSocket do not have any common super type and therefore they have very different ways to perform socket I/O. This mismatch makes porting a network application from one transport to the other tedious and difficult. The lack of portability between transports becomes a problem when you need to support more transports not rewriting the network layer of the application. Logically, many protocols can run on more than one transport such as TCP/IP, UDP/IP, SCTP, and serial port communication. To make the matter worse, Java New I/O (NIO) API introduced the incompatibility with the old blocking I/O (OIO) API, and so will NIO.2 (AIO). Because all these APIs are different from each other in design and performance characteristics, you are often forced to determine which API your application will depend on before you even begin the implementation phase. For instance, you might want to start with OIO because the number of clients you are going to serve will be very small and writing a socket server using OIO is much easier than using NIO. However, you are going to be in trouble when your business grows up exponentially and your server starts to serve tens of thousand clients simultaneously. You could start with NIO, but it might take much longer time to implement due to the complexity of the NIO Selector API, hindering rapid development. Netty has a universal asynchronous I/O interface called &Channel;, which abstracts away all operations required to point-to-point communication. That is, once you wrote your application on one Netty transport, your application can run on other Netty transports. Netty provides a number of essential transports via one universal API: NIO-based TCP/IP transport (See org.jboss.netty.channel.socket.nio), OIO-based TCP/IP transport (See org.jboss.netty.channel.socket.oio), OIO-based UDP/IP transport, and Local transport (See org.jboss.netty.channel.local). Switching from one transport from the other usually takes just a couple lines of changes such as choosing a different &ChannelFactory; implementation. Also, you are even able to take advantage of a new transport which is not written yet, serial port communication transport for instance, again by replacing just a couple lines of constructor calls. Moreover, you can write your own transport by extending the core API because it is highly extensible.
Event Model based on the Interceptor Chain Pattern Well-defined and extensible event model is a must for an event-driven application. Netty does have a well-defined event model focused on I/O. It also allows you to implement your own event type without breaking the existing code at all because each event type is distinguished from each other by strict type hierarchy. This is another differentiator against other frameworks. Many NIO frameworks have no or very limited notion of event model; they often break the existing code when you try to add a new custom event type, or just do not allow extension. A &ChannelEvent; is handled by a list of &ChannelHandler;s in a &ChannelPipeline;. The pipeline implements an advanced form of the Intercepting Filter pattern to give a user full control over how an event is handled and how the handlers in the pipeline interact with each other. For example, you can define what to do when a data is read from a socket: public class MyReadHandler implements &SimpleChannelHandler; { public void messageReceived(&ChannelHandlerContext; ctx, &MessageEvent; evt) { Object message = evt.getMessage(); // Do something with the received message. ... // And forward the event to the next handler. ctx.sendUpstream(evt); } } You can also define what to do when other handler requested a write operation: public class MyWriteHandler implements &SimpleChannelHandler; { public void writeRequested(&ChannelHandlerContext; ctx, &MessageEvent; evt) { Object message = evt.getMessage(); // Do something with the message to be written. ... // And forward the event to the next handler. ctx.sendDownstream(evt); } } For more information about the event model, please refer to the API documentation of &ChannelEvent; and &ChannelPipeline;.
Advanced Components for More Rapid Development On top of the core components mentioned above, that already enable the implementation of all types of network applications, Netty provides a set of advanced features to accelerate the development pace even more.
Codec framework As demonstrated in , it is always a good idea to separate a protocol codec from a business logic. However, there are some complications when implementing this idea from scratch. You have to deal with the fragmentation of messages. Some protocols are multi-layered (i.e. built on top of other lower level protocol). Some are too complicated to be implemented in a single state machine. Consequently, a good network application framework should provide an extensible, reusable, unit-testable, and multi-layered codec framework that generates maintainable user codec. Netty provides a number of basic and advanced codecs built on top of its core to address most issues you will encounter when you write a protocol codec regardless if it is simple or not, binary or text - simply whatever.
SSL / TLS Support Unlike old blocking I/O, it is a non-trivial task to support SSL in NIO. You can't simply wrap a stream to encrypt or decrypt data but you have to use javax.net.ssl.SSLEngine. SSLEngine is a state machine which is as complex as SSL is. You have to manage all possible states such as cipher suite and encryption key negotiation (or re-negotiation), certificate exchange and validation. Moreover, SSLEngine is not even completely thread-safe unlike usual expectation. In Netty, &SslHandler; takes care of all the gory details and pitfalls of SSLEngine. All you need to do is to configure and insert the &SslHandler; to your &ChannelPipeline;. It also allows you to implement advanced features like StartTLS very easily.
HTTP Implementation HTTP is definitely the most popular protocol in the Internet. There are already a number of HTTP implementations such as a Servlet container. Then why does Netty have HTTP on top of its core? Netty's HTTP support is very different from the existing HTTP libraries. It gives you complete control over how HTTP messages are exchanged in a low level. Because it is basically the combination of HTTP codec and HTTP message classes, there is no restriction such as enforced thread model. That is, you can write your own HTTP client or server that works exactly the way you want. You have full control over thread model, connection life cycle, chunked encoding, and as much as what HTTP specification allows you to do. Thanks to its highly customizable nature, you can write a very efficient HTTP server such as: Chat server that requires persistent connections and server push technology (e.g. Comet) Media streaming server that needs to keep the connection open until the whole media is streamed (e.g. 2 hours of movie) File server that allows the upload of large files without memory pressure (e.g. uploading 1GB per request) Scalable mash-up client that connects to tens of thousand 3rd party web services asynchronously
Google Protocol Buffer Integration Google Protocol Buffers are an ideal solution for the rapid implementation of a highly efficient binary protocol that evolves over time. With &ProtobufEncoder; and &ProtobufDecoder;, you can turn the message classes generated by Google Protocol Buffers Compiler (protoc) into Netty codec. Please take a look into the 'LocalTime' example that shows how easily you can create a high-performing binary protocol client and server from the sample protocol definition.
Summary In this chapter, we reviewed the overall architecture of Netty from the feature-wise standpoint. Netty has simple yet powerful architecture. It is composed of three components - buffer, channel, and event model - and all advanced features are built on top of the three core components. Once you understood how these three work together, it should not be difficult to understand more advanced features which were covered briefly in this chapter. You might still have an unanswered question about what the overall architecture looks exactly like and how each feature work together. If so, it is a good idea to talk to us to improve this guide.
libnetty-java-3.1.0.CR1.orig/src/docbook/module/start.xml0000644000175000017500000014534211167535025022454 0ustar deckerdecker %CustomDTD; ]> Getting Started This chapter tours around the core constructs of Netty with simple examples to let you get started quickly. You will be able to write a client and a server on top of Netty right away when you are at the end of this chapter. If you prefer top-down approach in learning something, you might want to start from and get back here.
Before Getting Started The minimum requirements to run the examples which are introduced in this chapter are only two; the latest version of Netty and JDK 1.5 or above. The latest version of Netty is available in the project download page. To download the right version of JDK, please refer to your preferred JDK vendor's web site. Is that all? To tell the truth, you should find these two are just enough to implement almost any type of protocols. Otherwise, please feel free to contact the Netty project community and let us know what's missing. At last but not least, please refer to the API reference whenever you want to know more about the classes introduced here. All class names in this document are linked to the online API reference for your convenience. Also, please don't hesitate to contact the Netty project community and let us know if there's any incorrect information, errors in grammar and typo, and if you have a good idea to improve the documentation.
Writing a Discard Server The most simplistic protocol in the world is not 'Hello, World!' but DISCARD. It's a protocol which discards any received data without any response. To implement the DISCARD protocol, the only thing you need to do is to ignore all received data. Let us start straight from the handler implementation, which handles I/O events generated by Netty. package org.jboss.netty.example.discard; @&ChannelPipelineCoverage;("all") public class DiscardServerHandler extends &SimpleChannelHandler; { @Override public void messageReceived(&ChannelHandlerContext; ctx, &MessageEvent; e) { } @Override public void exceptionCaught(&ChannelHandlerContext; ctx, &ExceptionEvent; e) { e.getCause().printStackTrace(); &Channel; ch = e.getChannel(); ch.close(); } } &ChannelPipelineCoverage; annotates a handler type to tell if the handler instance of the annotated type can be shared by more than one &Channel; (and its associated &ChannelPipeline;). DiscardServerHandler does not manage any stateful information, and therefore it is annotated with the value "all". DiscardServerHandler extends &SimpleChannelHandler;, which is an implementation of &ChannelHandler;. &SimpleChannelHandler; provides various event handler methods that you can override. For now, it is just enough to extend &SimpleChannelHandler; rather than to implement the handler interfaces by yourself. We override the messageReceived event handler method here. This method is called with a &MessageEvent;, which contains the received data, whenever new data is received from a client. In this example, we ignore the received data by doing nothing to implement the DISCARD protocol. exceptionCaught event handler method is called with an &ExceptionEvent; when an exception was raised by Netty due to I/O error or by a handler implementation due to the exception thrown while processing events. In most cases, the caught exception should be logged and its associated channel should be closed here, although the implementation of this method can be different depending on what you want to do to deal with an exceptional situation. For example, you might want to send a response message with an error code before closing the connection. So far so good. We have implemented the first half of the DISCARD server. What's left now is to write the main method which starts the server with the DiscardServerHandler. package org.jboss.netty.example.discard; import java.net.InetSocketAddress; import java.util.concurrent.Executors; public class DiscardServer { public static void main(String[] args) throws Exception { &ChannelFactory; factory = new &NioServerSocketChannelFactory;( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); &ServerBootstrap; bootstrap = new &ServerBootstrap;(factory); DiscardServerHandler handler = new DiscardServerHandler(); &ChannelPipeline; pipeline = bootstrap.getPipeline(); pipeline.addLast("handler", handler); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); bootstrap.bind(new InetSocketAddress(8080)); } } &ChannelFactory; is a factory which creates and manages &Channel;s and its related resources. It processes all I/O requests and performs I/O to generate &ChannelEvent;s. Netty provides various &ChannelFactory; implementations. We are implementing a server-side application in this example, and therefore &NioServerSocketChannelFactory; was used. Another thing to note is that it does not create I/O threads by itself. It is supposed to acquire threads from the thread pool you specified in the constructor, and it gives you more control over how threads should be managed in the environment where your application runs, such as an application server with a security manager. &ServerBootstrap; is a helper class that sets up a server. You can set up the server using a &Channel; directly. However, please note that this is a tedious process and you do not need to do that in most cases. Here, we add the DiscardServerHandler to the default &ChannelPipeline;. Whenever a new connection is accepted by the server, a new &ChannelPipeline; will be created for a newly accepted &Channel; and all the &ChannelHandler;s added here will be added to the new &ChannelPipeline;. It's just like a shallow-copy operation; all &Channel; and their &ChannelPipeline;s will share the same DiscardServerHandler instance. You can also set the parameters which are specific to the &Channel; implementation. We are writing a TCP/IP server, so we are allowed to set the socket options such as tcpNoDelay and keepAlive. Please note that the "child." prefix was added to all options. It means the options will be applied to the accepted &Channel;s instead of the options of the &ServerSocketChannel;. You could do the following to set the options of the &ServerSocketChannel;: bootstrap.setOption("reuseAddress", true); We are ready to go now. What's left is to bind to the port and to start the server. Here, we bind to the port 8080 of all NICs (network interface cards) in the machine. You can now call the bind method as many times as you want (with different bind addresses.) Congratulations! You've just finished your first server on top of Netty.
Looking into the Received Data Now that we have written our first server, we need to test if it really works. The easiest way to test it is to use the telnet command. For example, you could enter "telnet localhost 8080" in the command line and type something. However, can we say that the server is working fine? We cannot really know that because it is a discard server. You will not get any response at all. To prove it is really working, let us modify the server to print what it has received. We already know that &MessageEvent; is generated whenever data is received and the messageReceived handler method will be invoked. Let us put some code into the messageReceived method of the DiscardServerHandler: @Override public void messageReceived(&ChannelHandlerContext; ctx, &MessageEvent; e) { &ChannelBuffer; buf = (ChannelBuffer) e.getMessage(); while(buf.readable()) { System.out.println((char) buf.readByte()); } } It is safe to assume the message type in socket transports is always &ChannelBuffer;. &ChannelBuffer; is a fundamental data structure which stores a sequence of bytes in Netty. It's similar to NIO ByteBuffer, but it is easier to use and more flexible. For example, Netty allows you to create a composite &ChannelBuffer; which combines multiple &ChannelBuffer;s reducing the number of unnecessary memory copy. Although it resembles to NIO ByteBuffer a lot, it is highly recommended to refer to the API reference. Learning how to use &ChannelBuffer; correctly is a critical step in using Netty without difficulty. If you run the telnet command again, you will see the server prints what has received. The full source code of the discard server is located in the org.jboss.netty.example.discard package of the distribution.
Writing an Echo Server So far, we have been consuming data without responding at all. A server, however, is usually supposed to respond to a request. Let us learn how to write a response message to a client by implementing the ECHO protocol, where any received data is sent back. The only difference from the discard server we have implemented in the previous sections is that it sends the received data back instead of printing the received data out to the console. Therefore, it is enough again to modify the messageReceived method: @Override public void messageReceived(&ChannelHandlerContext; ctx, &MessageEvent; e) { &Channel; ch = e.getChannel(); ch.write(e.getMessage()); } A &ChannelEvent; object has a reference to its associated &Channel;. Here, the returned &Channel; represents the connection which received the &MessageEvent;. We can get the &Channel; and call the write method to write something back to the remote peer. If you run the telnet command again, you will see the server sends back whatever you have sent to it. The full source code of the echo server is located in the org.jboss.netty.example.echo package of the distribution.
Writing a Time Server The protocol to implement in this section is the TIME protocol. It is different from the previous examples in that it sends a message, which contains a 32-bit integer, without receiving any requests and closes the connection once the message is sent. In this example, you will learn how to construct and send a message, and to close the connection on completion. Because we are going to ignore any received data but to send a message as soon as a connection is established, we cannot use the messageReceived method this time. Instead, we should override the channelConnected method. The following is the implementation: package org.jboss.netty.example.time; @&ChannelPipelineCoverage;("all") public class TimeServerHandler extends &SimpleChannelHandler; { @Override public void channelConnected(&ChannelHandlerContext; ctx, &ChannelStateEvent; e) { &Channel; ch = e.getChannel(); &ChannelBuffer; time = &ChannelBuffers;.buffer(4); time.writeInt(System.currentTimeMillis() / 1000); &ChannelFuture; f = ch.write(time); f.addListener(new &ChannelFutureListener;() { public void operationComplete(&ChannelFuture; future) { &Channel; ch = future.getChannel(); ch.close(); } }); } @Override public void exceptionCaught(&ChannelHandlerContext; ctx, &ExceptionEvent; e) { e.getCause().printStackTrace(); e.getChannel().close(); } } As explained, channelConnected method will be invoked when a connection is established. Let us write the 32-bit integer that represents the current time in seconds here. To send a new message, we need to allocate a new buffer which will contain the message. We are going to write a 32-bit integer, and therefore we need a &ChannelBuffer; whose capacity is 4 bytes. The &ChannelBuffers; helper class is used to allocate a new buffer. Besides the buffer method, &ChannelBuffers; provides a lot of useful methods related to the &ChannelBuffer;. For more information, please refer to the API reference. On the other hand, it is a good idea to use static imports for &ChannelBuffers;: import static org.jboss.netty.buffer.&ChannelBuffers;.*; ... &ChannelBuffer; dynamicBuf = dynamicBuffer(256); &ChannelBuffer; ordinaryBuf = buffer(1024); As usual, we write the constructed message. But wait, where's the flip? Didn't we used to call ByteBuffer.flip() before sending a message in NIO? &ChannelBuffer; does not have such a method because it has two pointers; one for read operations and the other for write operations. The writer index increases when you write something to a &ChannelBuffer; while the reader index does not change. The reader index and the writer index represents where the message starts and ends respectively. In contrast, NIO buffer does not provide a clean way to figure out where the message content starts and ends without calling the flip method. You will be in trouble when you forget to flip the buffer because nothing or incorrect data will be sent. Such an error does not happen in Netty because we have different pointer for different operation types. You will find it makes your life much easier as you get used to it -- a life without flipping out! Another point to note is that the write method returns a &ChannelFuture;. A &ChannelFuture; represents an I/O operation which has not yet occurred. It means, any requested operation might not have been performed yet because all operations are asynchronous in Netty. For example, the following code might close the connection even before a message is sent: &Channel; ch = ...; ch.write(message); ch.close(); Therefore, you need to call the close method after the &ChannelFuture;, which was returned by the write method, notifies you when the write operation has been done. Please note that, close might not close the connection immediately, and it returns a &ChannelFuture;. How do we get notified when the write request is finished then? This is as simple as adding a &ChannelFutureListener; to the returned &ChannelFuture;. Here, we created a new anonymous &ChannelFutureListener; which closes the &Channel; when the operation is done. Alternatively, you could simplify the code using a pre-defined listener: f.addListener(&ChannelFutureListener;.CLOSE);
Writing a Time Client Unlike DISCARD and ECHO servers, we need a client for the TIME protocol because a human cannot translate a 32-bit binary data into a date on a calendar. In this section, we discuss how to make sure the server works correctly and learn how to write a client with Netty. The biggest and only difference between a server and a client in Netty is that different &Bootstrap; and &ChannelFactory; are required. Please take a look at the following code: package org.jboss.netty.example.time; import java.net.InetSocketAddress; import java.util.concurrent.Executors; public class TimeClient { public static void main(String[] args) throws Exception { String host = args[0]; int port = Integer.parseInt(args[1]); &ChannelFactory; factory = new &NioClientSocketChannelFactory;( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); &ClientBootstrap; bootstrap = new &ClientBootstrap;(factory); TimeClientHandler handler = new TimeClientHandler(); bootstrap.getPipeline().addLast("handler", handler); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); bootstrap.connect(new InetSocketAddress(host, port)); } } &NioClientSocketChannelFactory;, instead of &NioServerSocketChannelFactory; was used to create a client-side &Channel;. &ClientBootstrap; is a client-side counterpart of &ServerBootstrap;. Please note that there's no "child." prefix. A client-side &SocketChannel; does not have a parent. We should call the connect method instead of the bind method. As you can see, it is not really different from the server side startup. What about the &ChannelHandler; implementation? It should receive a 32-bit integer from the server, translate it into a human readable format, print the translated time, and close the connection: package org.jboss.netty.example.time; import java.util.Date; @&ChannelPipelineCoverage;("all") public class TimeClientHandler extends &SimpleChannelHandler; { @Override public void messageReceived(&ChannelHandlerContext; ctx, &MessageEvent; e) { &ChannelBuffer; buf = (&ChannelBuffer;) e.getMessage(); long currentTimeMillis = buf.readInt() * 1000L; System.out.println(new Date(currentTimeMillis)); e.getChannel().close(); } @Override public void exceptionCaught(&ChannelHandlerContext; ctx, &ExceptionEvent; e) { e.getCause().printStackTrace(); e.getChannel().close(); } } It looks very simple and does not look any different from the server side example. However, this handler sometimes will refuse to work raising an IndexOutOfBoundsException. We discuss why this happens in the next section.
Dealing with a Stream-based Transport
One Small Caveat of Socket Buffer In a stream-based transport such as TCP/IP, received data is stored into a socket receive buffer. Unfortunately, the buffer of a stream-based transport is not a queue of packets but a queue of bytes. It means, even if you sent two messages as two independent packets, an operating system will not treat them as two messages but as just a bunch of bytes. Therefore, there is no guarantee that what you read is exactly what your remote peer wrote. For example, let us assume that the TCP/IP stack of an operating system has received three packets: +-----+-----+-----+ | ABC | DEF | GHI | +-----+-----+-----+ Because of this general property of a stream-based protocol, there's high chance of reading them in the following fragmented form in your application: +----+-------+---+---+ | AB | CDEFG | H | I | +----+-------+---+---+ Therefore, a receiving part, regardless it is server-side or client-side, should defrag the received data into one or more meaningful frames that could be easily understood by the application logic. In case of the example above, the received data should be framed like the following: +-----+-----+-----+ | ABC | DEF | GHI | +-----+-----+-----+
The First Solution Now let us get back to the TIME client example. We have the same problem here. A 32-bit integer is a very small amount of data, and it is not likely to be fragmented often. However, the problem is that it can be fragmented, and the possibility of fragmentation will increase as the traffic increases. The simplistic solution is to create an internal cumulative buffer and wait until all 4 bytes are received into the internal buffer. The following is the modified TimeClientHandler implementation that fixes the problem: package org.jboss.netty.example.time; import static org.jboss.netty.buffer.&ChannelBuffers;.*; import java.util.Date; @&ChannelPipelineCoverage;("one") public class TimeClientHandler extends &SimpleChannelHandler; { private final &ChannelBuffer; buf = dynamicBuffer(); @Override public void messageReceived(&ChannelHandlerContext; ctx, &MessageEvent; e) { &ChannelBuffer; m = (&ChannelBuffer;) e.getMessage(); buf.writeBytes(m); if (buf.readableBytes() >= 4) { long currentTimeMillis = buf.readInt() * 1000L; System.out.println(new Date(currentTimeMillis)); e.getChannel().close(); } } @Override public void exceptionCaught(&ChannelHandlerContext; ctx, &ExceptionEvent; e) { e.getCause().printStackTrace(); e.getChannel().close(); } } This time, "one" was used as the value of the &ChannelPipelineCoverage; annotation. It's because the new TimeClientHandler has to maintain the internal buffer and therefore cannot serve multiple &Channel;s. If an instance of TimeClientHandler is shared by multiple &Channel;s (and consequently multiple &ChannelPipeline;s), the content of the buf will be corrupted. A dynamic buffer is a &ChannelBuffer; which increases its capacity on demand. It's very useful when you don't know the length of the message. First, all received data should be cumulated into buf. And then, the handler must check if buf has enough data, 4 bytes in this example, and proceed to the actual business logic. Otherwise, Netty will call the messageReceived method again when more data arrives, and eventually all 4 bytes will be cumulated. There's another place that needs a fix. Do you remember that we added a TimeClientHandler instance to the default &ChannelPipeline; of the &ClientBootstrap;? It means one same TimeClientHandler instance is going to handle multiple &Channel;s and consequently the data will be corrupted. To create a new TimeClientHandler instance per &Channel;, we have to implement a &ChannelPipelineFactory;: package org.jboss.netty.example.time; public class TimeClientPipelineFactory implements &ChannelPipelineFactory; { public &ChannelPipeline; getPipeline() { &ChannelPipeline; pipeline = &Channels;.pipeline(); pipeline.addLast("handler", new TimeClientHandler()); return pipeline; } } Now let us replace the following lines of TimeClient: TimeClientHandler handler = new TimeClientHandler(); bootstrap.getPipeline().addLast("handler", handler); with the following: bootstrap.setPipelineFactory(new TimeClientPipelineFactory()); It might look somewhat complicated at the first glance, and it is true that we don't need to introduce TimeClientPipelineFactory in this particular case because TimeClient creates only one connection. However, as your application gets more and more complex, you will almost always end up with writing a &ChannelPipelineFactory;, which yields much more flexibility to the pipeline configuration.
The Second Solution Although the first solution has resolved the problem with the TIME client, the modified handler does not look that clean. Imagine a more complicated protocol which is composed of multiple fields such as a variable length field. Your &ChannelHandler; implementation will become unmaintainable very quickly. As you may have noticed, you can add more than one &ChannelHandler; to a &ChannelPipeline;, and therefore, you can split one monolithic &ChannelHandler; into multiple modular ones to reduce the complexity of your application. For example, you could split TimeClientHandler into two handlers: TimeDecoder which deals with the fragmentation issue, and the initial simple version of TimeClientHandler. Fortunately, Netty provides an extensible class which helps you write the first one out of the box: package org.jboss.netty.example.time; public class TimeDecoder extends &FrameDecoder; { @Override protected Object decode( &ChannelHandlerContext; ctx, &Channel; channel, &ChannelBuffer; buffer) { if (buffer.readableBytes() < 4) { return null; } return buffer.readBytes(4); } } There's no &ChannelPipelineCoverage; annotation this time because &FrameDecoder; is already annotated with "one". &FrameDecoder; calls decode method with an internally maintained cumulative buffer whenever new data is received. If null is returned, it means there's not enough data yet. &FrameDecoder; will call again when there is a sufficient amount of data. If non-null is returned, it means the decode method has decoded a message successfully. &FrameDecoder; will discard the read part of its internal cumulative buffer. Please remember that you don't need to decode multiple messages. &FrameDecoder; will keep calling the decoder method until it returns null. If you are an adventurous person, you might want to try the &ReplayingDecoder; which simplifies the decoder even more. You will need to consult the API reference for more information though. package org.jboss.netty.example.time; public class TimeDecoder extends &ReplayingDecoder;<&VoidEnum;> { @Override protected Object decode( &ChannelHandlerContext; ctx, &Channel; channel, &ChannelBuffer; buffer, &VoidEnum; state) { return buffer.readBytes(4); } } Additionally, Netty provides out-of-the-box decoders which enables you to implement most protocols very easily and helps you avoid from ending up with a monolithic unmaintainable handler implementation. Please refer to the following packages for more detailed examples: org.jboss.netty.example.factorial for a binary protocol, and org.jboss.netty.example.telnet for a text line-based protocol.
Speaking in POJO instead of ChannelBuffer All the examples we have reviewed so far used a &ChannelBuffer; as a primary data structure of a protocol message. In this section, we will improve the TIME protocol client and server example to use a POJO instead of a &ChannelBuffer;. The advantage of using a POJO in your &ChannelHandler; is obvious; your handler becomes more maintainable and reusable by separating the code which extracts information from &ChannelBuffer; out from the handler. In the TIME client and server examples, we read only one 32-bit integer and it is not a major issue to use &ChannelBuffer; directly. However, you will find it is necessary to make the separation as you implement a real world protocol. First, let us define a new type called UnixTime. package org.jboss.netty.example.time; import java.util.Date; public class UnixTime { private final int value; public UnixTime(int value) { this.value = value; } public int getValue() { return value; } @Override public String toString() { return new Date(value * 1000L).toString(); } } We can now revise the TimeDecoder to return a UnixTime instead of a &ChannelBuffer;. @Override protected Object decode( &ChannelHandlerContext; ctx, &Channel; channel, &ChannelBuffer; buffer) { if (buffer.readableBytes() < 4) { return null; } return new UnixTime(buffer.readInt()); } &FrameDecoder; and &ReplayingDecoder; allow you to return an object of any type. If they were restricted to return only a &ChannelBuffer;, we would have to insert another &ChannelHandler; which transforms a &ChannelBuffer; into a UnixTime. With the updated decoder, the TimeClientHandler does not use &ChannelBuffer; anymore: @Override public void messageReceived(&ChannelHandlerContext; ctx, &MessageEvent; e) { UnixTime m = (UnixTime) e.getMessage(); System.out.println(m); e.getChannel().close(); } Much simpler and elegant, right? The same technique can be applied on the server side. Let us update the TimeServerHandler first this time: @Override public void channelConnected(&ChannelHandlerContext; ctx, &ChannelStateEvent; e) { UnixTime time = new UnixTime(System.currentTimeMillis() / 1000); &ChannelFuture; f = e.getChannel().write(time); f.addListener(&ChannelFutureListener;.CLOSE); } Now, the only missing piece is the &ChannelHandler; which translates a UnixTime back into a &ChannelBuffer;. It's much simpler than writing a decoder because there's no need to deal with packet fragmentation and assembly when encoding a message. package org.jboss.netty.example.time; import static org.jboss.netty.buffer.&ChannelBuffers;.*; @&ChannelPipelineCoverage;("all") public class TimeEncoder extends &SimpleChannelHandler; { public void writeRequested(&ChannelHandlerContext; ctx, &MessageEvent; e) { UnixTime time = (UnixTime) e.getMessage(); &ChannelBuffer; buf = buffer(4); buf.writeInt(time.getValue()); &Channels;.write(ctx, e.getFuture(), buf); } } The &ChannelPipelineCoverage; value of an encoder is usually "all" because this encoder is stateless. Actually, most encoders are stateless. An encoder overrides the writeRequested method to intercept a write request. Please note that the &MessageEvent; parameter here is the same type which was specified in messageReceived but they are interpreted differently. A &ChannelEvent; can be either an upstream or downstream event depending on the direction where the event flows. For instance, a &MessageEvent; can be an upstream event when called for messageReceived or a downstream event when called for writeRequested. Please refer to the API reference to learn more about the difference between a upstream event and a downstream event. Once done with transforming a POJO into a &ChannelBuffer;, you should forward the new buffer to the previous &ChannelDownstreamHandler; in the &ChannelPipeline;. &Channels; provides various helper methods which generates and sends a &ChannelEvent;. In this example, &Channels;.write(...) method creates a new &MessageEvent; and sends it to the previous &ChannelDownstreamHandler; in the &ChannelPipeline;. On the other hand, it is a good idea to use static imports for &Channels;: import static org.jboss.netty.channel.&Channels;.*; ... &ChannelPipeline; pipeline = pipeline(); write(ctx, e.getFuture(), buf); fireChannelDisconnected(ctx); The last task left is to insert a TimeEncoder into the &ChannelPipeline; on the server side, and it is left as a trivial exercise.
Shutting Down Your Application If you ran the TimeClient, you must have noticed that the application doesn't exit but just keep running doing nothing. Looking from the full stack trace, you will also find a couple I/O threads are running. To shut down the I/O threads and let the application exit gracefully, you need to release the resources allocated by &ChannelFactory;. The shutdown process of a typical network application is composed of the following three steps: Close all server sockets if there are any, Close all non-server sockets (i.e. client sockets and accepted sockets) if there are any, and Release all resources used by &ChannelFactory;. To apply the three steps above to the TimeClient, TimeClient.main() could shut itself down gracefully by closing the only one client connection and releasing all resources used by &ChannelFactory;: package org.jboss.netty.example.time; public class TimeClient { public static void main(String[] args) throws Exception { ... &ChannelFactory; factory = ...; &ClientBootstrap; bootstrap = ...; ... &ChannelFuture; future = bootstrap.connect(...); future.awaitUninterruptible(); if (!future.isSuccess()) { future.getCause().printStackTrace(); } future.getChannel().getCloseFuture().awaitUninterruptibly(); factory.releaseExternalResources(); } } The connect method of &ClientBootstrap; returns a &ChannelFuture; which notifies when a connection attempt succeeds or fails. It also has a reference to the &Channel; which is associated with the connection attempt. Wait for the returned &ChannelFuture; to determine if the connection attempt was successful or not. If failed, we print the cause of the failure to know why it failed. the getCause() method of &ChannelFuture; will return the cause of the failure if the connection attempt was neither successful nor cancelled. Now that the connection attempt is over, we need to wait until the connection is closed by waiting for the closeFuture of the &Channel;. Every &Channel; has its own closeFuture so that you are notified and can perform a certain action on closure. Even if the connection attempt has failed the closeFuture will be notified because the &Channel; will be closed automatically when the connection attempt fails. All connections have been closed at this point. The only task left is to release the resources being used by &ChannelFactory;. It is as simple as calling its releaseExternalResources() method. All resources including the NIO Selectors and thread pools will be shut down and terminated automatically. Shutting down a client was pretty easy, but how about shutting down a server? You need to unbind from the port and close all open accepted connections. To do this, you need a data structure that keeps track of the list of active connections, and it's not a trivial task. Fortunately, there is a solution, &ChannelGroup;. &ChannelGroup; is a special extension of Java collections API which represents a set of open &Channel;s. If a &Channel; is added to a &ChannelGroup; and the added &Channel; is closed, the closed &Channel; is removed from its &ChannelGroup; automatically. You can also perform an operation on all &Channel;s in the same group. For instance, you can close all &Channel;s in a &ChannelGroup; when you shut down your server. To keep track of open sockets, you need to modify the TimeServerHandler to add a new open &Channel; to the global &ChannelGroup;, TimeServer.allChannels: @Override public void channelOpen(&ChannelHandlerContext; ctx, &ChannelStateEvent; e) { TimeServer.allChannels.add(e.getChannel()); } Yes, &ChannelGroup; is thread-safe. Now that the list of all active &Channel;s are maintained automatically, shutting down a server is as easy as shutting down a client: package org.jboss.netty.example.time; public class TimeServer { static final &ChannelGroup; allChannels = new &DefaultChannelGroup;("time-server"); public static void main(String[] args) throws Exception { ... &ChannelFactory; factory = ...; &ServerBootstrap; bootstrap = ...; ... &Channel; channel = bootstrap.bind(...); allChannels.add(channel); waitForShutdownCommand(); &ChannelGroupFuture; future = allChannels.close(); future.awaitUninterruptibly(); factory.releaseExternalResources(); } } &DefaultChannelGroup; requires the name of the group as a constructor parameter. The group name is solely used to distinguish one group from others. The bind method of &ServerBootstrap; returns a server side &Channel; which is bound to the specified local address. Calling the close() method of the returned &Channel; will make the &Channel; unbind from the bound local address. Any type of &Channel;s can be added to a &ChannelGroup; regardless if it is either server side, client-side, or accepted. Therefore, you can close the bound &Channel; along with the accepted &Channel;s in one shot when the server shuts down. waitForShutdownCommand() is an imaginary method that waits for the shutdown signal. You could wait for a message from a privileged client or the JVM shutdown hook. You can perform the same operation on all channels in the same &ChannelGroup;. In this case, we close all channels, which means the bound server-side &Channel; will be unbound and all accepted connections will be closed asynchronously. To notify when all connections were closed successfully, it returns a &ChannelGroupFuture; which has a similar role with &ChannelFuture;.
Summary In this chapter, we had a quick tour of Netty with a demonstration on how to write a fully working network application on top of Netty. More questions you may have will be covered in the upcoming chapters and the revised version of this chapter. Please also note that the community is always waiting for your questions and ideas to help you and keep improving Netty based on your feed back.
libnetty-java-3.1.0.CR1.orig/src/docbook/module/state-mgmt.xml0000644000175000017500000000047111064705014023363 0ustar deckerdecker %CustomDTD; ]> State Management To be written... libnetty-java-3.1.0.CR1.orig/src/docbook/module/template.xml0000644000175000017500000000046611064705014023120 0ustar deckerdecker %CustomDTD; ]> Chapter title To be written... libnetty-java-3.1.0.CR1.orig/src/docbook/custom.dtd0000644000175000017500000001315011167575612021314 0ustar deckerdecker Bootstrap"> ClientBootstrap"> ServerBootstrap"> ChannelBuffer"> ChannelBuffers"> Channel"> ChannelDownstreamHandler"> ChannelEvent"> ChannelFactory"> ChannelFuture"> ChannelFutureListener"> ChannelHandler"> ChannelHandlerContext"> ChannelPipeline"> ChannelPipelineCoverage"> ChannelPipelineFactory"> Channels"> ChannelStateEvent"> ChannelUpstreamHandler"> ExceptionEvent"> MessageEvent"> SimpleChannelHandler"> ChannelGroup"> ChannelGroupFuture"> DefaultChannelGroup"> ServerSocketChannel"> SocketChannel"> NioClientSocketChannelFactory"> NioServerSocketChannelFactory"> FrameDecoder"> ProtobufEncoder"> ProtobufDecoder"> ReplayingDecoder"> VoidEnum"> SslHandler"> libnetty-java-3.1.0.CR1.orig/src/docbook/master.xml0000644000175000017500000000324611175564104021320 0ustar deckerdecker %CustomDTD; ]> The Netty Project 3.1 User Guide The Proven Approach to Rapid Network Application Development libnetty-java-3.1.0.CR1.orig/src/docbook/css/0000755000175000017500000000000011316313126020057 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/docbook/css/jbossorg.css0000644000175000017500000000361411065137132022427 0ustar deckerdecker@import url("documentation.css"); @import url("docnav.css"); @import url("reports.css"); @import url("extensions.css"); @import url("codehighlight.css"); body { background-image:url(../images/community/bkg_gradient.gif); background-repeat:repeat-x; margin:0 auto; font-family:'Lucida Grande', Geneva, Verdana, Arial, sans-serif; font-size:12px; max-width:55em; padding:0em 2em; color:#333; line-height:150%; text-align:justify; } /* Links */ a:link {color:#0066cc;} a:visited {color:#6699cc;} div.longdesc-link { float:right; color:#999; } /* Headings */ h1, h2, h3, h4, h5, h6 { color:#4a5d75; line-height:130%; margin-top:0em; font-family:'Lucida Grande', Geneva, Verdana, Arial, sans-serif; background-color:transparent; } h1 { background-image:url(../images/community/title_hdr.png); background-repeat:no-repeat; border-top:1px dotted #CCCCCC; line-height:1.2em; color:#182737; font-size:2em; padding:1.5em; } h2 {font-size:1.6em;} h3 { font-size:1.3em; padding-top:0em; padding-bottom:0em; } h4 { font-size:1.1em; padding-top:0em; padding-bottom:0em; } h5.formalpara { font-size:1em; margin-top:2em; margin-bottom:.8em; } /* Element rules */ hr { border-collapse:collapse; border-style:none; border-top:1px dotted #ccc; width:100% !important; } sup {color:#999;} /* Custom overrides */ pre, code { font-size: 100% !important; font-family: monospace !important; } pre a:link * {color:#0066cc !important;} pre a:visited * {color:#6699cc !important;} .programlisting, .programlistingco pre { line-height: 160%; } .programlisting img { margin: 0; padding: 0; vertical-align: middle; } span.co { position: relative; left: 0; top: 0; margin: 0 0; padding: 0 0; height: 17px; float: right; } span.co * { margin: 0 0; padding: 0 0; } libnetty-java-3.1.0.CR1.orig/src/docbook/xslt/0000755000175000017500000000000011316313126020261 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/docbook/xslt/pdf.xsl0000644000175000017500000000711611065630536021577 0ustar deckerdecker normal 1em url( ) libnetty-java-3.1.0.CR1.orig/src/docbook/xslt/xhtml.xsl0000644000175000017500000000076211066333151022154 0ustar deckerdecker 1 libnetty-java-3.1.0.CR1.orig/src/docbook/xslt/xhtml-single.xsl0000644000175000017500000000077111066333151023433 0ustar deckerdecker 1 libnetty-java-3.1.0.CR1.orig/src/docbook/xslt/eclipse.xsl0000644000175000017500000000076411066333151022446 0ustar deckerdecker 1 libnetty-java-3.1.0.CR1.orig/src/docbook/images/0000755000175000017500000000000011316313125020533 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/docbook/images/architecture.png0000644000175000017500000013053411167640677023754 0ustar deckerdecker‰PNG  IHDR ?†æ™sRGB®Îé pHYs¯¯^‘tIMEÙ /k²ø¼ IDATxÚì]wTTG¿o »ËÒ»€""D)6,¨€`E%ùL¢‰Æ(ÆØ¢ÆØMì%k¬Ø£"`7‚5ØP Uz¯KÛöÞûþxHp,» ¨ó;ïxðN»sçîܹS1’$áã ‰xdàG@@@@@@@xdàG@@@@@@@xdà>u0š¹¼{÷îUUUÉ òòòâp8¨ ‚xøðaJJ XXXôêÕ‹Ç㩟­H$ºuëVÏž= ‘²6F»JJJ‚ÐÓÓ³´´tvvÖÑÑi=ìíß¿ßÌÌlÔ¨Qͦ?¨i†i/2ðµ¸yófaa!¥b±˜Á`Ðét*ÈÝݽÕøÊÊÊ{÷îy{{ëêêʰgÏž¸¸¸öíÛ“$ùàÁ33³.]º¨_njjjhh(N÷÷÷GÊÚ "##óòòx<ž@ gòäÉnnnlhu““£(HKú£=…GК_ ê÷0Mnt¤½ÈÀ×bÙ²euеaÆɓ'÷èÑ£õ‹ééÓ§¡¡¡^^^rC“’’^¼x1~üx???àóùzzz)×ÙÙyáÂ…ööö¨ïk$œœœæÎ iiiû÷ï?pàÀ† ßÊZKОþhIá>5¨ßÃ4­Ñ‘ö"ß0ž?NM«FGG …B???]]]‘Hôüùó¼¼<‹åììlggGEŽŽŽvuu-..~ñâNïÚµ«™™”••=yò¤¦¦¦M›6;wf2™Tdsss>ŸŸžž®¯¯ïááQ7UZZYiiiÙ¥Kƒ!—777jöéñãÇ,ËÑÑÑÜܼ>óeeeжm[ê¿õ§§jjjbbbJJJŒŒŒ<<<ôõõåaffÆb±ÜÝÝë>~üX PÓ¦¦¦½N&l6ÛÕյ޹ÉÈ'‚¶mÛ6ìèÑ£éééB¡PV»d[¿  @nC+ÒEÍ¡$¾\(Òʲ···±±¡(oÞ¼‹Å®®®J´ZI"ÞTUxm  ݈¬š™™)Ò¹ ™™Iõ0B¡P¶Ñcccõôô:vìXW\\\ƒÁpqqQζÕU®¢ÍÐ]#ßçr¹EEEÆÆÆAÀ®]»’““ÍÍÍ+++Ï;èãã'OžtttLMMµ±±ÉÊʺ|ùòÒ¥Kétúï¿ÿŽa˜MddäÈ‘#©åÉ“'I’äñx¡¡¡AAAÎÎÎ/_¾Ü»w/dz°°ˆŒŒ¼råÊüùó¹\®,3¶¶¶‰‰‰E§Ó¹\®”Æ´iÓnݺնmÛºÈÊÊÚ¾};I’666999!!!3gÎtrr’-¢C‡7nÜØ¸q#µH‘——wàÀ77·´´4>Ÿ?gÎÊÀgeeíØ±C ØÙÙñùüU«V™››Ë-ÈÄÄD®@>9g0NŸ>-¥]r[?//O¶¡•è‰Üæ(,,T_éI’GŽ=zt]/YYYéêêªH«•(<(ª‹ª   4¡‘ÕÀ+V(ÒÙnÇÊÊ*,,ŒêaÄb±l£'$$DGGoܸ‘âG üõ×_õ ¼\¶•¨®rm†îø›¡š3g޳³3I’eôèÑfff‡ ˆ]»v]¸pÁÛÛÃ0¨¬¬üý÷ßÙlvqqñÒ¥K£¢¢LMM«««ýõW{{ûªª*‚ êrîܹóÔ©S1 «¬¬Ü²eKppðŠ+<èää4sæLV\\¼zõêÐÐÐo¾ùF– ÃÊÊÊNœ81wî\¹=µ••Õ€nÞ¼ùöíÛ¡C‡öîÝ›N§ã8¾gÏ[[Û3f0™L‰D²sçÎC‡­[·ŽªBý"JJJ®_¿þèÑ£À½{÷ôõõøá‡ŒŒŒ 6P¥H$’Ý»w³Ùì¥K—RCø‚‚sssE :T‘@>ðùü›7oêêêÚÚÚJI[(*j}©†VSns¬_¿^‰^É…\ýi°‚²Z½víZ¦(H,+Ñy•APµÁq\VMMMßÍbfhhHõ0nnn²îååuóæÍçÏŸwíÚ•ò•%‰§§g3k¯f»ëO ­è˜œ££#5ˆ£ì5íÃb±žœjÅFj Ç›0a‚»»û“'OäFxõê†aÔÏ&--­Žž˜˜hee¥Hc¨™‘HÔ¨ÈÔÉ“—/_6²¾†ùøø<|ø0..ŽZ‰—•á«W¯¤èíÚµSRPƒùA9=r[_ª¡•Ä”ÛJâSM,w J®þà8ŽaF«®®® RtI¥ÕÔnEAÊySGá´»¹Øxid£ëêêvïÞýþýû?vuumð• Ag£AíÕjw<ø–µ[$66ÖÇÇ'''çÊ•+PQQ¡È!...¾pဘLf~~~}8%%%++‹ÅbÅÆÆR×6¹»»ÛÛÛ‡††šššÞ¾};--mÒ¤IJüB¸qㆯ¯oUU•ÔÁtjçK=ÌÍÍß¾}Õµk×:têÔéܹs ÃÙÙ™º{aøðáJÖÂ{÷înggçàà êèèèäätîÜ9:îìì\QQqçÎñãÇ;88È-H$)È'GGGE­/ÕÐJbÊmŽqãÆ)Ñ+“7oÞ<}ú´K—.õ åêÕyÙÛÛ?|øÐÕÕ•ÇãݺuëíÛ·uÓ˜²Z]×Ärƒx<^ãu^¹Â#hªv#Š:%:Óàì—ÜFïÓ§Ïýû÷óó󃂂É6“ÉTΆJÚ«ÙîøVvíÚ <8,,Œj×1cÆ\ºtéêÕ«3fÌ¿¨¨èÕ«W>¤zÒúó´|>ýúõb±˜N§÷èÑcâĉ†S;HuuuÇŽÛ§OEÌtèСÿþ‘‘‘‘‘‘ÆÆÆëÖ­“[äçç=zh4Z=¨ÉðiÓ¦:uêØ±cA`æààPYY©ÄÀëééõìÙÓÑÑQQ„3fœ_$ÉL’dQQ‘P(411‘šÅ …\.·1÷& å»á„Bayy9—Ë­o$ä$W  ¶¾lC+ѹ͡(>I’eee†††RÍ¡D¨S”§¾þ(Ñjå ¯’Î+Qxm i݈¬ÊÕ™FBn£¯Y³ÆÁÁAÑ;El+b£ÉÚ«©îyð­§î‚z¦|žÃ0ccc¹AL&Sî Ñúù7%/(`Fݦ' ‹%ÛÉ*Bc~,KîyÙ‚”AIëË6´=‘ÛŠâcfdd¤’þP§(UÒjåA×yôdHóÏ-5¡‘Õ@%:£j£—––>|ø033󫯾R•mål4A{5Õ]#€€€€ðIC,ÿòË/ººº'NDû0>È!c+Ÿ¢WoÞ¼122ª;€ðqk5RxM$É””;;;Í>»Œ´x„¦ƒ†D€€€€€€ðñA‹kðqqqÙÙÙHÄ­b±xذay‚BffæÃ‡?©ggµ$vPpu‚JbìÙ³§Jwµž={‰]}±s8tŒú055íÛ·ï‡jàsrr† ŒZ±5#**J¥5@п_´B¦¾Ø¡¿¿…:(//ÏÍÍW)‰•••¶»ÔùùùQQQcÇŽE¢P°ð‰=QúáAå$8$9õÄŽ#1jBŒRU}G›Ž4Òg 1~`hW||žÀÀ‘äÔ;$£FüBU}G}’&ú ‰±zßVçÁ#-øUL€\O5àHŒjCÒL* 3HBbD<‰¦è?B¾Ö8!¨å{HŒš'¡)ú–é3‘G?¦ÑƒG‹Ç;Zƒ×ˆ%¨‡Aø€‡ùÚ÷Ñ=2ð*“†,“zÀpÀp$FµÅˆ6ÙµLŸA’è‚4Mè¯ößÿBSôÈÀ«>ìDͪþÐ@¿õÅH"ßr6‰áðÑ1¹OÞÒ¨¬’ ÅHrêý²%HŒš£XUhVQCÖ‰ñƒZƒGcHU€‘ï6ˆ!¨%w²9Ř_PT\\jcmi` ¯©<ÃÎÿãÙÃÝÆÚ²ǧ-¨‰UUU™™&&&ffæ "‚F£)úo}‚šš&“Éår5È3Žã÷îý+‰¼¼úI½7€~xóc†´œöJT]ÆÔˆÓA’äŠKvìøC @=÷ì9ЩSgåAEE…£FDEE×ÙZ—¸¸D¹EXX …B000ðóôÛoëګɶD">|Prr’£cOÏÞººjõÈwû €›APÑ“$ú>ˆïü…ˆ€QÓºuù,îÉÅ¢ì‡!§¶;;µÓXþµúвuTÙ8©ÿ­_¿fïÞGŽœÊË+‹Ž~Îf³‡ PXX¨<(666&æqzz:•Ƀ÷“““RSSåK–¬|úôÕÞ½‡^¿~9h@ T“í«W/ÇÆ>‹‰‰¿zõ&—«¯NVš’$úЪˆDÝhƃ×þE7"‘xÆO+Gô Þÿ;E5‡òåêâ<}uÿA¬~ÀÐþÆFŠˆ ~ñÊ휜wç;ÿ>™8!ÀÞÎú]EjsKNɈ¸ñ€Édøùöj×Ö¦¹Ä¨š‹¢þÆßŠ þæÍëV¬X0 >ûÌíÔ©°ŽíöîÝ5kÖÊ1$ FŸÚŸ×v)w£åæ.˜÷µ¢KVüÑßÒÃèØý‡Îvt ˆùZ.Q$ªö66¶qqÏ•¼x;}úOÛ·oÌÎΩ©©NMMþñÇù11ÑŠø©ªª®®$'',^<ßÚÚÆÅÅ æÍ›Ñ†ÀÓ§1›7¯=>ÂÇÇ&N½hÑÜU«ÖËÏŸøá‡Ÿø|~xxÈ?ÿD©Ù1`†ú€h=2ðhŠþ㜢' ÐhUÐý‡Ï&~»œ_Qµuýœ9?N¸zý_k3ßnTè˜Ï}¦Ìøýòµ»²Äχ÷ãés¬, $.ÎvPT\ÜÖžÚNHÂ.ÞÐÕe=yÿäi<”—Wò+ªRÓÒ?sn§e1Jšÿ˜†Ñ¨5 ã¿ÎÇq:®$¨¦F””àç7øÑ£ûçÏŸÃqI¿~¾ÞÞ~‡í%ð¹s§———À'©­õ‹Í^´h68;vâD8ƒÁ€qã&Ö=ôrýúU++ooê¿Ã‡™5kÊ?ÿ\–%J$8N×Ôæ8´ÉxäÁ¤ž$Ñ.zÍxíï¢ogo¯^'¹uv€€Á=Ërþ1µ€))/¯02Ô¯ãAŸÃ‹%%%e²ÄÞž.eåÁÇ.Œ3`×Þ3æÆ]ìß=ÕŠ)),,árôôÚ í&ÆúëVM·¶4Òºž´„ÚÛ·€äägçNuÄ””$[[{%A¯^Åá8Þ©“ÛØ±Ξ=I£ÑÆûŸ««Ÿ_ž’’äèèdiiÍá¼w"nñâUƒ 355³µµ¯#êÖÛûÎç—ÕýW___,—––ÈE"¡žõë¼{Õê}ÒPõ ‚€ú¡UÕÕÙÙ&FFæ¦¦ÍøKmsð8NÐhVïL”D‚3t'äÞ™‰a˜\:ƒAD5!“ÉàrZð0Ñ çà½û¹óô9ìüûðÞ_e¦a;[ó¬ì‚P•”’ilÄkï`}ä„4±[§][ç}7cí·Ó׸unþô:]]aI„½yuµ`ÎÌq2sòÚÖ“ð"½¼ú³ÙœÓ§¯X±Ž¢äæfß»wgéÒß•ÅÅÅÚØØŽ9ö—_fcväÈYSKK«gÏž8::-Z´\ª ++ë.]º+á¤M»œœ¬º#%%ÉÈȸmÛö99G¤ˆšµîT¿Ô˜hee¥¹¹Ù&&fææJˆ8ŽÓh4¬¡$IVTðy<ƒÆ—¥v·ƒ+èFŠxV‰f0ðZÞd§:\¼½KËËëþ{ðÔ)›nÝÔd„_Q1nÚ´ÄÔTÙ À  11ÉmûVb‰Z^…’ê ünÞ¼:]ÿuýzÓÎ?óñ±pwï5|xü›7Íe›ˆÚ'á›ñã˜û ¾X÷ߨ{±LCŸääŒöÇ3 }d?Et pC›!Æm†é[ 2´2þëe))™Í_æ‘!WOgÍŠ©ÁǯΘ½éÕ«”‚ü¢¿ÏDTTVIÞW$’lÙ~ŠÄ%éé9;ö†|8H.±¸¨tý–ã环¾~~óoK¿³±4¦ò76â]ºr¯ºªjÂ_&“4g3¿œ‹Åç/ÞÍÏ+j&Iªø"Ÿú£ØlîO?-عs˱c‡òóó=º?aÂH33‹I“¦) zñ"¶S'7’ccÓ¾}}zõêkllJ’Щ“û³gO¹‹MŠ8bÄ‘H´cÇ‚ 32ÒÿúkÇ„ ßÈ%ÊnÜSóð†ã¬\¹¸}{3//w''ËuëV*!Z[sŽ=Ø`†7nü3l˜w#ËÂq"11¡ U«ŸÐ㽩)SöSijÜÚµà¹Ö8EŸž•5uþüsûö½§jN ÕÛ¤Àbêç6ÜÏOÅbÒhêpÛpõ ÖüùçÎÇOíÚåÛ§OzVÖœ•+ŒÿòÆ 3íÂZj ¾þ¢5Õ­KÂN®ŠÄ°hù~:¶vÅ*˜¥Ã”K§rX¹ø›ñc|^'d,ûý°Ï°ÙɱGY,f³×…h1þ8mƒ+×Ý{ð°õX£†÷=¢7€ÄÆÚðÌÑeÓ~Úºj]°P$ûy¿5+¾eë±d‰`l¤ÿåäUmí,h4ÚÛôÜËg×úûvý}Ùä™ów˜™ò6¯ùájèÚI?l0²N£ÑÚÙ[Þ³ÐÂ\_ûbl™¥¢ –ÕÔTÿüóL¡p xyy:tZ_Ÿ§$(>þyŸ>ý©äcÆL‰DÔß®®îÝoVV6ÁÁgfÏž¶aÃ*‘H8räØeËÖèé±e‰Í߯߾¹mÛú'‡ ñòå j:A.±ñ8}úø—_~ÝȲ.œ•››}âD¸ªU«Ÿðøñ0‘H+V,¢ÓéË—¯UµÊ--OÑãMyñúüõë{>qâªô.Ÿ§ññ÷cb ôõ  fÈEbñ{÷õëw!22+7·Ïžî..²S-P\\|ðäI ÆùúZ𙽧­Šó§™›U]SãÕ½{j>Ÿ ÇBáå›7»tê$Áñ¯_·µ±WÂ’D"¹xãFN~¾ÇgŸÝyôhâ¨Qö66­>eéqœ_Y¹nçÎ5 Œò÷7'§°¿þ²ëÝ{WpðÊ9sT„R}R´¥Þƒ¯ÿ€:õÑŽv—‘!‡Á ÷êá$•F†Ž€µ±KG—Ž6æ¼¾ƒæ=}žÐÛÓ¥% |sˆqú”aÓ¾š‘U@„]sƒ^'‡€ÁÝ3_ŸÈÎ)âñØ<E—G„˜wÖe8xÔ¯!çïøûºûÕÀÀ/¼k"ܳ[‡×Oää3™ 3Sƒzm¤m1¶Àc3F[±bÃÂ…+rr²ŒM©ƒæT¶Š‚®^ª‹3vìÿê^c[¾|½Üavn®@–.K80 >>377[_ŸGÍ]“¤|"ÌŸ¿tþü¥šr•瓘ø†Íæ ú9tîìAÅ—Kld†ÕÕUW¯^X½z“l4Ùl““““ø|þùó!V={z@qqÑ×JKK:vtéßß2À—.…uëæ™––;hPŽKd€¡¡ÎèÖ­—«õ™Q^»–‚–GM:b9êÔEëÖ½LHšWZ²iSÿñã>{¶ÿÔ©Ž¾¾ñ @’üŠŠa“'ûOœ¸çرãaa݆¿uÿ¾Ü©) ^½}{ýîݼ½ÿ‹ÓPþ@’ûNžtìßÿXhhÄ¿ÿúN˜ûêU]’ï,X³s§…‰ÉÓ¸¸k×þ´b…–D"‘ï„ sV­º3ä›o¶<ȤÓ_ýº¿o?xP]S3fðàºT\®Ÿ—×Í{÷´‘ „qs@âÿý—Äà=Nj§:dÊÒëeEÇ`1±æ®‰Ù|ÅÑ@Ò¶±ƒ)ƒFÈÙZpu” ò =úL_¿åä…ËQÿøûþ£—^ž© ]̈ǪKhmÁ33f7¯b´Øv/==vûöNuwË42tttX,–ÆzpÍÆÆVjeZ.±9ѹ³{uuÕáÃ{$6/†vëÖÓª1e½~ý2991++ãäÉà;wnPkšöܾ}Õ+á#§M›HÅüþûÀ  IK—λt)TWWW6¡šUþ¨=ø¦Žaz¸¹ñ¸Ü ³f=>¾né)&>~í®]ÇŽù{yÀèéÓç®^qìaòر“ÆŽ¯/¾8|ö¬o¯^²lœÙ¹³¿§'Žã_Í›÷õ¼yoïÞeR§YHRIþ ©©AË–íùí·ï'L€ ª¦†JµfçÎ;E‡…qôô& ž•›{àôé:Ã)ËRø?ÿ<ŠMв27¹zuÜÌ™"‘HVDr«_ÿßô¬,°µ´¬ŸÖÖÊêùë×MÙ¯²ÿBÖ½ê÷?íøþ§ 9ÁHRcòèÕ5Pœ=ék×NvÍ^#0h16úúºßú†_~tðØõ6Ö¦{·MïÓ*ÂȦ]U‹ ¯M zõê7sæüŸ:v(º4[ IDATìà‚ˆ ©ˆØÈv9sæøøñ_É#›m@Àèë×/?þ®“Ã.\¸mcc ×®]œ8qäªU›¬­ÛƒÁŒˆ¨½Z@^BéXÏJj§QóØz\"¡SËÿM¸j¼¸E<øß–¾Žþ“úNìŸ#ǃB¾/E˜½h¿žÅ^³ËÊ*Ã/bÒ‰f÷à%-3Ò¤O…Í ¸{yuRÌÎ[WNü«±§ºoZ·„>©>£Á8+Wn¾sç¹]»‰?_½z±bÝF#E_^^ÞãÇÆ6¾¬ú'õïÙ³í»ï¾üû™IE;v"IbuÑdÖëz¡~4YžåÖNc]ïGãÁIÒi´c›7»ž™“CQÊ+*Œ ê2Ôg³Å‰P(|ow)F#HÒÚÜœËf¿7Ðz÷‡™‘TVUÕ§+Ê¿¨´ÔÒÌ “Îí:vìsÿÍ|õùç:L¦ôz„<–¼{ô(«¨>wnüС»Ž³05íÜ¡ƒÉ«~ýÐv66’Ò©C‡:rRZš½µµö=xꢛxÈÜÒ\ß¹Cíã›EÅ%ðî²ÒºzLcrè«6°‹™)ÏÞÖô]>Í IK‰ñã‚°¦ì¢GP¿SoŒ]8³uëï[·þ6kÖ/Ô’\¢òv 99hÐp6›«$ŽT¶RyVUUÚ›Ç3˜:u–X,ºx1Çq*”ºôW¹’4ƃWRe%.ð¾ßT¢­•ÕÎåË/ݺEåcgi™•—G¼s[“Þ¾560`³XÒãÉw#«åAA›.ܼp! @*NJz:8´iaIJò·³´LÏÎ RLX³æÄ¦M5Á†¿þ’ëÁ˲ԩ}û]Ë—÷Ë/7·{11çwïÖe2YýúùôïÞ£§w<<¼.UvnîèèÁ}ûª,í&< -waþP8¢jð¼€µ¥QwvömLZîjm‰Q •–VVVÖh‰s‘PrþaIIEã“àüö¿/¯ß|^S#ÔŽ$µ>«(ã"‘Dö E.„”””hÏWNIIŽŒ¼&K¯©”––VTT6-ÛK—²³³›Ì•J!½{ûˆD¢¼¼\EÄgVBBŽû•Je`8Ž×ÑÏŸ?›››}æLÄÈ‘_úû™­ß¿—°¾«­Ü§o°Êȃ—}=rä¥[·îDGIŽ8ð—Í›·:ôówßeäæî8~ü›Q£¤{Eå’$D¿xÑÓÍ-+/ï×­[öécoe$il`péÖ­ooEù:tÙöí3W­Ú²h—Í>{íZ×NÀÞÚš­«»{ÅŠÑ?þøåСNmÛÊ×½ÏRqYÙú}ûÎýù'—élÌÍåËG^õëqõôL™²fïÞöö>>)³~ûÍÂÄdÚøñͱOŠ€5¿Û¤ä¿rIq­÷…¨åM:,ýý¬ZÆ k‰öS„B ðôùº®[6®};óF?2)5¯££•’8|~ŸÉÛü³¼W÷F=O.‘àƒÆnJJÍïà`Ñ»û`iZŒ˜Ê¾ '{zölŸ••.K‹+œ:uÜÅ‹ºví¥%MùçŸK‡ï¼?YŠÞ¡ƒ!u‚K_ßÀÛ{Я¿®³·WáÁøéÓwî<ðEXÂqÊ *‹SYYqøðÎ#ÆÀöíkÍÍ-Û´q(/—C¤òIMM~ð ŠJËd2»téùßÜdÒëÜÜì¾})*QnY¦¦–‘‘Wòó tuõØl†1çó+étÖ߀ªªj*C)•JHm¶wDþ½r¥xîÐá3EµûH×àÕóà©oVV@6ffgþøcÛ‘#ú]»:ØÇÃcÍìÙJÜe©ÏÔÈèÔ¥K,WWûXLæñ)úï³gŸ½vmùöíŠò·02º²woTLŒ‘§§ž»ûÏ7&½}[Wâо}GùùM_±¢1¼žŽŽ±Á—sçÎ\µjá¦M팼w¯‘Õ—ÊÙôés'Mš¹zµ¥——W` >‡sãða›­uþïÜì4DŒ¼˜äÇûÁÊE£^=X{hÇÔ—o²|F® ÅL;ë—c‹VžiR[(ü.GÄ>‹K¿·ææùEú\–æëÛ,î†]¼øàâŽzõïÓÇ—úûâÅ-;U>þÊÛ·_mÝz(1ñ娱>”½oÎYz%HL|¹k×z/¯^^ÒÓS¾ÀdêÈ%RñwíÚ0zt?êûúë€úY;wläÈ/ë_ïߘ²&Ob³9–..†™™i#FŒssëÞ½»­««Y|ü³†9²[nnR •ÔQŠg%µkA`¤Ö~!ÿ„„ vÑÀñⲊ C}ýw"» €Çåp¹ª 3ˆ¢²2scãÜÂB]ˈǫ* k„BЍ$ÿœ‚ ìê Wƒ§MkצÍÞåË_})T Yyy¦FFÆM<õôi¯À@%?)$½‰á‘w,Ìxh%RD=JDþÞŸi3` «ƒ½<}‘q?:Ù€§0ÐÍØˆ“˜’´ð¿¢fá¬!V^žŽ²q ¨¤Ò¬ãÜK'gåð1 †ù»Zš@UµðêøÁ¾ô¹ºð*!'¯€obÌÙ¼ëúýè” +ÆöíéHÅÔ Êù5¹Õ®Î}Ÿ$,,ÊÓ³o“Kœ2eÎØ·/„úoII‘››Yhè¿ÅÅùù¹ÞÞƒÚµë×®…yxx¦§§¾zëç`gçiiÉwïF0™L//?;»vTòÛ·¯•••8:ºôíëWÿj”ì쌛7¯èè°²³ÓÏ;~ïž´ïà »fÍÎÀÀ©ðøñ½Ñ£ûž?¿[·ÞqqOŸ<¹Ïãøù¿›i&:8èîØÑD¾°0ÿÅ‹{~~cš¼gf¦±XºÖֶʉêCn¶8Žçæfêë×*^^^6—Ëãrõ ¬¬¤N>2SÒ ÕaC >Œ;và‡¿ìÇ¿š9sÑüù+`Ë–UçΓ˳@P- RRV­šoii#‘ˆÿüsíéÓýúùÀwß^¹rî’%ëe‰§OGHUDÕê„Ĉðx@Ï ¾=&sÞĉó&NlEòiÂ2¨á‰ÔM)õCë_Ÿb``zäÈÕyó&uêdD£ÑlmÛmÚtxèÐqgÎ{zÚ²Ù?¿>>Cƒƒw{y 222ß½ûì‚ßuîlÌfsìíAÁ«ÎR7´˜™ÙìÚufñâiü±J$2vþü5zzlY"ŽÃÏ?ÿ¾lÙL##³%KTî=p¼É/#H· ¶¡Ísðÿ=¸}û&$ÜyæÌ/»vUÞ¹#ôôÍ›û/^p¹}û¿;Ξ™Ÿ]-x¹»{89••™ ôàС^; D¢ËQQ]:vt°±€äÌ̈èh&ƒá×£G;kkHÌÈÚ°_Uµð믭LM½ÜÝe µ`ƒNY¿ÂnßöìÔ)5;;611ÀËËÁƦ¨¬ìÚƒ%|¾KÛ¶~=zÐh4‘X|ãñãA½z]¸{7«  —.îï.OHOŒŽæ²Ù==M /ܽÛÍÅåvLŒH,öëÑÃÑÖVyMë—ÞÁÖvóñãÊ9oQ±±½&OfPwé7Io¢yâ³fôãTQÑÄ¿¿C‹v.dv^Ë2à±êõÝdV.ß§KeãYTRmnÊÉͯÔÕe¼·T\]#.-ØXê7OÊùÂ\¯³Û Æ'9{6ª{÷¾-%óüü&“ilüß]yyÙúú<Gúd6A……y††ÆYŒ¿Y‰üül.—Wÿ ·\¢P(j ŒT­EQQ~\\”¯ïXôCVGŒÿAŸƒoÒ0Ͻ}ûªšš½!!ÓG®O_²wïö3gFõŸ?oÛ¶[»vuvpØ>këV/77‡³tÏžˆ?ÿlkeU7VÿnÕª7ééÿîÝ 8¾/<|ζmºw‰Å?nܸñ⯇}™œœ˜‘!‹ƒ/]òüì3¯Î•Û—,éëî^^UÅÕÓëíMJ$=¿ý–Íb™-Š‹åí}jõj>Ÿ?lΟ®]™ FyeåÜ­[#þüÓ·[·ññÞ3fôqu¥Ñh'®^=¹jոŋ­MM{uŸ?sãÆÃK—~=t¨¢šJ•þ…¯oÜkc ImCPËõ$ˆ–# [+λé„ZÐi`oí#ÊÆ¡a`n¢ $ne®'•غ4¶.»ùêEâÖs±ææÖðþÊ«……MÅÀÀ¸.Ãh²‘å±a4KK[©„r‰::º::ºM¹«ºÑÍ 4F’¬o*ûý<<æÿïA›6¼xqٷߎì×bÞ¼Y{äHÄŸú÷è£-š»mÛΟÚ´iÏÂ…ßþ9Ô…z,VQY펕5ÁÁwž=‹>tˆ£§—”™´iÓ¥-[†ôê{BCܲeœŸßhoïË÷î•—‡oØÐHö˜ FôÁƒØ»…ƒÛ»vÙZXÀŨ¨‘ lúñG]˜0iØ0ðš6íðå˾ݺÝ~úԀ˽½{7ð«ªDb1_¹Ò·[7X¼gÏ[¶|1`À«·oekñ矲¥?KLT‰sE]‚J#‚ÿ–uÔ1ðHŒš˜†Pµ“Áq õ%õ ‘IbHŒš˜Eû  |S=xØ4iðàß‚ƒ?_¸ð—¯¾Z7}úÕû÷mÌÌü»v¥òãí=eݺЛ7ôõ§PD=p¼ö½öÛ·7ž%;p|XÏž«œ¸|ùòo¿íhgW$€“IE›2lØú£Gcß¼¹#[S\,¦ÓhÒ¥7ÈycTLåqºÉNdÝ}sj@Ü"Ý|â ˆÄøA õžƒwmßþÌo¿ý~äÈoÁÁ¿|õUye¥Q½+Ù©÷ÚóKK-ML0yº¶+4ôó¾}7Ÿ:õÕ A:LfaY—Í®;áfb`°núôÚÛgUå S¨¬©éýÃά/¾I$!·ná2£²Ú÷àÜîÛ·lÿþÎ_½lòä 1ï]æL]8ϯª’[S¡HÄÖÕ•*½Å\OMÑ«-FGbTÛÂSÙ B–IžDbÔÔPéCöàÕ^dðñðX&çÙYXd8NèLÊÌ4æñÚ[[ÊËŠD¬úÛÄH,Z4ÂË«Ó×_o8~|ÙäÉöÕÁœq㤠$Ib8µ1T¹/ï9Ú³7ofFïÛ§Çb•UVþ@n÷öí/¬_¿ÿâÅi7ŽðòªíMZØYXÈ­)›Å’}…¶aÎ5Þ@ÚE¯‘ß…VwÑJb$›¿Oú䥎n²k-æ±aКITù*ªªÖ;–œ••œ•µöØ1Kcc+«1ýú‰$’-ÿMDznîŽoïëKð™[¶”WVâ8þwddqy9%6{ 6‹µ{Þ¼5G&fdLðóc2A[¶ð++q?ÿï¿ù%%Tq–ÆÆO JJ*ªªÊ^J}õëò~¥4N•ÕÕŽ¹zªÙhÔ“23CnÝÂq܄DZX ¯Þ¾’LËÍ¿s§§‹‹‹ÜšÊ-½aÎó©Ö ðî¡ô©óáïîŠAŸšŸÊ}$5K>ôµ†ï7ðMºzåeJÊúãÇ;v LÍξ°ffcl|fÅŠmgÎèìاS§5S¦XðxW6lˆzñÂhØ0=ÿŸwízM]üµ§D‡öè1ªoßé›7›r¹W7lxo4l˜®Ÿß‚Ý»“32¨â‚FŽäèêZŽe8thZNŽ–ê–ºëqÅqÀñqýûwwr²;ÖlĈg C{öÜ*í]òØ„„Ék×êúù}¹bÅÏ_~é`a«ƒƒY´?ž†a§—/—[S¹¥7Ìyƒ_¶y ¥f~ÙH#Ú¨ˆ€v*%2Ä“ÉD’Z°°0qw€ãHŒê¢m[­O&iy=:K¡Fúúi'N´0*îô`êè;ÃÂÂ5Ÿ:ˆŠº'üýý(ÔòàËËss TJÒ±c[$7„OZ6ð躣V•OÙ‘@à@ fU$£úb” Mv-gà ôókå]¤ª D¾;â… ÖÀ €@bT_}›pLxdÝ”'d™Ô·LHŒQE„1ð† þ=xtǪú пêk/ŽƒÁèÕ£3õßää·70™ ?Ÿ^íÚÚÀ³ç¯óò‹‡ª}žáêõ(ks]+!1•ϯ ½jeiæÕ»‹ÜJÖg81)ýE|B[;+‘Ppãö£A~}.\¾••ß¿o7w׎uÑ’S2¤ШoîMvzzL[§«{Gï~ÝÓÒ³€Äëä$.‰‰¢¨¸ôÚõ{%¥å.ü|{Òh4»pó»kêÛ¬ØoètšŸO¯ŽNm©ø/âKJÊ}ú÷hõmåkðyyyOž<)..ÖÑѱ±±éÞ½;›ÍÖv¡"‘èÖ­[={ö4|ÿQlM!111--màÀXëöß´-dà‘ÿ ¼jËð€@sË$Aå¼ïP蜛x{ŠÄâç®Ý¿kÙ×ÿ ÐÑÁF9ûì‰#†õ?ñ÷•Yó6>{xêiì›Ä¤4‘H|,ܳ{'¯Þåja}†ŸÆÆ-^¾ƒÅÒ‰ºqhب>ý»3™Œòòʹ 7D\ÚãëÝCšýaH´#FE?D±D"xûúæíG;¶.×ÉáMl(¿¢L®(H’ìÙ?­§gff´héÖQ#|OY“öíãQ^^Éå²9l½ —n^»°‹*èû ~¾ž>ý=š¥Zb­÷`jàæÍ›gÏže2™VVVB¡ðîÝ»fff...MË­²²òÞ½{ÞÞÞºº ì™HMM ¥Óéþþþڨ׋/"""üýý•øÆ3¬È§m9|ê^"_PX} IDATŒG6´5#&-­—jÃpBk»ÃHH")9#höÚKç¶ Øöìùqîúq£ý:9·ûmùô?­µ²0žñÓÚ£VÛÛZØÛZ\¾z·¨¸,üô»®Þgx³²ó§ˆ“¿>iâpðòûîðÑó¾ý»)b@WWGsu%¨Ê6[COŸµfÆOkI’ü|¸w¿>î@ïÉA(0€Û×öÙ¶±€‹WîŽ7oÓšÙmlÌ€É`Dß=‚aXô“—½}¿ÍÊÊkccþ6-'úI|ð¾ÍTµV¼É...îôéÓ]ºt™¼ß;9àŠDQYUÓÛwš;kÆ"‘8$ì&ŽK¨8º,FÿS& ßõWè¯?}:$bÒÄ¡ÍW¯ÖzSP~~~NNÎСC묻^¾|¹wï^gaayåÊ•ùóçs¹Ü“'O:::¦¦¦ÚØØdee]¾|yéÒ¥æææyyy‰‰‰E§Ó¹\®¹¹ù®]»’““ÍÍÍ+++Ï;èãã“••ÆçóçÌ™c`` (CÈÊÊÚ¾};I’666999!!!3gÎtrr€ððp.—[TTdllLD@€²õ)¹EÈeXI‰ÿý÷íÛ·;tèP]]jkkKíöåä?þ­µlq‰¤¾ \ÿ”ˆGøkÕƒ··3«®Ì™9VfJ\ò">eͦ#£Fôûjʪ§÷X˜Aí“FÊY•xðõB‰ø`=øÿªYU] \ ‘òàeEq642;§0úÎ^==VYyåûqþãÿë@ÿEËv•8n@3Ö«•>6“““”s) ¡PxðàA''§™3gÒh´âââÕ«W‡††~óÍ7PYYùû￳Ùìâââ¥K—FEE3ÆÍÍ­¬¬ìĉsçΥ̌=ÚÌÌŒÃá±k×® .x{{wíÚÕÐÐpÆ uÅÉÍÇñ={öØÚÚΘ1ƒÉdJ$’;w:thݺuÔÊzRRÒœ9sœÉFÌ‘È-BŠa%%fggߺukäÈ‘$Inݺ5++KOOÊ\йµ–+Ÿ:9(¸"þ?ŽÎ"EPÕùĵò‘$õTÝ„1>L&=hÎ~y.Ÿ¿x7?¯\P]3ñ»ß¾ž0ðܱ•.í¾üf.[š>M(È/®àW‰t¶É)YQ÷b©ïQt|ý²j½ÀÚ˜ 0 éЖ$e?€¢¢²œì‚èÇ/ƒæl535ÐÏý=9(ƒŽá8^YQIH$GŽ_€êªêÚÈõø76àŒÑoö‚?úv³0å5_½Zëkr"‘X,–ÜÐøøøªªªÁƒSNª‰‰‰‡‡Ç³gϨPGGGj§½‰‰‰……Eaa¡¢RÚ¶mËb±žŸáÂêb8åR3Ì7nÜ(**JOO§¦µccc…BáÛ·o¯\¹ŠdáààЩS§sçÎÝ¿¿¤¤$##ãÔ©SOÞH1¬¤D‚ ¶nÝêïï?pà@[[ÛÂÂÂììl¹y*©µTqõS5MàȃGø$­;)A-EêªÚAŒö&Ñ7Öý§Í*FI«½©ÖÊÊjÞ¼y'Ož ¡(ööö”QÁ0,(((88˜Úã­««;vìØ>}ú(ϰC‡ýû÷ŒŒŒŒŒ466^·nÝàÁƒÃÂÂBCC ÇŒséÒ¥«W¯Î˜1£‘N›6íÔ©SÇŽ#Ã0‡ÊÊÊúÓÕ„,ÊJ¤ÑhçÏŸ×ÓÓ355-..¾pá‚ d'ÕZ¶¸úÎ}þq#Iô 2Bc‘ôæ)öØẨBD=LEþÞ®Hê œ_[ÑÁ¹s¿ÖÌ$ŸÏçóù<ÇãIUUUÕÔÔ6~®˜Ïç‹D¢º$UUUB¡ÐÈÈÃ0‚ ***TÝ' +**¸\®–.”•b¸1%ŠÅâ x{{=Zn%µ–-NM#áSó>IÍ^&ŠkjDL&Ëiù‡ÉÃ.?öìÚÞÆÊXû2$F ˆZ»"×´Sàp8Ô~{•rS”FkÂÖw‹¥è8Ÿ¦ªß˜?Þ®];ê¤Ü³gÏ………¢<•ÔZ‘¨›,pdà>5ˆ4¹‘ʰÝT¡P<½A¾×-×¾]c¯‘"2)5¿££¥¦˜ ü~Çñ½?|1²‡öeˆÄ¨1"|𨮮.--ŠŠ¢¦“étú€z÷î$ƒ ÌgäºäÇX:ÒÌY‹Žgç–†¥Afjß¼×¶ë‰Ä¨e$Zç.z•Àf³gÍšUYY™““ƒa˜M3<ª‹ <‚\P—´h6V.Næ.NææÜ¾ž>OÍ+à{vm—š^Ÿ0ÐÕÁÞì鋌ûÑÉ<½€nÆFHLÉOHÎåWÔ„\Œ¶²0ðòtÙh2³K"ï¾®®yõtôèlKD&¨ &$çEÞyÍå°ú|fm©Ù'¥©-ô- FÙZË£"á4AŒÚ”$hÑÇ.—KÝK A crªB¢éÞ]‹&¡ÓH`±°Àiû&ýxpÞ²Ó¡—btY´%kÎõ±ñaLÊþcw;öZÿ:@òòMfbJ^FVIð©¨w_HäFì;zÛÑsɱ3÷#î¼ôµéIlŠâÈÔFòàq¢kÿ•g/<>rúÞäY‡´Pë£ÜZËŠQ‘pš F­KC¡%<ø”””éRßÓVK$}úô¡.™j4HÏ‹V×BaBrÁüå!6V†®.VÀdТ¯/À0,æyÆÚm×"Bfù{;ÀèIûæ.;2kt€Û券¢’Êð£?@Ìó4¹Ñ’óƒžÚ³iÂ÷_{@@¬§ËT¹®‚·ï%èëÝ>?øMW™l~1*Q}1þŸ½³Ž‹*ûø™NbèÆ€Á@A)± lÝÕŸ®ÝÝ…®]k­­Ø-v êšØ Ò­0äÄ{÷÷Ç“qe¤fÜû]>ûïÜwï9çÝyçžûnj ¾aiÏŸ0#T¦%I 5sð‘‘‘ÿÔ•÷Ðàp8¿Ò~®Õ…¾¾¾³³³®:ø·oß4oŽï¢6I’¤&"¿œ.ZqŒ›ytÜÌ£à\Çâäî!,& úu÷ „.\}imiØÊï7ªÞàŽnŽ?@Èå €šŽN@iÙNž"2àîçE¥ó8 @di™¨)îd‡VÎ V^è7|×ÜIíë8˜U°ÊÊçÕV•¿c"e3––íÄÙ¨Ÿ0#T¢%5/ª°°ÐÇÇÿðËCzzú½{÷‚‚‚°)ÊÉõë×uØÁ3 —‹ï¢6óS7¨â› ™Ú®C+gS¡½¨¸  †” Gœ/2à)*Õ²d2B"-âóØÅaâ÷²efåZ˜éÑhߥejlÙÝÅüß‹ãç,=ïê·hÎÄ6s'·­P+å°™ï›ñ»Z#åÃcÔfKËÈù 3@eZ’Ðt<€Çã)Î!Åü\.—Édb3V€÷­üÁ¤Ê¬  ¦ÑbÊ4Î_ñÞÊBèQßRá“”ßr°³1HLÉ&IN€wïÓŒD|> §ÑAþ ›A\â'‰´HyJyi™i4@Há™ÌNïýß¶½÷†N:6 wÃb¯©½þûfü®Ö_ÍXZ¶Ú5Œvø3V¦%åš·w„·ö*÷3æ»ßcJ³d¥B¯l ðŸ¶ÿi UüAæ_ú‚%¿TÜÞY*•¯úç:"äqñ™ë·EöïÑúÊÂTðøYRzzN®¸ K»ºj³õ r¥Ói£¦žÈÉÎ'd²C'geå–V¦‘ˆöòË‚ü¢w1iÇN?!d2cC.H‹¤Ú~üÌøK*›‘”ËÕfû93IT®%ñ4úê€Ä‘›® TvCÀ&þ¥"x N“«è F¡¦ÌâDk Þ‘­½†N9²òªD*ïÖÑeÑôÔW#x>õÔ¢Þ" ÞÝ™ 6›¹ çü¾?MÕ a2éfÆ‚C[zú4±W›ù¯i-GÍ8kjÄólh3p|XéA˜<ÂDZ¦A…j-W¯rešñ;–T1c-{QÉl|ë'̸r^»'/*Ë’H¦©ƒÇ<ŽàÿSTâ^ô—ΟoÛ¢6±6y玗Ÿ_Ù_½{ó¯¾ô¸¹©°:‚””*Ör ô¿™7@dbŠØPŸK¥—– ’Óri–æzß/³H"/,’‰ xR‘’–k,â ì 6ûýø"‰¼•o­j ¿Ôh­bÆïXRS3@%Y2G\”" prkSöKnÞ¼éííøå!--íÎ;¥m);W¯^mÛ¶m¥VQÉ<îåýz|5A§Ól­ÔlµÍ`пÿÝl`e®W–2¹&—Ã6‹¡\r…ûY­²¤Š¿cIMÍX¹–$q#xLµ8x<Éî×sðUÆì°ÿÔËclÆ 1#vðØÁcp©˜$Çž©"<6cù‘ãIvÕèã1ÚoFÁÿ·Ñø! å@àS¼Êiv96c¹Í(Ó¹­jóó󌌌Ì̾9ëïóçÏÉÉÉ&&&%IMKKûôé“•••ò¹¨………Õ¸½j<5WŸN§æççËd2CCà ÑZew¯’›}Éåò?"„ììì*ï8]jÉJ…^©­?‚~ÉÇ*þ«ˆ?„PHã!z²š böìÙ–––nnn666ÞÞÞÏŸ?§¾š5k–••U£Flmm,X ¸äâÅ‹ 4°µµuww·°°5j•¾nÝ:;;;‰DR-Š „h4ZT4pà@’$ÍÌ̬¬¬ìííE"Q```ZZZyŠMOO÷ññQüS&“¹ºº*gعs§­­­³³³‹‹‹™™Ù;w*Ï’ºÁÓh8‚×þA"Í/©„erÿ9³ØŒå7£.mt³téÒM›6íÙ³ÇÏÏ/>>~Ê”)mÛ¶ŠŠzöìÙŠ+Ž9Ò±cÇ/^Ðh_V69s¦wïÞ}ûöݽ{·¥¥åíÛ·ãâ⨯ڷoOm'W-º bª¬.XµjÕ€Þ½{×½{÷yóæmܸñ§Ë|òäÉÇãââìììàîÝ»111ïß¿¯Y³&ìÛ·oøðá3gÎ ¦éM аåÊßÿÅf¬êÆ0¡X,^±bEHHµ…{½zõ>üÛo¿mÞ¼ÙØØX PénnnT~©T:vìØN:mÛ¶JQìýþîÝ»/^ØÛÛÿ§î4Çõë×÷õõ‹‹SöÖwïÞ500hß¾½H$€èèèððp¡PزeKKKË’)Ïž=€“'OŽ;Î;?®Y³fQQÑôéÓ8gΪüÀÀ@¶ÞèGðš^"„O.§Ù¥€ä€Š°%ÊkFáæÍ›;wV¤4oÞüúõë!!!ùùùÛ¶m2dˆâÛÈÈÈÔÔÔ‰'ª @çÌ™Ãápž>}Z}ªîW!—ËŸ€˜˜pqqÁ¾ÒDŒGð$Ýè}N«OtCl¹ò`RàÍgl‰r‘ŸWÐÐA³Ý©ÉnU/*5_Z*•*ï)“Éèt:A‹-êÛ·ïÒ¥K{ôè1iÒ¤JH„õáöíÛƒ ÊÍÍ]ºt)5ÕNñUÕCÕ[µS/੊֯_?pàÀ´´´¹sçúúúÞ¿ÿÂ… VVVþþþT†N:9ráÂ…‹/0`ÀŒ3 ‚hݺµrJ~~~tttË–-ïÞ½{âÄ ¹\îçççïï¿mÛ6¹\NÍÛ¯FÛꚃ—㕾چí˜Ëåvî]r%S |NNJJúOøŒª•šÏ]·n]Ebll¬%³³óž={–/_¾lÙ²‰'R¯Ø_¿~íêê mÛ¶MJJ²··WžàV]³«¬v’$ ©¹‡fffsæÌqrrŠˆˆ‹Å††† 1„B¡L&spp_¸paãÆ§M›6}útWWWå”Ö­[áââÒ½{÷#GŽÐéôž={Ö«WO,ÇÄÄØÚÚR·ÉÉÉ© ,Ygöhï2¹Â¢¢ÌOŸRÒÒ ‹¾yUváBRjªFEIe²cgÏ~ÊÎV[Ků߽KÏÌ,‹¨1?^ŒˆP{¿KÞr„PŽXüúª êh29þÃZñº1ËÇÇLJÏç:tH‘’œœÙ²eKål¾¾¾R©455ÕÇÇGOOoÆ ÿñœ‘‘‘JbAAÈår›¤¤$Å366V$ñùüzõê9rdÍš5‹-¢ÞŒ(§Ü¸qÃÆÆÆÀÀ sçÎ>|ðàAPP‰‰‰……Åãǽ½½ù|þöíÛV¦ƒ'Éòc*rr2uuµjÐ@èàо_¿ôŒ *½Ïˆw>Ô¨(±XÜcèÐèØX•ôµÛ¶Yº»Ëd²òȉHræ’%&..Îþþænn^;¾xýúû¢ž½|yôÌ™%ÓÛôî=h•ÄKþÁÁ?¬«ŠŽ‹(>Ëÿá¿jÿ#5EO£ÑèÕžžÞ„ Ö¯_¿oß¾ÌÌÌû÷ï÷êÕËÌÌlðàÁ«W¯þðáÇV®\inn^«V-==½ùóçïß¿„ ÑÑÑYYYÇÏËËSÈôê!TI%O:µU«Vñññׯ_ñâEÓ¦M)e?}ú”––öøñã &˜˜˜téÒE&“mذF£%&&nÞ¼¹_¿~ïß¿?uêBÈØØ˜ê¨¤¼zõÊÕÕ•N§›ššúúú6mÚÔÔÔ”N§×«WïÉ“'†††“&MÚºuë’%K’““?~ü8sæÌU«VU’²º?D_¾!ˆu  êÕëmllç?ÿœ½lÙÖe˾«QÉTæW¶lÉãpXtzyä\´n݆]»nÜЬY\bâøùó[ôìùòÚ5ScãRE¥Üji•~›¾ïøñ?ºu£PWÕŒ² ùO¬?Æ`*aŒPþSM¾zF¶§M›VPP0a„#FP1ýž={„Báýû÷W®\9oÞ<ptt=))ÉØØ˜Z´M’¤‡‡ÇÇããã95Í^!á Aƒþ÷¿ÿ%&&’$iccCMÐ#Ir̘1cÆŒ©.E¨)~•T»µµõ£G’““ ôôô¨ê222JÊmÚ´yýúurr²¾¾¾¾¾>tîܹ}ûöiiiFFF€$I•åË»wï®PdþüùŠôéÓ§Oœ8111‘Ïç[XX@¥½,×ñn ¼¯á ‚Ëd_¾ ¿sg}HÈ×ÒŠÇ–g­X±v×®.mÚÄ''O\¸0âàA×:u¶80fÞé …–&&@’ukՀ̬¬VV_»Þ4r9“ÁøÚÕËŠ÷úIž½v­H"™6t(•h –ÚûQ¢OÍȸûøññ©”×U=0Ác´ò'fÑcÏ„ü­¢§B&&M˜`ëë{52²s«V_ŠE('7Wd` ¨BÏ—Éåi™™¦¦4•ª€{÷vnÕjåöí¿wîÌf±å|/þÀ ÓI’„ü7ÎÎÍ =~¼gûö÷î571qutT.¹¦µ5¼uqtT$¾ûøÑÞÊJ¹Ì¤ÔT‘ˆËf—”ê;F;pút`@€Ç£R~\WÜ „ð))­‰àe?±Ÿ?>˼Üu„͈<üì*,5(¿xí#P8I²³´LLM% ‚ZoðîãG#ƒÚ¶¶;“’$ ‡ÍV)dûâÅA.:,Û²eΨQjäTù€‹ƒÃÆyóMŸ>pÚ4·:uNmÚ¤â¤ý7ðxûNZ2i•’”–vãþý¿&LPÕÌÈ(-337/Ošå¡¨E­ÅŠÓ÷:E•S–ºª¬ûˆÔtfS9OÛaõN²ûe<6c…P6Ôê>óÓ§ä´´ÄÔÔ«V™µðò„Œ ÎFDtô÷nÝzúÊ•«vì˜üçŸñ))ë÷îíߥKÏvíæüý÷¨ùóWMŸ.äó^¼ØÚÛ›ÃÞÒ’Ïåþ3~×Q£zuèð[êýº’ðYÙÙK·l9¾~½Ï/”H¬ÍÌT4òxS^´i“£½}GÿØ„„1 š›˜ íÙSYÔŽþþ6{ÔüùëfÏæóxÏß¾ýaÿ:66)-­M±ð?¬«ê"x<‹£-®F®é¬Ú'ÙýA£Ñ°+j,D—|ùz(3V­š±j•Ï÷óð¸¾gH(’ükܸQ šŠD+§N=²fÍйsC6lH¥ÝÚ´Y4~<ŸË=¿eË Y³D3 3cãC«V9ÕªõÅ9‘d{Ÿ.-[Ÿ;7<4Tåü×÷ßÅËÕxl¶‘A¯ñãkX[Óéô‰‰ç¶liÕ´©²s†/((ò§Dþ^½ZŸÏWõèßš5˨Iç`g§Þ8JËäöž<Ù«}{&¦œí;uUÕ Brìà1Zák4ݪ‹Ú(®<Ðét’$±ËOÌc U^'âÒ±cm+£ä"‰¤P"éëS]ò¤ôt}À@OO9Orz:F³45­ÀzÛRÓÆfó¼y%¿*(*JLM5‰Œ ¾#jjf¦‘—Ã)¥ÕõD>~ìÕ»·òßçÝÛçúÜ,s3cüãÄT;9â¼”,Ž“sò_ráÂ///lºò‘‘ñàÁƒ:`S”“[·nuêÔI—#øÊé=pÙlÅ»p:fK}òm]V”k/ŸéŸ>µ2¤wûöεk¿ùðáΓ'¿©-“Ïáüfo_²FQ+DªÒꪒD$Ç“ì0Z’biØÞžVîgžd§3Tò$;O£Çåö :¾ãÄ 3³Í³g÷ëÐ~¥—O?3DOàerí€Ðt}TTTzz:6\yÈÉÉa³ÙÇǦ('œò åjA¯ã3-y,ÖÄ~ý&öë÷ËhT7Ï¢ÇhK,Ij:ekkëããƒ-WÒÒÒ¢££}}}±)ÊÉÇu<‚Çüj>O²Ãh·ÃZµjÕ¢¦Üb~@’’‚ÍX~bccuÜÁ—#Þý,'ed˜ŠDæ%Žþ>R™ìô-š41Ò×/øIª}Ϥ¼‘œîÇ@?±U- H†èårâC\ BÈÞÖ‚Ã)ë›Ú˜÷I1±IíZ7ùùfC¨6&S7ŒT*;}þv ÿ†F"}i½‹ßÁWÄ3a3ê •5uâßGlØàZ«ÖÖS§Æ¬^í]¯ž¾@0{Ó¦+ëÖÕ°°øÒ' ˆA ¼‰‹»µiÄÖS§Æÿýw‹F¤rùè+¶Í˜ñG»v/cb¢ãã¥2Yè™3Mœ½ÕŽêSÌô™=ÛÇÝ='/OÈçwó÷Gr¹çÀ|.×ÔÐpÚ† ]üü.X ‹;L˜Ð¼aC“™“—7aÍš+ëÖ4lx÷Å ÿ‘#›Õ«G§Ñö_¼x`þü3fX™˜x¹ºÆ§¦ŽZ¾|×ìÙ´kWš¦*µwø±äe¹AïV«Õ[ÕÞ¼ý43K4"n>8bUZ̾Y v•T\Y¤n¼¾ÈŒ@òA£V½‰N¼uq™VoKŒä@Ó,„À¡g…Dðx ¤-©Ëþ§ðuwŸÔ§ÏÈ•+wœ93gàÀN¾¾ðè͛Żw_Y»¶UãÆÐuúô k×n˜4i䊛¦NÒ©J$<'3;›*gQh訨û;vx¼w #W¬8»re;//ØtâÄèU«z´hÑÕßÿÜ;™ÙÙ'—-+£x,&óþŽŠ]¯oÜHí´s&2²ÓÔ©+Fæ²Ùð¿tèÞÆí:{6 aÃë…×7nq~¾T&€}óç4l36m½jU÷€€W>”ÔôÊÚµ%kŠŽÖHrõh:D¯ÝëàßÅ&@=gÛ’B>z»xÕ‘+'CZ5w€®ý–L˜±íèî©¿]5m|ð¼é½ d顽‡¯ïb“GNÚtöðìv­À¦GOÙì^Ïnä¤M›V2  Iy\vÉŠ†Œ]?dìz073LýÚrXŒûáË©{wýÜ_¶Ö&pæâƒN½­X8ÀÆÊ€@Üá÷^þR©ÜÆyG‡õˇ@³6ÓB\±³1*)U.^}ºû´ì4'5-ÓÂ\´e×…·_|ŒO©agvðØõÀv£cJ*~ådˆŠH™YbªÓ·hå¡‘/îG¬ðYÚ½ç©iσ/?ø¸XÁƒ"†þ¹KWŽ9 ]»…¡¡§M›þûïK† »p玵©i«† ©2ƒýüþ\ºôDD„HOopñæ3<&âËéïׯ/?p`û´iÖFF@aׯsÙ쇯^=|õ ròóÅùù#g¾¿'Ï·úµnMSzõ`$þ}ðàÝ—/©£RRmm Ž u‰[íÚ±II@<=ìÜÙoÞ¼¹ÿû_;»L‰ä«Ìvè°tïÞ'oÞ\{ô¨¤¦„LÆ ÓUkÿ¡äe¹Gõ"@ Å£T§˜N‡’B^¸òÈÚÒ¸Us7ê«à ¯?Çl8}þ~‘D:m|0•h`À§Š ;û/—Ã~ó0*rÄâÜ‚ÝÂE†ÂÁý[Q™y\–ZS,œÕ·{çfÀdÒ•3ôëáG£}ÌH$ø{Óé»÷ß’$€„Ä +#ê+‡ZˆÍf‰ôìmM¨D׺v)iŸÕJõþcª_3gKs£gî¶jî~÷Á›VÍÝ7X`fŸgþݹq´ZÅ©ÃB”E¢þòܽåkö¯emiÚ>Ž4oïø´ò?×IlFìàh´ò,…¯W³æ‘¿j×^¸{÷ô~ýròòDBá×Óßy<™\žöé“…‘‘úÓßOœèìã³òàÁß[·f³XŸ? y<Å 7c}ý%ÆYs”Ü}—ÅR|Î+,l:|¸P8¦[7©LvìúuB1è­8]žF£N—w¯]ûßÍ›çìØáÚ¿ÿœFR/ г …Td¯VS‰DÂçrUj/«äßWJÓž8’’jmƒ¶·ÀÛwëØ¨|•#ÎòÂë Y2Ÿ˜bb¤Ïå /éˆ@€¤™Ÿ…B“ùŶÆF¼%óú$§|¶03 ìûžÅÂLÏɱø%[q94êŸyùEM[Ï6ÐçÚN*“;u‡ $€¤Å{+,LÍxŽIª•ÊÊBH§Éz7=vêöûɽº66°U§>˺Ù!„:´ªwûß—%—Hò•Eúrg6n;ß¹ƒÇÊua¿÷hÊf3µúé…¤Ú¿çÒçÏŸ“““MLLÌ©µËLaa!ÇÓN¥ªñ¤™´´´OŸ>YYY”á$m¶!èüq±?;‹^™æ ÌÙ¾=%+ËÎÂ"1#ƒDèËéïIIFúúµ­­wž;'‘Ë9,Ö7 €íÓ¦y{»üñDzæüïöÉøž=¹ÊçÄ8$ùcQ•'ç>zýzRfæýmÛxNv^Þ7ß*(þ¿»£ãé¥K·93tùò jG­âloâãÀÎÂB­¦|E3Uª½¬’—E)Â&-~ýæ×Ô‰ÏãlÚqyý²*_ÙY'&" ’šÑö.6ÅH$´¶0JËÈÎÍ-Ðò”ûLö6&ÒñÃ;p•ÖЯßz1ôÀ I‘ôG ëÑ÷Ï>v7)åÓýk‹x\vvNþ×~žêùÅÊÝ8P/•§Op³µ›Ï?yþñjØì†î5kØ™Žžº³[P6‹¡Vq>—­Òs¥>l_7,¨]C—¦“—ý}jΔ`ívðHÓ­j©³Ì«LÀ9sæ¬^½šªtöìÙ³gÏ.ã…6lX¸pabb"‹ÅÒ>«WÏyð—/_ž1cÆË—/€Á` 4hýúõ:jêëŠUnñrùOüåŠÅKv‹‹‰‹[¼g…‘Q-só`oo©L¶êÀ$“Å%%­?v¬›6=ýüè4Ú¨•+srr©ôÐåËYŸ>\ö¦¦|&óŸñãíÙýñcïæÍY ÆÈ•+Åb1!•žºq#-#ƒªÎB$züömzff®XLÊdjD¢¸Ôg ÅWL‚ òrsI™l÷¹sPPP š—Ëß}üxìÚ5B*5 @VT¯Þ¿¹ücbâ¤õë›89Õµ¶V«©ÚÚ,ùÿ~bxIµùÏ@9}|àÆí—ç/=œ˜û>qâ¬ÐÅ«’6Je«6œB¤$.>yýÖ ý{ywlãÊa³FMÞž-•<õ‘Šà{wõ`±è#'m‹syÑ©óÿ¦¥gôìÒˆN§š²=''›:~3+듪 €ÉÕȦ”Îd"‚ órsIB²û`ø—fó%[ñ‰JQ@ µRQ<êÛÔ²7s®cÕÐÍtìÐÖ™â>Ýš”¦¸zQìm ø\Ú?+,Z}":&^Ëo·6÷5ÃÃÃW¬XqèС¼¼¼{÷îuîܹì×vèÐañâÅÿeϤ™3gºtéÒ AƒG%''‡s~Ù²AË–‰‚‚˜ †™¡á¡¹s¨ÓÖ ½§gŸá«W‡¯^}aùòK–ˆétzMKË]Ó¦™‹D0²sçÃÁÁ4€wû÷ײ´,»¨=š7½xѶgO—Ô¬Y{OÏNžÜ>eŠÚÌObb.[ÖgáB˜Ü«W-++X°{÷ˆÕ«¥r¹—³óÁ9s@­¦j ,ä?Ý}×þuÒ³'v$ bÕ?B–‡€s«õKDX[èÙ9rè„Ðåa©¬[Ç¢YÁ|ûèΑƒÆî4ª=BÀg;Ô4€#þ…ÃŒÚ.ª5œN§Õ´3ݵþOoOÇó‡& »CTk“I73Ñ?´m„—£Š…!5&B_—˜÷èÔ(ôÀMÛzãNPÛúí[¹ý³ãJ›æu¿ 8µ0úºf!@H­Tæ&Bª†>Ý<]êXQù{uöXóÏÅï:¥)þe™òÝTª½}K—.Ÿ¸+üäT-ŽàImžEÿæÍ@nnn ‘HÎ;× Aƒ›7oJ¥Ò€€€ÚµkS™OŸ>íááñáǧOŸ:88äççÛÙÙ!„¤RiDDD«V­Î;—˜˜èããCr¹üüùóÉÉÉîîî·nÝêÝ»·Ò£¯R#x¨ÚYôR©t̘1:uÚ¶m•¤!??ÿòåË­ZµÒÓӀׯ_§¥¥Y[[¿xñ‚²!uIbbbxxxAAA³fÍ6Œ½ví‹Å ¨Q£Æ¯çà+ó<øÚþ¬Ë‘ÉåSS¹l¶­™Ù7/-JÊÈÐ åôä¬,€¥ñÏ)OÎÊb1¦††Ê‰I&fd …*Å–‘¤ÌL}>_Ï€O¹¹FßžLÿMK•ËS²²Œõõ…<^fNŽi×®w7l¨aaÁd0L¾}¥Tš¦*”SòÈçϽFŒ`–¹“ûîÍC}¸mnª[™J¥òø¤O>ÇÒü[Ã’()å³¾Ï@Ÿ§œ˜šžc$pKŒ½'§f³X Sc=•D¦R²ÆÍ&å³¾OOÈ€OŸóDÜAµRåH¸ƒñeXNœ[¨¯Çû¾â:Mޏ0%ÏÙ©^ó²_ѬY³ªïöíÛ-[¶\¿~ýâ8³²²¬­­---===ž58¯Ú`Ìù% Q›¨q³±( 12diTšZ<€\1P_ÈPѱ¤âºæŠTe߬Y³qãÆ;v×®]3fÌ ¤ªÞµk—¿¿?Ì™3güøñ]ºt¡&‚±X¬[·nQËÏH’ܵk—BÚ?þøã÷߀€€€Ý»wûùù>}úÁƒÑÑÑaaa}ûö•H$U£BˆF£UeM‚P•fggS)öööæææŠå=zôHJJ¢l=vìØuëÖ 4ŠgÞ½{÷nìØ±'NœhÓ¦ lݺuüøñ]»vår¹¿R¯½‡Íüò0h4{ss“YVÒ¸jRË—ÉaþKhB$IU÷‚iÑ¢E}ûö]ºti=&Mš4vìX`³Ù” ýû÷_¹reTT”§§'ôìÙS1s$I„ATÎÚµkS\]]ß¿ODFF†žžž©©)AŽŽŽT`mccSJAÉVef¤êRTzûöíAƒåææ.]ºtÔ¨Q”Ñw–róA(lxêÔ)CCÃþýûS(ûŸ|ø:³U,‹ÅâØØX''§ªk¾ÿÍnþ#ˆ„ÂûöU¿/“Óêì0ÿ%ÿ.ÿ‰¾fïÐâêêºoß¾eË–-]º”Š ›í@^^õO.—KSZ £œSñÁ`$I£Ñ|}}srröïß¼uëV333—ªQ­ê7º¡ÞŽ¿}ûÖÕÕÚ·oŸ’’bkk«,†ÊFʦËÊÊ277WYÚ—™™)SðŒ,X`eeõ‹màSÉ­ZµjÿþýB¡°°°ÐÒÒ²Êôªúwð`þüù“&Mâr¹Ã‡766¾qãF^^%Œ¹¹9ŸÏ?zôhݺuŸ={¶wï^333e‹/X°`„ K–,aaa-Z´èÞ½û_ý5~üøåË—óùü .4iÒÄìÛ9Ý8‚ǼîGðÞT e@J±å0ZÐz¥Ú|ü«W¯V­Z5þ|ptt<|ø05 ¼téÒñãÇK¥ÒƇ††*;õÒ¼J¿!ÄápD"Ñ€ìììètz\\ܱcǪ,î¬â ~èС cñâÅÛ·o>ŸHÍ[äp8K–,™:uêš5k\\\|||¢££•¼©©é‰'FŒammÍd2MMMCCC›6m6tèPkkk:noo¿yófSSÓ_ì'R™Ëäöìi[†uk˜j$òÕ+¯ñã5Y&w__fn*ĦÃT;9⢔"?'·Ö<”.]òòòª2 e2Y||<—˵¶¶€¬¬¬Úµk_¹rÅÎÎŽÉdWÜã188ØÞÞ~Íš5U TzzúãÇÛµkWñ™˜˜H’¤ “ùMtZXX˜ýý…‚©©©`aa¡’Èd2MLLª^[·nQÛ$èlÑ>ž¦§ÉÉð$;Œ6 ÿ©ö^u³¨Øl¶ƒƒƒJÕ4MÅÇü]ºtéÞ½{:u¢££ïݻ׫W¯*›dGÒWýýf0öööj¿âóù|>ÿû—«uÿU³y@uQÉ^&Ã!í~BÊ5?iÿ ˜ÿhÖ«÷¸X&“ikkËápÊ/ƒžž^ß¾}Ïž=»gÏkkëµk×öìÙ³ª"‚jsðmrð8ˆ×G¤æÞ;xŒV@©KOCCCꬔòÃãñF=zôhÜ0Õçàq/OËQ:›®ìQ?¢Çh·C‚ ärÜz资 6côOuþ¸XÜ´þǪY <‹£%H)Ð4[§S-çœþ’n ›Gð8‚×…^³üø F›@ø SVÇï^±ƒÇ{ÑëDo\Ã{ Etl9Œ ñ:xƒAm|†ùièt:FÃfÄ<žd§]q#xDÃaFkÂwí=þ׎à±±ƒ¼“Ý/ÁSÇÅâÎ;FüŒÆ¼\.—áµ»åƒ2 6c…ô“tØÁËe²È¸8|µ™È·o5ÚÖ«HRôüA’™1›SíääJíêi6÷Þ½{8ô,'™™™………ÿþû/6E9ÉÈȨì**q«Z™T*ǽ<­ïBò…BMò“r™Û £%0YMƒ!x‡–ò?4° +:®|ÀŽ9x ƒÁ`0ÕÖ‡À&À`0 ;x ƒÁ`0ØÁc0 ƒÁƒÁ`0 vð ƒÁ`°ƒÇ`0 ;x ƒÁ`0ØÁŸ0Ož IDATc0 ƒÁƒÁ`0 vð ƒÁ`°ƒÇ`0 ;x ƒÁ`0ØÁc0 ƒÁƒÁ`0 vð ƒÁ`°ƒÇ`0 £fåûùóglb ƒÁ`TàóùÎÎκêàß¼yÝ´©¾‹ ƒÁ¨p+2R‡<ƒI70⻈Á`0Œ <.§²«¨D!ỈÁ`0Œª‡B—< aÁ`0LIOê°ƒG@"ìà1 ƒ)é"‘.GðØÁc0 óK:xD‚ßE ƒÁ`J¸H~IHñ]Ä`0 ¦„ƒ×åwð€H’†#x ƒÁ`JºHÝžEO"„<ƒÁ`0%ü;ÒéYô‰'Ùa0 SÂEêø:x’¤aÁ`0LI©ã³èQå+€Á`0ŒîEð4¤Ó<"žEÑI‚D蛟“ɨ²Ú‹ %\G*•_:ÛÇ¿¡H¤§’áü™Èœ,­L´Y’Dt:­´þï“>Ä&µhݤ´ ƒÑ>_ésÔ*ÕÁx’FG±7ï(•|ó‚)M|ù;žì}l’ƒ£M…T½mSØòE{^}8š+Îÿóó×Ö6j\W%ÏÐ ÿÙ6=¨‹o…뢩 /Mñ¬Ìœ¾Ýg_º¾^ÑÉðñøónÔ®²~ùÂí[Nß{ZZŒ€Áh¤ŽoU ø°Œî2vR϶<•Ús©yÆ”R“³BΩz[µkÄá2™,„@ä¥T-/ûï«ìºhÄwþüí“Ço’llÍàÁ½—ïc“>~L°¯aQæ ðëäø!ƒÑÕ^·w²C‰gÑct;{Ój+E«²ÏÞ§§e·hÝJ ¿òØÒʈÃaÇD'äåž»an.jìU>¾O¹ñ”Åbøø»ÙÙ›€L*¿u㙋ú—/ÜOIÊòòvqv­±ï’n^*rýê›[½I~õò£­1IʨŸOVæçý»/ÐhТu#3sÑWy”~_%«û¡.×.?2·¹ºÕ¢R=x+“ɽš¹”,­4ÉßÇ$—Tü«ƒúΜ¼9lTg¸tþ.D=zckg\œ!öá½7zú‚Vm= E_Ï•NJ̸vù‡ÃÊÉ JÇÒ$ñC£Ó1¼ŽGðøø›ŠM'YßÄËéÕËø9Ó¶‡šÖÌ×E)x•€Úê~¨Kĵ‡w#_]½½‚üÇÒ±“‚=›9–,­Eë%%oæëòæªâÊå¿|+pÏžº=tT{¸|ñ¾@À}õ6¨kcX¶ðàöMçÛ6IJÈœ?kÇѳóêÚÀµK‡Xí\ÏÞØX?âÚkÒï*(ÇŒ®ºw]ßè†Äïà1:Ë”±[¦ŒÝ-Û4=<ëXN™Ùcú„m¦fz3&nû{óH+‘•èꥇŸ²rw쟱1‰3'm=<¥yKwØ»óê¬);:viLýzôõíÑǺ¶h_¸C+}}þ‘³³ /·Dò `Ï䤌ƒ{#H$§.Ù´kœg3'‚ ÇÝ8fèú»O×2YŒ/Á+’ˆMU[‡Ãú¾.ýÿlµkëŧOÞÕs¯~5ª @Ò­·Zá#î­()¹—O¶*+®òcñìàam7­;›’’QX ýø>uèèOÅHþüɇu«Â„Íômî ƒ_=Æ®a3Å9£‡®9>h´n°fÙñã‡#K³'¥ eÜV18‚¯jOC¨ vêÁ`*‰É3»wìÜø®¢%ÕþÒù‡]ÚÍÿý-Úthø%ïKuáì}‡õôqìÓDZ+.ÌË-Œûjl¢µ,¨lN.¶qÒ†Œjÿ÷²c†l7µkmKê+Dý‡HêŸL!’N‡Ñ;µñ™ñâù÷Ô¸:Bˆ,­:Ç:Öß×¥–ƒ¹·ŸËÑ7\ÝìíèÕÏŸÏg«--!.½¤ä%WF"‘½IñkQïáýès§îÑÔ§®·ŸËÞ×H’¿ea)òñw¦.lè1yì6¹\~åâ#I‘lĸ@*]O÷{+ˆ2Ý#Ôñóàñ29ŒîþúLÌ„5¾,ÁúÚ’iàßÒåá½è6ë+}iíY™Ù|‡Q¼ ÍPÄ›6§»©¹@.—B2*ŽH’tr±8yyöª%a­›M3¹Ó¸)!"‘”Dß\"2æ@^^‰¤ˆDrIK«îÛŸžz] ˜:v×ÐÑm¯<¹zgQi¥™˜ñKJN}VV\™W/?YÇÙ"¨kã“Çÿ¥Óè»{Öu±Ì¼M‹ó ùŠ«øB¦\FI R’3ŒŒ…,6R€¾«à#àÆŠÑM¯ÛCôðq±†,ـ߼Lܰêl›õÇÛzîúlS} ÑITfk[Qa¡tЈ•AòOYy@—‰¨òëºZnß?òàž[3&ìíÞÛÓÚÖ¸xàN^œóË%qRÀÎ^ § !@^Zu%$W£K‹6.|gÌÍ~.v5D¥•Všä*ŠãàŸ´´6Ò7`· ª?æÐþÙ5ÔȘgfnð,꽕aJòg’”QËâ?ĦŠ<ÝÄT‘!ÎÏ˹Å5¢ï(¨0n©tð:½="ðWŒÎö®?¼O¹w÷5õ/ƒÞÀ£¦D";l{מM®ì= Ç†Qƒ¶ì=1†Á › #®6/ŸÇ99[¤Ô@ÄöjæH¤ˆMR'ë§Qïl±,äÄÖ j™œø9t[xמMRêßʉÍfΞ²oîâ<ûõË„ÐwTÇcã‹ÑÁB··ª%«àSIlYwe˺+Ôg=}^Tì²e!'óóŠf,èB££Õ›ûú/]¶àäŒ.ýùœ;ùÈÓy&×îÏÝqhÄÔÑû8L¡Ñi¶vÆËÖ÷36 ê}5 êG W/â§ŽÙ?Nº ja_˘ZüMeC€DF‚Ó'.žFÈIoÿ:«6ýA]>afÇùS f„tQ[Ýu¡>÷øÝëüé¨fþŽT±†Fü’¥Õr0/)9õYEq[û/Kà^¿Hlܬ6•§cpC™” >×uµz|ÿƒ™¥þºgM<´vÅy©TÞ.°þÄYF&‚ ;M»¿¡ãTŸm_Ó¤4‘(•€›+F÷ü;­Ò_ÀQýý“èó§|caFš˜Íaò”¿•HäE…2Eb«+I^n‘P«’XöÒJ*^RAˆÍf–Ô.-%G¨ÇU¹$Qfz®ˆÏá0(’Š0âAä§>]ÿÒ]¿ÁµI¾‹ ƒÁ¨ðèNNß®K*µŠÊ]~Á`0Œ*ˆÔñYôØÁc0 £6Öa€Dx ƒÁ`0j\¤NÏ¢'>è ƒÁ`05.R÷÷¢ÇËä0 ƒ)Á£Ê®‚Y¹âãs 0 ƒQã!u<‚Ç“ì0 ƒQïâuÚÁã“1 ƒQãÞ‘.;x$‰#x ƒÁ`Ô8xºN;x„ÞªƒÁ`0˜’>²ÒIªlgÑc0 £ ©ëïà $ÁwƒÁ`0˜0tØÁsY–‘ç9øb0 £‚±ÈN‡< ,ö݈ï"ƒÁ`0*DÞŠÔaÏ`Ò „ø.b0 £[é#Ü•|šÞ‹ƒÁ`0˜’² ;Ù‰Åâ„„„üü|‹eeeenn^é!”ššŠ²²²ú¾øx«Z ƒÁ`4uðiii‡~õê•ò~8VVVÁÁÁõêÕ«,½sçÎÏŸ?s8œuëÖ@nnn^^ž¥¥eIé ìà1 ƒQ*—ºŒöš9xÓ§OoÚ´Éßß²²²^¾|yüøñ&Mšp8%—ô‘$àƒÁ`0˜þJuðöööW¯^­_¿>‹ÅRù6;;;55µŒ“ìhšI›˜˜¸iÓ¦ÌÌLEŠ‹‹ËСCK¼€‡³ç{8່Á`0Œ ·ÂŸuê8PíW±±±—/_îß¿¿@ Pí ôúõë5jðùü vðÔL:‚ ^¿~’’B§ÓkÖ¬Y«V-µ™Ïž;Ô,ÀßE ƒÁ`TˆŒxÙ©ãàRã{„bccãããår¹‰‰‰‹‹‹ºaò Ùýµk×^¼x1uêTWWWWW×? „|1 ƒ)áÂK]ŸýÏ?ÿÄÅÅ)R„BáàÁƒëÖ­[‰žÃá0 VFùñ29LµC$NS4Z„ALæ÷j,*”pyUtâù3‘ 9YZ™¨ýV.'âãRB¶¶ælKÛl[Q†ª¨rrrò ”οI ‹$,S à)g#It: ÿ:0ÕYú:øÐÐÐüüü¡C‡Ö¨QƒÉd¦¦¦^¼xqÓ¦M ,044¬,ߤI“ðððèèèß~ûíÇî/“ÃT7öæKVŽê7 =õÏ gï ì›rR塯`Û¦°‹ö¾üp„ÅbVxCþõ϶i]|K~u`ÏÅ¿æíü”•\çèé¥=µÇ°?g(’Db“j;ÚT¸Áß¾Ž[²k÷¡ùŠ”Ú6¤èë ü[6š5Pš–УótK+“u›'ã_¦z£µ©ùùù¯_¿ž6mšâõ·ƒƒÃܹs£¢¢Ê8½îg|jjª±±ñêÕ« ”¿2dˆš¼L£ D|mŠˆ„ä¥5ÎVmq¹L&³êZ/¢d]G\›8zÍÄi}þ؞ɤ?zð¶ž›½Vý ~ÎP3'oJMÉÚu`v…|ÏÎ3×.ßÏHÏ01ýâLžÑ·SWßwÑ ËþÚ×µýäŸlcsX€H?0Õþ\R›^XX&&ߌê1 ssó¼¼<ªÐÌÁRÛÎççççççÿè±…ÿ„0ZÒSþÚåH&“ [7žù·¨ùÂýä¤,/o×ïc’_½ühkk Hvíò#s ‘«Û—Nô£Ñ2™Ì«™ |xŸr3â)“Åðõw³³7€ gÿmÐÈ1îcÚ‹gZµõ°¯aû.éæõg!×/ÀÝÂÂ>e‰#®F}þœçXÇÆ×ßíë1’«üR$E²Ù;úõo=eFO*¥mû†”Øðüéû÷Þèëó[µõ0 @&•ß¾õÜÛÏíì©;âœ|_·µ,¯^~˜ŸáåíììR㇠  (üÊãæ-…<ˆ~“žžíéU·¤•@ÙP”„ÉI™7¯?-,6ñrr©WS­¾ïc’cß%äæœ=yÃÜܨ±—SÉrT´“IåjP¡¨HzôP¸‘±^ØÑð!#‚é–†Ž¿Y8þfaj¢×©ÝŒgOÞz4©€‘øé„©fêg¸r¹Ü7n}mÉYYY±±±^^^•èàÝÝÝÝÝÝË,=IâŸF;zÊŠ¦H"H$Ëôë±°© ‹Å‹ æÍÜy(lNFFö’lëæý¿Ã¯>º{ûÕÕÈ@äŸ,;)¸IÓßö…^7#ÔÛÏU&“Ïœ²mÅÚaÝ{ù ÿsu/§\q_ÀíЩñƒû/ƒ;ÎkܤN;~äúÁ³BZNåñØF&úÍ‹n×±É?;Æ•âÎí§Ÿ²Ä jUò´láÁí›Ï·ëØ$)1sÞ¬GÏÌwªk›#ÎíÛ}aƒFFÆúqRgOßîæ^‹ËcHæÎØqàø,g×ßÏàã_/5%cÈ€7î¯qp´€Sa·®^z´ÿج’Vjæëòôi´ÂP°/ôêìi;{ÖÑÓã/ýkÿ¡°Ùnõk•Ô÷õë±1I2™üÐþk 94ò¬­RNIíÌÌ Õ  b–S'nš˜êÿ> Õ¡ý×þޮ䭧1H`±i$’!@øé„ÑÚžÉdvèÐáĉ¯^½rttd³Ù™™™Ož<‰D 6¬Dÿm—¹ˆÉdªl[«">~ÑŽž2©hŠè‹ƒ—S)=úøöèã]ÛÍ?´?üïM#’“2î‰ ‘¼ÿàV»¶]|úä]=÷šáW£ $Ýz{ÇÆ$Μ¼=ôДæ-Ý`ïΫ³¦ìèØ¹10™ô3WP³ù××ç93òr ©ºŽœ™mem W.>Ôwå¬},­Œ€,1[å}lÔ©k¥’þüɇu«Ã„Íôõw€Á¬ž?c×°™$’#„ nÜÓG&•7víÖ æÂeÿ€.mç>1oÑßÏÐ̯nq×ç‹0HH­•¼|êuõT*6&eæäí‹W êÛ¿Ls¹lDI}ÛvlxõÒÃOŸrwì›DÝårÔj·aûµ¨Üâ}¡WºtkÖ.ÐcÁœ½/žÇ:»~Y [PPXXTû.9dÖn K£b“"ütÂhÁÈb)´mÛV(^½zõÒ¥KÀãñ4hü=‡[!>777,,,**ª  €F£YZZ¶nݺY³f¥~HDµ3"j×6óñs>zàF=7»C{#z÷óðYÏÞçpXÏ¢bŸEÅ€X\—[ÿ!uíÞ”$5êÖ¢•ÛßËOŒºaü”.µ,©* yÛ7{ü †šÅœ˜aiiPB¼/}c ÑH•1¼ˆ«Q–"_¿ºTþö“Çn#ä2êŸ5jš"X,š¡¡ÀÆÆ˜J¬S×&=-»leË"A©VPêÒÙû†‚>¿ûQé\ãGú¢oô-.G½v„¬TЉ~“ôð~ôš†ÚÚ¹ºÙ;xcî_ý¨¢çÍØ3oÆp¬c½cßx&¾Üb0˜êx0}ç[oooooo™LF‡Ã)óâµr8x™L¶jÕªììlwww©T½{÷î¼¼¼6mÚ¨ÅËä0Õ hÉM±8<•Q#´Š¯ht I‚DR*^áÙpÀÔq¡CG·¿òäÚÝ¿H$ÍÌüÌpèŒ/¿LCoÚœn¦æ@ÀæÐµ8¹Xœº$I¢ ¤ÅydÅy(Ç.i%*e¨¬¬lS3}2åM³JÓ©²€VQŽZí$’ÂÒP°7ôŠc+:ˆKnÒÔñÄÑ;Óçuc2é€`â´Î­ÝŒõ¬m XrR¡>S}þÇ]L‹Ur·ÚÊrðQQQŸ?ž;w®±±±"ñÔ©SçÎkÙ²%ƒÁøöÁŠH ñ]ÄT/!7)ù“¢)¦$g1Y 6—YX(Èâ¯õO$õÚÔã 8c†nñ p±±7&´¶5*,”Þ’SbU:ú¶Á×q±Þ¶ô¡½·fLØÜ»é[oRS>Ÿ¼2‹Ëe‰s ùi4‰H•_Jã¦<{Ï®ˆ¥}¾uüF)ÉŸå$AMÐûð>ÕP$àð˜Eßê¨ø3*þç÷3@Ò詌J'HRÝ…HaÅWV6F‰ YER)›ýõyröÔ}µú 䡬¯r9j´ã2K€¢¨HvâÈ]“Þ­ã*%+Sqíi˶î`faàZßNåªütÂT³ƒ/} )$$Dmz—.]Ê> ~b™\íÚµ•½;4oÞüüùóÙÙÙ*éHÜGÆT;~-œvn¾âìjááUëÕó¤kδvš„„"*¤#QQqI’¨ˆDr’J¤Ñ¡ïïÞsl4•Ò±«Ûše§fOÞ3gQ7ŸqùE}š&¦z@‚ŒÊßg¼~™Ô¦ƒ›!$Ò:ƒ 2//‡É;tò òHTd(â_½åßú7ïëñP=Úðq­ÿ^vÞPÄéÙ¯©LFìÝqSd,ì֫ɲÇ·mŸ!ûðìù Ü'±ÿl¦ñÔ•nîJnÍØØõ{S³ŸÒÙè ¾4q»ŒgúgŽà½¼Œ>º«ÉËË ”ÉdVÁËåòòòr–e~eEEEQ|œMýí¿7êÞ½ú/'B(ŠêÿTÐ{ŽgAÇÝFŠÃõÒûƒŽKô]wÜ ½2åöàÏ­qt–nÙ5}Þ_ö ˜O ¨v¾.«?~ÞÙMf˜\»zkÁ¬Ô·´:xu擾UÞûvy"$A&Ç í: &ø‹mß?ñdÀìø§—Îßëìb·l¤aµg̉aXfËgß&­Í€€Îê%«Æ¸y*’¶¼´hÎîÖfhµºØ=f/ŠåÛn€Î='ˆ t" ¿|äòøý›>ÎêìÙ×ÿæoåæZéA˜tÎn²ä]¯Å½¹«gÀ;¡ÀÅU±aó‹±#Cx÷wÒ+}ÈíÝeEAÖ¹EíÚ»èóáÝ»¦FÚ\8©;~ŒŠtq·×¯Œ}¶Çú÷WWׂÁn¿´â\—èoÇšý Éô¾27nÜØ±c‡§§ç#•ðh“ÍTWW'$$tîÜyèСjµZ§Ó¤¥¥¹»»¿õÖ[F‰÷ú,¤w=DôOPSÓXyWãâªpt²Ômë4M ãÉËKk…";g¹¹­hš)/«U©äöò?†æe%5 ©\!€š{ \eš›uMM´££Œ7“;E÷ìíEnJƒ—RVZ£PH”Ò6o¨ÆFºö^ƒ‡§c+¶-/­¥(0¬*ïþ2 [ZR£TÊxëoÕ½CèŸ#çÔ½çG¿gyúµk×öìÙsРAÖÁ«TªéÓ§oݺuýúõú•~~~S¦ðÍyG±–\D€Ð_@é(V:º€e¶på 2ÝÊM-o97¡¼|”FiÜ=ú5J' ÷D,¡Ä1oVBøvp2Ê„€ÚË¡uûò§¤2T¦h]Φm»¿;ž–ùkö¡ÐþQ®!„0 ÓÜÜlÅ<§©©éÚµkB¡Ð××7 €÷ þ}‡’ºö®Æ£ˆBùéÇúIcÖ´àæÍ›……… ÃxzzÛÙÙq3¶·ñ¾¡¡áÖ­[AAA\ —J¥áááÜ¿êëë?ÿüóÁƒûûûó¼å`ñ=8B!Ä7†7?ŠÞ´iÓµk×ôk\]]g̘áããóHXàsrrRSSW­Ze:QX,®®®Þ½{÷Â… ã;Eþ!„Ó!°Ùø˜šššŸŸ?iÒ¤.]º$&&N:õĉIII‰‰‰m?‚/**R«Õ¼ÓЊD¢Aƒ%''k4‡‡jϲ,‹?DA!„L¼™«Lš››Ï;7yòdý-b}||^ýõ… æääDGG·q€§iZ,›û/7olMMQ€ @@ð("„B&#xþø¨ÑhX– 2K{{{WUU=RxggçÜÜ\s_ï€R©4©>Ã08‚G!„LGðüÑ+ Š¢êêêœõ+u:Ý;w"""Ú>ÀGDDdddlß¾}êÔ©F÷Å-,,ÌÈÈðóó3 ðà|M!„O€ç'•J;vì˜=qâDnÍõë×srr´ZmhhhÛxOOϱciº–²IDATÇîÙ³'!!!**Ê××W"‘h4šëׯŸ;wN,Oš4‰¯ö„¥0À#„B&!’˜ nòäÉ …B¿¸sçN•J5sæLãïÁÛ$ÀÀ AƒÜÝÝÓÒÒ233õ+)Š ?~¼™ûç1„¥ñ("„B–Ç_ÃjµÚðñmà $$$$$¤´´´¤¤D«ÕÊår___ž¯Þ >`þL!„2ÁZ&ž±V€ç¨ÕjµZmaõšñ "„B¦cà¿í#‚6©?‹#x„BˆglõoÅoGœ¿O—áQD!„Œ(6àíÅí'}"B!däÌ™³¶<‚Ú©=Ýð("„BFrð@XBðgr!„I„«Ï¶jÝ‹ìÞÉ!„â ðV¿]hÍÚGð!„ÏØ–GðX ð!„п-À°0À#„B¦c`Áã½èB!¾¼-àEv!„)Ûð,‹#x„Bˆgoõ°•ïE#x„Bˆ'ÀÛöÏäXÂjñ("„BÆ(›¾Èް8‚G!„þm#x çƒGÓÃÑz”¹‚À41WÛªÊ{);ŽQ<58ÜÝCõÇ™HØÍ”»‡SÇuÇ5!ìıËòòn‹EŸ¯ú´sÓçs§¸â‡—š#£‚»vïÀ­×éè#‡²ËJ«>ÚÁßË4g©T$“‰º…øõ‰îzû÷2BÞvS«ó~+ªÓ4¦øÁÃCÕ+*ØÂÊ›æßÐÐôíñÜ1= üzãvyyutÿŸ¯>øƒJ¥øþÛÜÈ¨àŠ»5†‹\ëñÇÛÇjUŒ´íßÁÀ[Õ¢¶ðóÕÂ#‡Nï=¼Tߣ¾Øžµ$n[ô€nZ­.~Þ¦uýwÜ„þ3¦®Œ ÒÔ6ÈåÒá#{Ы—§&o<;"²øvÅÒE[ö^ìk˜ó™S—«*k_š:ˆ·¯šnîöÒµ*¼W§â¢Šøw>ÿðÓ™ã&ôÏH?U\T‘²o·á;o~= {ßèΖ”E3O&“¸¸*W,ý%vxäÆ-ok4Þ‚xè`î¬#£‚¾v+aAòö] žè§{Áp%ò6Ï;s`¹ôe¥wÊÕÕþÇ“WW.ûR,ýpþ#.ŸEó·DöR8ÈÞ_ñåWÚùºÀ¯}àèUU©ILض?#14,À(k†¡uº¦+— ~ïÍ-´ŽN˜¿£¶¦’6Í` „bYb\.ïæ:F©[9þ…~ŸnH¿z¹ ¬W@§ ï=»N¾1û™ƒi§º…øu ô` ?w»%e)d›7fäžÏãþW\tׯ£‡¹‚Ì%Š,a(Ìœ=âPÚé+W zôì@aY˜k´ÀÎÞF•©ªÒäæüöͱ‹¯¾»(ñ9®„ÀæèáóŽNòç^èÇ­KìXÂpÏ;ø»sOº‡úÝÌ+59ýÉê§<ÿâÀ»å5«—í~fð’ã?® ééÇÛnò§GüáÊóäÏWyöÁ^°úl Üߣ¯¶,¶XÜC} ¡Ç ñ6<‚'8›jëWí8¨[h„¯¾;UVÖØË%vv÷¨Tö ƺ« – ôÉjkëìõ‹r…HG3ÍÚFwµÒ^.´—7¶ìlü±¹Í¹·ÞÜz¥4š:ôø¢w&7svlú3ã&ôåXRV}}ó˜¡+”²—_‹ÑÒºŒCçuŒ–{woZP]}ÝŸ&vv•@}}·H€!@›k4““”<3ª×Œ·‡ÅÏÙ‘žvæíùÃå )Ü¿ ˆ «ªjÜÜ•@éˆÉXD_;;`Y†çô§X´«»ýÜE#ûtÏÎþþòàa¡¼íÀƒé(-­¼IþA^†`¹½0Ü£»ðÇbËÅö1„#DÚöt±g“CéâO'²®ÊŠ3ìKÞÞNÚ)Ó}B €èô)½¼KîT1:­@@@A^‰“J.•PoÎ}°.2ªƒL&Þ¹õÛe«ž3*ÚÜæ@Øû¥äÿz<½”„¥G‹X½tï®'~¹^üÌè0.%e9p¶´¤úÀ× ¤RQmM#Ñ¡y ²$qáÍh×NEXšŠ[o®ÑLORBÂÒóú‹m'sÊc€f б#{Ôâù)÷jkµLóÁýg+«îq`AÇeB€%&§?TTÖ””Väææ-žŸâì¢èÝÑ\»¹º+®^þ½¼¢ª¶®Žfµ–Tž7{™L|pÿYšÕ^¾|sOê)„KÏž-¶PœQÃ>Zý Œm_dGþ‚Ùrпؕ‹·³OÜ€ #6èWÞ¸³ÎI%Ù’:mÞ¬”°€”€jçë²:i‚‹«ìþèóA¯sWË“’_\4wwÒÚL­V;"dv|¬iŸ|}v Ë0[6~›´6:{,Y9†ïæM4|²6sɼ¯h-Þ~æÉú<‡ìqxî¨ÿ„™ëù¼e…EvØ·ëLtÈ™\3¤ë€˜à/¶ž\¹á9Þ‚bŸíΛXå,Oß—³êÝŒŽíÛ?pÝg¹:ÌY8lé‚}Î.öqKŸ5×h¦o͹mŸº/õLü씃ßÌ%ÀBt.®²äÔ×âÞÚg'¸¸*6lzÑ?Ðýþw„û¬žÂsú¯[‘¾nEº½\Ù§ã—f*Å\Óv›4¥Ï‘¹Q]Sdo×ÞÅ’Ê›æñ‰#—/Ú¿ùão:{Föõ¿ù[ÙýRûÐk”Áb ̨!Ôz±~ V»V$-ýÓ¨F<ˆÈzÊKk…";gyKŸ#±¤¬¤Fá uPJ[HFk™;ÅÕööb7e ›WWÕG-Ý“ù†w;g¡P r~¨è 9·¦Œß|úÚ»2™èQËâJ‘+$PSÝÀÒBAF‰eÕUõ.®Š»eµb‰ÈÑé¡È×ܬkj¤õ+-i4 Ÿ¢À¨¹Z‡·Ý†--©Q*e†®u•ol¤kï5xx:Z£ƒ!Ô:ç²ïM½ÂfGð„0øM²&wüi7s÷”ÿi2|Ú;ò&3Üœû˲ w!›>qC½6}ßÅíŸg™.–´¦,W{ý…£¨ºªž· ÞÄtNΆ¥ÝxD(…H¨_ia£µUã·¬¥v£@í¥0*¢u…Š%àêaߊª¶U[!ÄÇÆ&GQø39ô¯"´#^>Nb eÔ·«*k÷¦œÿÏ á/OëÛ&ÝÞ\Aÿ2mÞnÙ bý{Ñ[ñ#ú½?êÚ»"B!d$÷Tݤ1ëlwϲ'l@!„LGð6}=Á«èB!ÞoãÓÅ‹#x„BÈt lÓw²£X–bñ("„B&Þ¶§‹eX‚S-!„B¦ÞêEX1À³É;„Býµ#ø7¼D!„ÐC#x l8À Á;@!„B¦C`¡µK°îpÖd„Bˆ'@Úò€ŽàB!žiË#xG…çé¬ xB!#NŽÖ.Š÷¢G!„ÐßE€M€Ba€G!„x„Ba€G!„x„Ba€G!„0À#„Bn¦¢Epטq‚cÂ'LÇèß!‡p¹c~«*Â2@Ù÷åL.ÁKZÞ–M5fIÌIø«mþú9ë·2±‹ƒ}H›QF~£ÂòÉÀý·PôV›‚saŸ³ ˆëú8“ƒt¡Í0™Î€ðòc  QBðœö[„Ó:[8[oÎöÙÂÙ~‹pÚg gç4pJóR<¯Ô†`q a‡ú2êoLùSÁ8•]㛋zòçyÊ$ë(9K¶;Ä©kÚçÑa@ÂBÁt‚¢-“ëè¶Õæø¢ûá‹—ù"e{ g tÓ~¡3zggîHˆËÂÌVÐ8›èÒÿ`t#ŒÖûíV¬~ÜÊ”ÁH\À]´”ó"6…©}ì•—XÚȪ O³‰XÞLBZRÙúvo¥¤´Ý露§:|Ñr+ÿŒ"ÿuÌð$ʘ+÷£´¥¸ºAþ¯Ph!¿ÒŽ¥MqušëcAâ¸"îæˆq¨§fÄä7ÓêF¼:!4kP’"Q¿õwuŠúÛÇˬ»¾›¶RÝÓ¹é÷ñh+y|5÷&A]ù£ž)‡vÒäo…(™ú±âv£µŸCëÒM>+ñIœÙ^ñÎRË>žc?»ÅIâûBÚ)Úa|5½L»4q8~¥þï¿ÿ)@/ ²†¾ö–1‚”b´ &´€4‰1lø¡ I‚”̧û!Ô¾Ð8=h¡ËŒÓ–ÙD·¨KÝY:mì}À›uL¨»*.²'¹×Ÿä™—xž›ž~¥é·¸ÎŸÞ• ùHX¶(æ˜ÉÁYßß±‡_:RÀIb°C‹g(ÂÛÉÄʼn]¥xyÌÌøh%Þñšðô4±8ÇïÉs|Ù–ÈÙz§·-ÅåÀ,dVëëŒ]QÆòÄEÍÌ·û¡ ¾þJCmâSç °S¾~yÈü žÕÍi‚FO…“ki`R`ÿ˜¡0¯DTtÓ¿£ zÎÄ«.T{4Àœ­$s‚71S±­®™ýÎJ£¬t¾Z|–»ócÕj'_E`%ÃGá´8e-̈äûE÷Š˜ø.›ºb‚²þ4•_”¯’ÿ[,ªI,ûbÙm½×Ýb–¥wúýÔ²L}Ð=šZ?‡D¼Â|å–AÌâeåo_>|ýª¾îòµ3ý£ý fT»¥ÑJ»E‘8nQþIœ™r³âX¹I<³Ÿïñy럷õv{‡ËK..oé¶ÝüÖ1Ý)†"R>¾5íÞ÷å"«¯÷ú{èáá^{d”z¯·«g ã*”ú͈öŒèëýÁs„èv§¼d»Y†x!n©‹åG Êž>“wëѽ­ßtmeAÄjª­´JqÕé *Õ• ®ï‚¾2ÐÛƒs)°Ò ñ^Øú•4Ñ$_63*¯¢{þë×õÿPKö±ðJb6LPKÚNŠ: styles.xmlí\Árã6½ç+TLíÞ(R”<±´c§v7•\âÔVfrNA$(!C,´¬ù‰óù’tJ¤LÙòÈñÒS5e¢D¿‡F݆ôþÛ‡4ÝSQ0žÝ8“±ïŒhòˆe«ç—ß»×η·_½çqÌBºˆxX¦4“n!· -FÐ9+Zxã”"[pR°b‘‘” .xN3Óiak/ÔPºE½¬ow¥l÷–ôAö팺¾dÙd¥l÷ŽÙô팺À©Ý=æ};?‰s7äiN$Û³â!aÙ§g-e¾ð¼Íf3ÞLÇ\¬¼É|>÷”´68¬õòR$J+ =šP¬ð&ã‰gtS*I_ûP×6)+Ó%½©!’Ìj.h*ý²ß‹ì> ÿº_õö®ûUÍᚈÞ~¦”›®2ú»Ê4²û¦D®;æ÷Ú»¡úïîÇ_‰´ïX¨Û *,ï SkÛý9絩ØA/venàû3O?[Ú›£êÁ$–zxT=$IX3ÎÓ6Ò@oâ†KïÑåkÜ)Kz£Ý'!ëM=긪@ò;^y‚æ\Èš¸Ð…Q‚z”(&õ0 YŒÕ\ì¨Æ²ßàáêö°Ë×Ψ ÞÖ†8·fwЛÂí{Œu‹• ƒî#õ„¶Ý8ÿÅeñkàÿ:utsÄŠò‹-éäíìùY‚ÙµýŠÏú!Ÿ=9®÷g.ìÇ‘§D|¢ÂÆýo!øÆÁQpqÏèæ?B”?òG?šúºÎréÚÜ ¶­ÿ3¾Ob#“2©R¤‘n‹ œÀ2 9_³Ð1º9Dµ¹¹€=WHI•aªâ’Rò"'˜\±ˆr­J’|MœJ-/³P–êán@|ã,ÍjäÈ»»”@ŠPHÁBi$x¶‚ŒÄMy„ó#\¹4¢˜gHuDñ€éžz ¢Ò˜$­1@ZXy^^7¬Zq - êB~ñ«¯\@ŠÄ\[dXü'Éyñ¯ Ž;£Ÿèfô3OI¦´¾»¢à°ñ ^C#g2„³õ= “»ÝPû ¤³\ª¶ü¨$+h¢™jy™I¶üò¡mH8M‘ÌzG’U +ƒK˜úGÍ4}‹m!izh­‘ïl¶4Ðl£ ¯¼ ²ßÈ>?<Q…ÄH2žÑ6ëð¼›PX Éh< Ví„Pktƒ¨UZaÔÒ µLAÙ9ec]o´©^ýg²ˆˆÈydéV϶+WqJðOøž°HG Ýþa"ç‡i£ÙD;_ýTJG%W=Óq<Å®‡ò–(F5½. »»«`ÛÒ9fIR#¨[jKçs—aä$ÂR‘ ëG˜W8†%Xr)1k“%4–(9¶Z[ÍëšD*[dQ„‹Ðjt!ÿ(¨tš ›Âm«Ð@Â-6ÙÛ÷ªB”°¢¿÷\ÃVK ‘L´²»,“„Ê‘b;ìEŽ~Ô" 7Οü^û‘õ’+y]Ñr?~ø°M—µ£ðoÉÐôl AÞý&š‘¡ë7ÉÐÕÙ Ƴ7Éл³14}“ü|s>~Þhœ¾>C³7§çgdèmÆé‰6Š®þ^ÚW¹–ו2­ƒÀا¬°Nª,¡j4IB³U'"Ͷ:©šU5cMu],‚VÅSõ­ÚÉiÞ¬Ž¼”8`aY"eˆ\ ^®ÖnU(Ó x{Éã´J “ëªà¡ÛŒE"Åz½áÈdbv©@ J OèRQ–MŸy_µ ¨„üÓ…t4SÅ%›¿×VRÑôØBåøuéÄÆeA>¢péêJ"«†Ò…©CE9Mó5ÑuPO4a4>¨Îÿ¢sðHέ‰.7 õQõQ¿F††ŒzȨ‡ŒzȨ‡Œúÿ"£Ö+lÿzÓxÒqÁ©´$S§Ýqjr3=é©kJ"¼tù4þê+6gAÁ¤?G§e¡†£‹Ô.GRó‚™¹ 6:ºÊá_+u~ËÕ<&a‡Ï%4¥¤(Å—X®vAêÔûQ»âÆîþSk¿Æ½¨]/kþLv…2c²Úúºpжν½ïÀ¨ñ¼ø-¡k†Ì…­nËKÙ˜ŠÿÝùN‹Î÷êØ öšõ&3iÝdL«¯".˜ëûh¦ÙÜ–UkB0 … ¶ûžžü¡Inß%²`t»à]”DBœ$ü4 ¾ &Ån:úîZÑ­‚“ žѨV:FO¥åíãФT`‘ãÆ,}§?B»‹;ݹ¯õ±ך\oGò—^û—‹ÝþPK=íäÖ¸œLPKÚNŠ:ôçÆêQQmeta.xml OpenOffice.org/3.0$Linux OpenOffice.org_project/300m15$Build-93792008-09-24T12:49:262009-04-10T18:54:5119PT01H42M15SPKÚNŠ:Thumbnails/thumbnail.pngåšUPœOô¦!h€à.‚»kpw\ƒ»»»nÁ ÜBpîîƒ0ÌŸßÞìÕ^ìÞîMWwÕ©¯Þî:òœúNŒª² :  @—“•TàÞ¶€æïßÖ_ð”8c‘œäWMïÜóØôÍ|øÀ„€30ÉþkÊ^ø×Ôs2œ@l=_õòò„†õM[;}¼¯ï+éR›Û¡æRá@0Ü;2ØP¾V]]ݯ†Y£ªþ˜OtšüüüG]‚iIÚî—õBýýýšT‰òi26G©žJ?9ª;‘nÓ=AZÌEeéÅjˆb°W(³çÅZeÑ8966/uqHA[h ô‰RHˆdyyùêöv0_d$¼Ö@Üâ¸.>’Hú÷3??¡a‡gÚRÌÍáÔÀȈÌÂo}½Öúúzn۞dz4ZffTBBBb2ý++DÌú¿\«·7ÑE§2 Q2¾îîîZ>å zñŒK(() ]mÔÛ/sŒ÷ȯ¥F´òâ®;IJ"¼ÿHÆt©æRÌ1::*¦®žÂ$áë3–°3#IŸ4:*‹»ŽŸ†ŸV¯^†ŒŒì›æ¤T^sts ¤§ÍÃÃsuw—ö e)= }“LÔáyžò“ø‰¥fsl]HxX¬HK oÐå‹K-“ؘ¨­Ö7&¯  Q €IDûòâ¯ÇÉÉÉî~¤ú¡ÁäábýË—/ß·‡!Ç x“ø‰Cvåì,T½ºh­xGÚRŒ•r?\ÓšLÑm¯2ˆî…×Bã´èÔ\”Ïš 8ÑèæÎkÈï9roÀ¶,fAÚ'ÕT½hVÈ`Á‡{{Hækå™È—´âÄࣃqxLlu²wMãO†AÇ´(ù(@Ï ¹ØÙ kÀ÷5¦¦»rZèÑzGKÄ÷†ù¹Z}^µèç6\Øçä˜÷èDºÑ±´Pˆ¹x¹Yý2'¦FÑê,ƒ?¿†1}}}}=ñÓ\ûÁ¡ú—{]“ȯË.=j'*<^½¬h©t¶ÜßNÀR8HÍ‘f\¹¸iǨrH;†]Ô÷öHÍ6w~\T~ß àµh“zUÕdT¸1øêÞ3Þi”´Î¥×SãOHL#j¹^ìZw\–õ0ûËÁ|g°ÔjµÂβ±,E]gLXgÄ>,VM”Æ(à³ÖUíq¶í<ݯΫ°^2ºŸySkS*Æù@Ú’>1-u.1®þë¥Ü $RÝ¿ì—gÁ™%$ôÆf–!fMdÁ5bI_À¥u¦L†÷¦ t|¦ ?UVB8†±>>\“?JªpõWS#ZB^Üw÷¿ÎÏûci'(ðáâáuÑ*ÕsˆsCHœ²J½§¿·Ø­29l4ÛyVãzÙÃ~p>åa½y±øó=»YÓb~FúÕÕQôÕçÕý}Úkгƒð›÷²ûÞòµ¶ÿfà܈ÃgÝ:[ž#àu M¾(90%û^³¾È—ýnò=8c]Ú:‡Lõ õ!…bbáFÍ øíš4 WQ³ø½¦ÉëÙ±ø|‰Ê§Œz{_7¬—†KO–™™|•äw ‚úû#.w§D¤“Èô€°ãÔºcrÿ›I†ýµ@õ²A§®;‘'ë6LŒ< ’ÉlnMM"{Ù9vÿGëÝkr¡ç³8Ë2; çÁÉÓ%yÍìæ÷HÎ>5„¯¯‹ÎC¾u¿¾5úŠUwÌn ûÇ׸§ãÓÀetXà_ Ç,üÖ×é(t$$™½= ;¨Šbgü\¹ÄL•–ÿÝ‚<…ÎQ-°>•V˜Ñ÷¨ùL8ÁË'·C–àÆFá””©}¦£ãÅ\{ß¹d¡(€äüå3‚Êã£ÉåöÁZ‡WVïårX/¥„|nÆþáU¥ÆÕÝ­¤ƒÝ©úîœbžW“‹ÇPÙzÇöL;·ôG’ŠÍ®±ôûl£¯žèCW}FÿH݉ðwA±­mVE¯¢'󦹨F‚0WÞýkµÃçôb:Ù‘ú7_—}sh‰(äùÄ•¢¡Á.ŸÛâê9<ó‹ísY‰ÉŸŸ_£â$®ÆRm{åä>àЏ:Y‹º ܱWDK™›u¾[á&”iŠ.XË'!©£™t¿Ê‘9îôãy½×·ˆYèÛè^>_Õiróê/@ú»Ul9eé1?±òQâ7~zuòöÛ@€Àº¤R«¸EKzéœ/Èjjk-œ~þü‰™žÞÌ6Ø“#äåaz5ŠÛó#Ñ)þS¨MDyZšeóáù]ytç:.n•r%¬2C\8´RÃ8†Ï¤[…ñB¶ÛÜNZé1°1¹pø>ûb™C¡ % M6ËØ0È6ÒgÔBvf¶_+—ËÚñÍHw§Áæå,iÇ#Ý!ÌSdÀs½žcuоÉZô…õþ¬ì)ÐLÖ ÷²Ç]ß+’Ò¹D'†e°tû¶MR‘`ßáê% ÖÒj©À;ÓìŒEÍpï_áÕðmÊ!¾ï`òÔ’d *),N¡;öhî±+쎞§äóåÒ%“ = Ñ… ç÷¦1fÌôÀ¦±ßÂp ã_½9uQQÿP׿íƒI*É¡€½Ñgcê|ô›ò'½%nT:•ô‹Ë8¼ÜÌ(ƒ8#”CvWÆ”¸Š.Ûc°¨!ñ\ã·duéë 0ã:qY⃋—×ÿP=3ADQÔ×X™/–d^^|Šý¥;)àJ©Ó}Š)ÞÔq¡ÇçnC*¥•&ÝfS#ÛçKÏs°O¼A˜Ù¼µIÑ™\ñd+p— µ$9sáRgš–°‘ÝäLoDsxŠ{u¿…túHœŠŸ}e¢÷A–^Ñi'ÉîˆÊxÿfÈ[1¿ë|2¯±[o'Í÷6£PW¯£à£åû9Ò`áyÂ{]n$»µbÆñ»màžR¾Ñ0U$!3p=.:&æû¡{WÑÝÕV=¸\,áOÇe`Õëf¥FòûBì‚‚¥\>%OXò‰tBΔW/ óæ!pÅ zfвÇ( õð¡ˆGî1ã*½é©qF1ºª Ëÿ‚¥|DÐMÂ\æ÷ªßÉ¡¾:>‰)îØ*`|0í«†^mgô9Û‹+×ñ˜6# º3£ƒüŸðOjº…×ÃMd#üe=ýjVnN¶¦?„„L™þUr…gã} #z»ó —Ý"üèÕWh؃Ùý™”n£UšLí1ïfÍ÷ZØÞçÕ‚¹|!Ï›¡OݳÑ$-É€é;'K 3 Æºä\ÃñqÜØÜ™'Z†º:›ßZ+öO\º ª¦‘¶Ðf“µ¶ÿÂb­ìäxhNê§2<»ç´¡0²z«Nßëï w¿@ÆÑÖ˜Å× âÙ õ•6Ý;CLÿv>*vÈ{GÁ"O»S«¤Ñ3‰Œ;,7öO§¼dØÇ{øÐ*Ý÷ûˆªÃ{å?¦W<"ºzn.4“644Ì€ŒKî“ÅæO†îj…µõ¦­¾wgìOþþÏçåºoŽ}©¹9õü!–iÑi>SDt›)˜¬7„óÛ/÷M„8sI!¢ÕUjN:í—Œ:W:Ögùt%ef?3ðµWÂå̘6Gæ>5'=N-ö79‘¿bï¾Ü³°dò[¡½b†Òð “¿¼8ó ‘$¢Qœ£[Ä’7ßûˆI¸X×7ÒÚ)FšlW'Mì®nPÔjI¹0³ö`.j7—¬VOy¥:J-­5¿hÑ5~cMÉ⌳º-Wô‘ ¨ýIa¼×‡êé–ìÊïÉÞ)Š^+컬4µÙ>ˆDZçák{j_QŽìµœâIb¤Œh:®É;©Îàß¹|[åña†œhÙã3ßcå[=$ÅÉŸ,¶²?59ø‰vï´§n¤vùšÂ–ùH±Bn\\2)¨eœU>`Žx8óÓ#£æûcÿ[[k@$}*ü²ÇñQb܈U÷ž ØìCWÆ—B{Û ª©³gµ*;Y‚µ®ã»gGÅf~µÕd*yMÞ‡¶ÿ ¾A¢¤t¿¼¬©Ýµ~³9ÒSž÷d!ÁÅ)*ŒŒ»›×HûO ‹Íö9ù rß°DÛ×øcîúúßÒ¿¬'Ïí’ó ›€Š±ë3~ù×r®N)©òb•ÏÌ“…Põ]ËLÂÔ)¸øó ÃW¦¸ø?„’Pn“™£™Ù©_Êy{¡¤Ø8sƒÓÁ@šî!3±CT™qJæ_“ÕïGwê^‹ôU.B̯B¬ïŒÉØ "wXœDG§c'îeÁ» ú娽šä´—pÖ·ôÓo¸{åÍyæÛã³f€CUíÅêCݘxû¥jÚû;˜Z™§E å¬ZG rg«/Ì¢RƱ¹Ö†%ÍýËÁþh+RÖn‘J_,„_ …c¶ð±¸¸™¿á¯äA÷hEt™1òSIM8¥‚«6£dxÙ˜àÐÁ~ò¬6XR4¤€ª–57Í%ë=[æ–ÞÉJñtÈšð$† ë¼` Š% á¬+³2Ýý-‘ÉVf ýêù—¹F·Òôpa[–us}RŽô·Àϼ@ª"l“ÍŸù8€l›KAo<#Ãõ!LJGBi4ò°$ÑÍø cmí (Z$–Jn6{u™Š6ÙÔnFM@Õ9´<õdn¥Q›²Òc7èÓ-§«…ÆìÌŒšíYšX™úE>‡Y>ð4ã‚ §ÆF±›8W˜?«4kº¼g>A M‰ëðAAÐײlÄ>¨L½ü‘­¸…ù¶]“ÄŒ°$ùs‹€}Äð½ï_8ÿûÎÄ h“•è»9? j¤æäëX|’©ø‡Ft‰Ù¹OUW ¶Ù Ôã)&C$ø„ˆ \¢å?'ÃsYÚßZJê" „5HÿK`ñ`i–1‘F|MïÝà ¤Z ­SL^æ8üCiËp&³›DL„Ä[öÇ AÜÉ ³=é9íÙLS# '°ß}&s<¡ÊiöΉ~¤ôA+—R'ýÁ!ކK¬¨á'×ð:BÁI¾Ê‡Âp›™¢ûå17ÚËQõTìÈWF«ñѽ«Î²`D1­ÊÞÏJ7ذ‰7†7ùå$þ.¤ Ë ·8Êsø™ñÁlVd–÷LÕΘõ!Iþ«ùˆ¯¬BOÌè¿êhÎS9Ê}õ¦†hÄÿú~B€¯Ç,î¶›íô>«]¬D7V_x÷ðˆý°Daéz×þ„˜“cM ´æIt|úÇc5çšítP)u5³i—Ý•&Ž$ n«R£†¸2Çè'¸t¥Þb1 ·úcoy5*mâqbPÝ¿8ÄF¤Ö°­ÅY¬ßß‹®ÅÂ>n+“õP*ÿWÐõh{ ¾6—DáÞé2]@„3r_J ü¼M7ôRô×]”ÍþAÜšuZ)%¸Ùb,…’í¿Ýõ°Q]áU¼þnS<\)L w!ìÛêù¹f&L^§6¤tÜR§D¦ÐB,bHDÍί¯ oÛ.5h0í4ŽÎ2:Ù’ó)%uw{~Þï>oø×+$,žÅ6 ñZË»)GÓÃ:q­LV°G©„É·ÒŽŠ›Û8²·&^'kV1L+¸ôæil·YJ¿`* 2ê÷ß#ÊšZ»ÊõÈ[»Z‘òÝ\›¤ Cïô±-çÆ4ÿ´t^ù›¯õ5ðMœ'f ×ü6™€5†ŸSÊÒ–}n-©©eODæ¤abR¬{‰‹—¼ÜèºÂ7–Ý–(@ ÛÞÚ¢XB›f§¢‚o"r¾;YPÇœ–,¦dhêÎôÇ0ÞŸËâGpPRˆè§Î– ;ýõ&3°çAPfÔsoL‰8ÈØ(U™N Áûóê\=¶¾Ù%ÁSÒa‚ùyÿ4)ËCÀÑòìÔÆ™F™bßÎP\½õ U[o$Ã|^ãxUèHØŸï‰øj£Q­Ü¿5§"*öÝ‚Œ““s?,ÃËôª³Ö÷ÿô'ä­ŠÑv?=>R(â̇ý L>Zèê¨Ù³ˆGá?ü6IYö»pøO ?¯ClÿjË>‡é}à„Q€–8®ß.û±Ö!9Ñcýä^ƒ¹ûuè#©j‡ ž]¼‘Uߺ¾Ó‡¢ ç"21Kσð‹Ž(ÐSárÂy†@•¦äšWKÒöóeðÉÄëd¾R}Z•¨©» “Ý<Ò÷ÐÔµ¼°NGšFÓë¾ÖáúÈ®ß%X?æh2gÍzhÿ>ØÏ‚;<ªHp \JÇoªú»h#ñOÙ$2 £0L+ÊgŒÂ†¹P‡ Ȫ^Âë°Ð«T‡‹jT\åóœfwaMº™h}z#-ýÕ3«žH¿wâ&²sF¡S‡“¨¶©ÆáÓ\×Í[ÇåÍ;Ô-CER#½fn{í¦·‘~€÷… Æp™UoDÌò” e˜Ü˨‹Å2¥³é4špÇD âg  ZЧzs£KÔ*sAH‚ëÄ£«²ÞsÆ›~g#|ô‘`óïZéíqÊx–éú°$Oøê]¹¸ìŽYi³|´XŠû$jÚº ›\M¢tÖT Ò!Ó³=IYÍÎf•0“rÞwL\>låA>™:8ÄlQ'GGw£•[aÈÊá€9ñeT†·Ü½IÞßßIúZaôS³L ø²€9Œ2w>ò.Yýûµÿ+¾Ú¥ø=Ÿ ™¯˜ôú|ssH^³avÅn´HA8Þ$éL›¹Â™¨»òS!×åÆdXc*5 MÉhËÙýÁ=LbàiÁ÷²G7ˆ,¿´7©É†m`N·â¢w…J¥^Ø›Õ5ذzÉ™úÕ­æñI¥æÙÿåÙ{ë1FuÎj+ϧ©Ïš|ãH%ro­OÁ €§p$®êÌÅÁ9ë¼¥J°D§ªy_› qU¨q—2i‹·ßôw®;³q©•éMyð\ÐÔöçJ™þcÉé)H3 [£Öhdóù¬¶>Ò¥õÉÿj™¥µƒ«ÖÅ¡ØAÞå¯o¾~)³çy1Y‚âôÍþ^(·(iÿÕ×”ÎÚU­õ\º¸äW‡«›øÜuÆ´´j[Ž‘ÄüÓ,{šü.sœºéuàS0uÛ\K žˆ‰‰ã𼿢¼+ø=šçõ"teeç*m†5™Ä ô¯ù™¿ÜΩ¨óM+OíMá¼¥øÞLÍ$6#$”ŠÙ/•Cå4-ù¥Š[ ¨ÃÏÂò·Ø !ØöÄ<öªÆÅèâ=°W?4RÍßOŸ½ÿHf l¿÷–CÐ$Ž:p2Ó_&m±‚Oî„#v .ZèôïÕAò€Ïú&@¶ƒÓS}£¦÷o²Ht¿BTnð?÷Ê~'ôCþ:v óEq"´'h¸p1Ο‚zŒÌÑZˆYüûeúb¯­Æ•qr täa÷EäÃwh b¬®Ñ7Ultm-oŒ^Šù½·pá°'ª‰e‚ž½Pû9 —˜D$ÒGýÿèÆ«!ôîxmV%G’˜ZA’ÈÉvÆmæ}«)!ˆ¬¤Æ@"xyY— äØã—UGªÜÍŸzÝþû A9’ª˜p0Žùç;ÙFKs¶Ù¹†­ýS8§ÍûYf~zRæ\¢•é½½ú/Ÿi þ]K×\¬" È@„Ù.¦9©^°Wšb¢Ý\ŽJ»*¬Úƒè0Ùvº »gg­äökìú„ƒ£¢3G„îþPø‘ú’)3mߨfà®ÎŽ«kŸéWè€0"ÑN)? ü£¼veØa)Ý®x¨úíìDX„çF§¿>ßžÆ.:ä.¸´¸Ú%® &+èx½4óJ^`J ÞUÓrlh1òŽqù=zô¿þdÛι\:Ì&ǧ:Ód2+b-Öã”)ùóºÜ³-•²áäFÊçÝš““ !Yêh€$ kE‡=Zs[ÿUƒÞmdõ]/ù]¯ÞCþAGDö6&d ;hGÛ’#Ÿ<}fˆ ‚:q›j®VŸHgEjfú›Ë.¬þFD'õPü•’J”…ýZøqšykONJ¡žËù€*Œ~˜~çò¤øƒ4vð?ÜÑžrÁv6/ÏØCµA„𠣃ÁR¥ŠÃ1ŇR§«xÈ.6Ö&ÆaÏN_ÖÖr(é1|cb­ll(ޏÙ\#}Ðdë‹yU£çý‘°£CˆøSÆRë¾<³µ›½Ê@Þ_ ¸móÎzHK±õávÍ}£å»G§|ö€´_¡ê-æÉêB_øXà£Ý”Þ¿•ÅáöËû¸BI;{<Ó4N8S‹›IÔw'\vÓ?¤ÆpÌKøƒs„L¬ô ¶B>À³ øxŸ*n𠊉åyxè‹8„|tø‘ÞaŸ 6}àš$p2þ©éиà«Ò>wÚ£pkê Qà‚Êq»-£'â“KJ¾•‡Öˆ‚jö­bAÐPã¿Ñ}Re–vi%ß°E«2y!o¾±MN\„sÂÁ2ÆÓ"R+¦Ú&¯N5ž÷iKL mÚÕgŸÇ­ Û]NÊ*ux™'¹¸w+µ”Ûã]Ø7HÄD’ž ÊÊú„ÿ›‚ˆÄ >üï# ›— ‘¥mm¡ïzwDË"é{÷ðíùªŠ‹ÎP×ÐвhJ®)æãã¿§ˆd*AûQPj„ è 7|ùòE5ù˜½A@S PT\lúísý#Ri{ÍKYÉSSSÔÍeCõ°ú«©©ÉÙÃcÁî= €O"è‰6™Í¦Ñ#Œ6­ 1³¤`eeõ >ÝÞ.Ô ³s†ûž–1–JçVm,zn²…I~öE bdë5{Dí xº‚d‘íE?vü¯É´'º˜4ÿH6ÚJŠž•<6ÝD ì öÆÁf-§>ˆL8‰ˆ;Y¯³j¸H¶§åäÄñ8¬ü4ìð,ÃpaÕ›`à. ¡~ø°Åæ÷ãø~´ùžZ8:®,½²`FrÃùmŠ’†ð½Šî™Çq½=jÔ-¦5ßÕñB)9Ã88ýTNª ÂMçêOóÓ'tX°6ÇFóæ+¾ÛA‚˜õ(Mõ=¢»Ô¿1…ÖìÄÕöf5P ©M¨á茼]bÞÈ]>+ý˜ÞÑ|œ2I÷ç´"® Æ¥{ _F‘hµõò­ÅuMƒh%zy™’ʵsfâí¿y°¤Ëéú sÝ+e ˜jM-ÓL£“ÛÞ«„¬©ia¬=zl{äÖ– 6À7‚·àìå5Òl·D1L™¸rÝóC»&?V°å’’’T.†Ðû "P÷þþ½ÿ’þ³Dúî÷³E. ´)ná]¤mÐd‘~™B…es Ý<ìØOY£èÛ§¨ªÙ“¹i©-“?ØÅÝÌŒ©o© |Ül’ÅQ÷ÍxŸ×bñ1%²ÏÈqã/I_/ã•« m?nëþ tk Ý9j5WˆÆ!@5‚a)e¯P;›}´ß$1+Rl-4õ´¶®°ÝN àuÌÝØ~sп¹üÔß(?’ð‰íb¥yW2éVìðñÔ÷žhé;?_þ[R§Ev´-%ë|gl¿É»9pÆÑ5‹ËaæhT¿ ïÉaZL@­g=ú|²ºü³ÎºOc[Â×(ã“ùLS)°Uw7N%hÄØÏÜÄ<5‰%ˇñ Šim ßÌᘄU ¡Ú¿8€ ¢ü“EöKÅr5|›.·Ë/a½Y¿­÷eËtZÉ~; c¿:õŽKG\vC@ÿ]ô‹ý`›îãG‡$b~¯’Y,zîýk³zyN§ ¡å9 dä¿Ã0Ô`ìO=¤0Ö÷æÀðOÁÍ;cè>­±a±@(ö>cÿÞ¬úq)6ƒ‹[“fýÞØ'° \RHªk”ÙPWÏcz×ÿFÅ?€éOôz'§ìÿq¼QýÚ»7Àþ¿•¥çÙ‰ljû½CW#®?ÞöBÿÏÿŸšÀà,þª¢26*ý7»+'¥,Y'nú?PKÀ4KÐ*Û+PKÚNŠ: settings.xmlÝZ[sâ6~ï¯ÈxúÐ>B’% ØfIBcØvû&ìƒQ#KIá߯$LÊ‚€Œ:æ![ú¾stŽÎ\~ÉÑ pmzµãïhÀBL£¦7õ*—ÞçÖO×l:Å4B¤1PY ¥Z"ŽÔv*Ë×M/å´ÁÀ¢AQ ¢!ƒK€®¶5ÖW7 ÙòÉ+Áô¹éͤLÕê|>?žŸ3UkWWWUóvµ4á ’FàÝ×÷¬ÓŒNq´+Êrõú~ÆØ›ÐzÃR1#øéÉÉyuù÷jµˆ1Ù•K¯­,N”ÌòÃY!Šã]aôÚ5­³ƒ_3÷©×ZÙveÒÖu¦èòGKˆµ½²Çš¯é)Õ/æožàåíûqÏW,´2mhÄoõR.õSéµ*gçõO×Õm ½À0•¹èµOµZiô?p(gyðgõúeiø;ÀÑ,WüÓZýlçéÄ(©`Â+„›\0Ï·–Ù£œ‡/v‘æýpCL!¹r¯¥Ãò ã8ì‹ì<6à'Œ@ÔkMP¿ÇÝ<ãC ÷…OQ2bš¥^ò´$úEpx„©pG¢¿0…BŠÓãäod«‡ÎY†L]"7Ê I*î ˆ6™£…C÷Õ®«~¹á(òÕU#Åæ±÷€[‚cL‘„!# slõ@¶5]^\ª}:9±Õf›Ë…‰2{ ÐBe¾M|$ ~ÞQBð…תîüuÙ´“e¨B¤Dÿi,x†ðcQªC=°¶Tñ‬ËÛ±¼³?¥ø‡ Ç_Çê/*ofÊãêêXÞˆŠhjðƒ÷…q…{:8оèà(‹“NBã K• »Ï#x•·!.Ìñe´0Ý¢<±eSá@ŸàÄø›çÛøÜ2¼«cÑö¥2⛞iBº¥û¬ ˜Ü2ñ!pµó°4·8._×ÿ_[’+Ç-Iݾï2ÄJ_;½°t˜À‹e/‡ÞS¥q¡à{ôiùÈÅR—‚Öõ°úχ4Ž$ã9n€2SÜå³”hß8¾ý z|s£G_˜‚ZÓÜR]6Œe’ˆBwP·ÿÅXüHsªòkÎÃõ¹CÑël”‘¿@€Ü}jµ|r“¸÷_µ“„,Æø ’èð…EK¥èH»ÂøiP0Yùù—T ðkFPY?lbǪêŽT-É»,ÖcR=)ʃ–•¦x·Ö,°#½AbfÍZrÂ¥D*Z_æ—ûdâ^ñ C oæ+?Ѩ‚6Íi(²³jkûTó Ž}ËêqŒ¶FxêÍj"LõxËá–†ïî/ç>ÎQ(Ä ÌÚÅ#»“¿C2°¿W3Ûdù8m eóaJ™ºêºúÂÌg:Œ=p3!^'è àÙE‹ºÎñ4‰Ê…n朽‡å{UFy‚;E5‡“QºáÐè®F܆a„ ¸=§v"¿Ž *Z‡[Z†Â'@!£d31B«{@"å0¦[󧬌º°Ÿ%ª†g\åÿåö‡–C¡¡*#"Ž’™ŸÆ±«àj<é÷,7½ÌtÈÀï«Ì©?W9q€Ûc¢•76¯¨B—‘T«YŠ2çVï^@d>Èt³RÜwôî£øºüPÿ‘v .îª nzaýn+o †s>ZJbàH;yð LS¤Š!Œ»OÎîÊ"èŒÆLpï|ôéðÁõ)ß—£gƒ³s&\Ð#ÉWÍxÊêxýý(¡hÇî©¢®ÔTð· Ê,Ç^½ O~þ_3ÿÎ%>¤Ù±2Ìvðl÷qØYІ$_†•·ýÜðy ‹Ì鮼–v%\•ëOPK]ñèGePKÚNŠ:Ÿ.Ä++mimetypePKÚNŠ:QConfigurations2/statusbar/PKÚNŠ:'‰Configurations2/accelerator/current.xmlPKÚNŠ:àConfigurations2/floater/PKÚNŠ:Configurations2/popupmenu/PKÚNŠ:NConfigurations2/progressbar/PKÚNŠ:ˆConfigurations2/menubar/PKÚNŠ:¾Configurations2/toolbar/PKÚNŠ:ôConfigurations2/images/Bitmaps/PKÚNŠ:ö±ðJb6L 1content.xmlPKÚNŠ:=íäÖ¸œL Ì styles.xmlPKÚNŠ:ôçÆêQQ¼meta.xmlPKÚNŠ:À4KÐ*Û+3Thumbnails/thumbnail.pngPKÚNŠ:òÓ–™h# Csettings.xmlPKÚNŠ:]ñèGeEHMETA-INF/manifest.xmlPKîÏIlibnetty-java-3.1.0.CR1.orig/src/assembly/0000755000175000017500000000000011316313121017461 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/assembly/default.xml0000644000175000017500000000530411172567046021652 0ustar deckerdecker dist tar.bz2 zip false **/README* **/LICENSE* **/NOTICE* **/COPYRIGHT* **/*.txt **/*.xml **/license/** **/src/** **/target/** **/.*/** target jar ${project.build.finalName}*.jar ${project.build.finalName}*-javadoc.jar target/api doc/api **/** target/xref doc/xref **/** target/docbook/publish/en-US doc/guide **/** libnetty-java-3.1.0.CR1.orig/src/test/0000755000175000017500000000000011316313121016621 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/0000755000175000017500000000000011316313121017542 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/0000755000175000017500000000000011316313121020331 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/0000755000175000017500000000000011316313121021451 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/0000755000175000017500000000000011316313124022617 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/0000755000175000017500000000000011316313122024225 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/SucceededChannelFutureTest.java0000644000175000017500000000316511054514360032313 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 125 $, $Date: 2008-08-25 04:35:12 -0700 (Mon, 25 Aug 2008) $ * */ public class SucceededChannelFutureTest { @Test public void testConstantProperties() { Channel channel = createMock(Channel.class); SucceededChannelFuture future = new SucceededChannelFuture(channel); assertTrue(future.isSuccess()); assertNull(future.getCause()); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/CompleteChannelFutureTest.java0000644000175000017500000000726311117154720032202 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.util.concurrent.TimeUnit; import org.junit.Before; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 594 $, $Date: 2008-12-08 00:24:48 -0800 (Mon, 08 Dec 2008) $ * */ public class CompleteChannelFutureTest { private final Channel channel = createMock(Channel.class); private CompleteChannelFuture future; @Before public void init() { future = new CompleteChannelFutureImpl(channel); } @Test(expected = NullPointerException.class) public void shouldDisallowNullChannel() { new CompleteChannelFutureImpl(null); } @Test public void shouldNotifyImmediatelyOnAdd() throws Exception { ChannelFutureListener l = createStrictMock(ChannelFutureListener.class); l.operationComplete(future); replay(l); future.addListener(l); verify(l); } @Test public void shouldNotRethrowListenerException() { ChannelFutureListener l = new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { throw new ExpectedError(); } }; future.addListener(l); } @Test public void shouldNotDoAnythingOnRemove() throws Exception { ChannelFutureListener l = createStrictMock(ChannelFutureListener.class); replay(l); future.removeListener(l); verify(l); } @Test public void testConstantProperties() throws InterruptedException { assertSame(channel, future.getChannel()); assertTrue(future.isDone()); assertFalse(future.cancel()); assertFalse(future.isCancelled()); assertSame(future, future.await()); assertTrue(future.await(1)); assertTrue(future.await(1, TimeUnit.NANOSECONDS)); assertSame(future, future.awaitUninterruptibly()); assertTrue(future.awaitUninterruptibly(1)); assertTrue(future.awaitUninterruptibly(1, TimeUnit.NANOSECONDS)); } private static class CompleteChannelFutureImpl extends CompleteChannelFuture { CompleteChannelFutureImpl(Channel channel) { super(channel); } public Throwable getCause() { throw new Error(); } public boolean isSuccess() { throw new Error(); } } private static class ExpectedError extends Error { private static final long serialVersionUID = 7059276744882005047L; ExpectedError() { super(); } } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/0000755000175000017500000000000011316313122025515 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/NioOioSocketEchoTest.java0000644000175000017500000000354511055251464032405 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 148 $, $Date: 2008-08-27 06:14:28 -0700 (Wed, 27 Aug 2008) $ * */ public class NioOioSocketEchoTest extends AbstractSocketEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/AbstractSocketEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/AbstractSocketEchoTest.jav0000644000175000017500000001501711172030314032575 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public abstract class AbstractSocketEchoTest { private static final Random random = new Random(); static final byte[] data = new byte[1048576]; private static ExecutorService executor; static { random.nextBytes(data); } @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract ChannelFactory newClientSocketChannelFactory(Executor executor); @Test public void testSimpleEcho() throws Throwable { ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor)); ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor)); EchoHandler sh = new EchoHandler(); EchoHandler ch = new EchoHandler(); sb.getPipeline().addFirst("handler", sh); cb.getPipeline().addFirst("handler", ch); Channel sc = sb.bind(new InetSocketAddress(0)); int port = ((InetSocketAddress) sc.getLocalAddress()).getPort(); ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port)); assertTrue(ccf.awaitUninterruptibly().isSuccess()); Channel cc = ccf.getChannel(); for (int i = 0; i < data.length;) { int length = Math.min(random.nextInt(1024 * 64), data.length - i); cc.write(ChannelBuffers.wrappedBuffer(data, i, length)); i += length; } while (ch.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } while (sh.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } sh.channel.close().awaitUninterruptibly(); ch.channel.close().awaitUninterruptibly(); sc.close().awaitUninterruptibly(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } @ChannelPipelineCoverage("one") private class EchoHandler extends SimpleChannelUpstreamHandler { volatile Channel channel; final AtomicReference exception = new AtomicReference(); volatile int counter; EchoHandler() { super(); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer m = (ChannelBuffer) e.getMessage(); byte[] actual = new byte[m.readableBytes()]; m.getBytes(0, actual); int lastIdx = counter; for (int i = 0; i < actual.length; i ++) { assertEquals(data[i + lastIdx], actual[i]); } if (channel.getParent() != null) { channel.write(m); } counter += actual.length; } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (exception.compareAndSet(null, e.getCause())) { e.getChannel().close(); } } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/NioServerSocketShutdownTimeTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/NioServerSocketShutdownTim0000644000175000017500000001056311172030314032737 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.util.TestUtil; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public class NioServerSocketShutdownTimeTest { @Test(timeout = 10000) public void testSuccessfulBindAttempt() throws Exception { if (!TestUtil.isTimingTestEnabled()) { return; } ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setOption("localAddress", new InetSocketAddress(0)); bootstrap.setOption("child.receiveBufferSize", 9753); bootstrap.setOption("child.sendBufferSize", 8642); DummyHandler handler = new DummyHandler(); bootstrap.getPipeline().addLast("dummy", handler); Channel channel = bootstrap.bind(); long startTime = System.currentTimeMillis(); Socket socket = null; try { socket = new Socket( TestUtil.getLocalHost(), ((InetSocketAddress) channel.getLocalAddress()).getPort()); while (!handler.connected) { try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore } } socket.close(); while (!handler.closed) { try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore } } } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // Ignore. } } channel.close().awaitUninterruptibly(); bootstrap.getFactory().releaseExternalResources(); } long shutdownTime = System.currentTimeMillis() - startTime; assertTrue("Shutdown takes too long: " + shutdownTime + " ms", shutdownTime < 500); } @ChannelPipelineCoverage("all") private static class DummyHandler extends SimpleChannelUpstreamHandler { volatile boolean connected; volatile boolean closed; DummyHandler() { super(); } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { connected = true; } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { closed = true; } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/NioClientSocketShutdownTimeTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/NioClientSocketShutdownTim0000644000175000017500000000641011156055201032707 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.util.DummyHandler; import org.jboss.netty.util.TestUtil; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1013 $, $Date: 2009-03-11 17:42:41 -0700 (Wed, 11 Mar 2009) $ * */ public class NioClientSocketShutdownTimeTest { @Test public void testShutdownTime() throws Throwable { if (!TestUtil.isTimingTestEnabled()) { return; } ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(0)); ClientBootstrap b = new ClientBootstrap( new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); b.getPipeline().addLast("handler", new DummyHandler()); long startTime; long stopTime; try { serverSocket.configureBlocking(false); ChannelFuture f = b.connect(new InetSocketAddress( TestUtil.getLocalHost(), serverSocket.socket().getLocalPort())); serverSocket.accept(); f.awaitUninterruptibly(); if (f.getCause() != null) { throw f.getCause(); } assertTrue(f.isSuccess()); startTime = System.currentTimeMillis(); f.getChannel().close().awaitUninterruptibly(); } finally { b.getFactory().releaseExternalResources(); stopTime = System.currentTimeMillis(); try { serverSocket.close(); } catch (IOException ex) { // Ignore. } } long shutdownTime = stopTime - startTime; assertTrue("Shutdown takes too long: " + shutdownTime + " ms", shutdownTime < 500); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/nio/0000755000175000017500000000000011316313121026301 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/nio/SimpleHandler.java0000644000175000017500000000373011214110071031672 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelHandler; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Daniel Bevenius (dbevenius@jboss.com) * @version $Rev: 1343 $, $Date: 2009-06-10 22:03:53 -0700 (Wed, 10 Jun 2009) $ */ @ChannelPipelineCoverage("all") public class SimpleHandler extends SimpleChannelHandler { @Override public void messageReceived(final ChannelHandlerContext ctx, final MessageEvent e) throws Exception { final ChannelBuffer cb = (ChannelBuffer) e.getMessage(); final byte[] actual = new byte[cb.readableBytes()]; cb.getBytes(0, actual); //System.out.println("TestHandler payload : " + new String(actual)); ctx.sendDownstream(e); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/nio/NioDatagramChannelTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/nio/NioDatagramChannelTest0000644000175000017500000001123311214117746032557 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.junit.Assert.*; import java.io.IOException; import java.net.DatagramPacket; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Daniel Bevenius (dbevenius@jboss.com) * @version $Rev: 1347 $, $Date: 2009-06-10 23:10:46 -0700 (Wed, 10 Jun 2009) $ */ public class NioDatagramChannelTest { private static Channel sc; private static InetSocketAddress inetSocketAddress; @BeforeClass public static void setupChannel() { final NioDatagramChannelFactory channelFactory = new NioDatagramChannelFactory( Executors.newCachedThreadPool()); final ConnectionlessBootstrap sb = new ConnectionlessBootstrap(channelFactory); inetSocketAddress = new InetSocketAddress("localhost", 9999); sc = sb.bind(inetSocketAddress); final SimpleHandler handler = new SimpleHandler(); sc.getPipeline().addFirst("handler", handler); } @Test public void checkBoundPort() throws Throwable { final InetSocketAddress socketAddress = (InetSocketAddress) sc .getLocalAddress(); assertEquals(9999, socketAddress.getPort()); } @Test public void sendReciveOne() throws Throwable { final String expectedPayload = "some payload"; sendRecive(expectedPayload); } @Test public void sendReciveMultiple() throws Throwable { final String expectedPayload = "some payload"; for (int i = 0; i < 1000; i ++) { sendRecive(expectedPayload); } } public void clientBootstrap() { final NioDatagramChannelFactory channelFactory = new NioDatagramChannelFactory( Executors.newCachedThreadPool()); final ConnectionlessBootstrap bootstrap = new ConnectionlessBootstrap(channelFactory); bootstrap.getPipeline().addLast("test", new SimpleHandler()); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); InetSocketAddress clientAddress = new InetSocketAddress("localhost", 8888); bootstrap.setOption("localAddress", clientAddress); ChannelFuture ccf = bootstrap.connect(inetSocketAddress); ccf.awaitUninterruptibly(); Channel cc = ccf.getChannel(); final String payload = "client payload"; ChannelFuture write = cc.write(ChannelBuffers.wrappedBuffer(payload .getBytes(), 0, payload.length())); write.awaitUninterruptibly(); } @AfterClass public static void closeChannel() { if (sc != null) { final ChannelFuture future = sc.close(); if (future != null) { future.awaitUninterruptibly(); } } } private void sendRecive(final String expectedPayload) throws IOException { final UdpClient udpClient = new UdpClient(inetSocketAddress .getAddress(), inetSocketAddress.getPort()); final DatagramPacket dp = udpClient.send(expectedPayload.getBytes()); dp.setData(new byte[expectedPayload.length()]); assertFalse("The payload should have been cleared", expectedPayload .equals(new String(dp.getData()))); udpClient.receive(dp); assertEquals(expectedPayload, new String(dp.getData())); udpClient.close(); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/nio/UdpClient.java0000644000175000017500000000426111214110071031032 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.io.IOException; import java.net.DatagramPacket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.SocketException; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Daniel Bevenius (dbevenius@jboss.com) * @version $Rev: 1343 $, $Date: 2009-06-10 22:03:53 -0700 (Wed, 10 Jun 2009) $ */ public class UdpClient { private final InetAddress address; private final DatagramSocket clientSocket; private final int port; public UdpClient(final InetAddress address, final int port) throws SocketException { this.address = address; this.port = port; clientSocket = new DatagramSocket(); clientSocket.setReuseAddress(true); } public DatagramPacket send(final byte[] payload) throws IOException { final DatagramPacket dp = new DatagramPacket(payload, payload.length, address, port); clientSocket.send(dp); return dp; } public void receive(final DatagramPacket dp) throws IOException { clientSocket.receive(dp); } public void close() { clientSocket.close(); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/OioNioSocketEchoTest.java0000644000175000017500000000353311055251464032402 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 148 $, $Date: 2008-08-27 06:14:28 -0700 (Wed, 27 Aug 2008) $ * */ public class OioNioSocketEchoTest extends AbstractSocketEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/NioNioSocketEchoTest.java0000644000175000017500000000354511055251464032404 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 148 $, $Date: 2008-08-27 06:14:28 -0700 (Wed, 27 Aug 2008) $ * */ public class NioNioSocketEchoTest extends AbstractSocketEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/socket/OioOioSocketEchoTest.java0000644000175000017500000000353311055251464032403 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 148 $, $Date: 2008-08-27 06:14:28 -0700 (Wed, 27 Aug 2008) $ * */ public class OioOioSocketEchoTest extends AbstractSocketEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/channel/FailedChannelFutureTest.java0000644000175000017500000000350411054514360031610 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 125 $, $Date: 2008-08-25 04:35:12 -0700 (Mon, 25 Aug 2008) $ * */ public class FailedChannelFutureTest { @Test public void testConstantProperties() { Channel channel = createMock(Channel.class); Exception e = new Exception(); FailedChannelFuture future = new FailedChannelFuture(channel, e); assertFalse(future.isSuccess()); assertSame(e, future.getCause()); } @Test(expected = NullPointerException.class) public void shouldDisallowNullException() { new FailedChannelFuture(createMock(Channel.class), null); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/0000755000175000017500000000000011316313121024242 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/Slf4JLoggerTest.java0000644000175000017500000001203311054510506030033 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class Slf4JLoggerTest { private static final Exception e = new Exception(); @Test public void testIsDebugEnabled() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); expect(mock.isDebugEnabled()).andReturn(true); replay(mock); InternalLogger logger = new Slf4JLogger(mock); assertTrue(logger.isDebugEnabled()); verify(mock); } @Test public void testIsInfoEnabled() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); expect(mock.isInfoEnabled()).andReturn(true); replay(mock); InternalLogger logger = new Slf4JLogger(mock); assertTrue(logger.isInfoEnabled()); verify(mock); } @Test public void testIsWarnEnabled() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); expect(mock.isWarnEnabled()).andReturn(true); replay(mock); InternalLogger logger = new Slf4JLogger(mock); assertTrue(logger.isWarnEnabled()); verify(mock); } @Test public void testIsErrorEnabled() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); expect(mock.isErrorEnabled()).andReturn(true); replay(mock); InternalLogger logger = new Slf4JLogger(mock); assertTrue(logger.isErrorEnabled()); verify(mock); } @Test public void testDebug() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.debug("a"); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.debug("a"); verify(mock); } @Test public void testDebugWithException() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.debug("a", e); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.debug("a", e); verify(mock); } @Test public void testInfo() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.info("a"); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.info("a"); verify(mock); } @Test public void testInfoWithException() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.info("a", e); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.info("a", e); verify(mock); } @Test public void testWarn() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.warn("a"); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.warn("a"); verify(mock); } @Test public void testWarnWithException() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.warn("a", e); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.warn("a", e); verify(mock); } @Test public void testError() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.error("a"); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.error("a"); verify(mock); } @Test public void testErrorWithException() { org.slf4j.Logger mock = createStrictMock(org.slf4j.Logger.class); mock.error("a", e); replay(mock); InternalLogger logger = new Slf4JLogger(mock); logger.error("a", e); verify(mock); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/Log4JLoggerTest.java0000644000175000017500000001221411054510506030031 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.easymock.EasyMock.*; import static org.easymock.classextension.EasyMock.*; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class Log4JLoggerTest { private static final Exception e = new Exception(); @Test public void testIsDebugEnabled() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); expect(mock.isDebugEnabled()).andReturn(true); replay(mock); InternalLogger logger = new Log4JLogger(mock); assertTrue(logger.isDebugEnabled()); verify(mock); } @Test public void testIsInfoEnabled() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); expect(mock.isInfoEnabled()).andReturn(true); replay(mock); InternalLogger logger = new Log4JLogger(mock); assertTrue(logger.isInfoEnabled()); verify(mock); } @Test public void testIsWarnEnabled() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); replay(mock); InternalLogger logger = new Log4JLogger(mock); assertTrue(logger.isWarnEnabled()); verify(mock); } @Test public void testIsErrorEnabled() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); replay(mock); InternalLogger logger = new Log4JLogger(mock); assertTrue(logger.isErrorEnabled()); verify(mock); } @Test public void testDebug() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.debug("a"); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.debug("a"); verify(mock); } @Test public void testDebugWithException() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.debug("a", e); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.debug("a", e); verify(mock); } @Test public void testInfo() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.info("a"); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.info("a"); verify(mock); } @Test public void testInfoWithException() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.info("a", e); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.info("a", e); verify(mock); } @Test public void testWarn() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.warn("a"); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.warn("a"); verify(mock); } @Test public void testWarnWithException() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.warn("a", e); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.warn("a", e); verify(mock); } @Test public void testError() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.error("a"); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.error("a"); verify(mock); } @Test public void testErrorWithException() { org.apache.log4j.Logger mock = createStrictMock(org.apache.log4j.Logger.class); mock.error("a", e); replay(mock); InternalLogger logger = new Log4JLogger(mock); logger.error("a", e); verify(mock); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/JdkLoggerTest.java0000644000175000017500000001313211054524651027630 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.easymock.EasyMock.*; import static org.easymock.classextension.EasyMock.*; import static org.junit.Assert.*; import java.util.logging.Level; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 128 $, $Date: 2008-08-25 05:46:33 -0700 (Mon, 25 Aug 2008) $ * */ public class JdkLoggerTest { private static final Exception e = new Exception(); @Test public void testIsDebugEnabled() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); expect(mock.isLoggable(Level.FINE)).andReturn(true); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); assertTrue(logger.isDebugEnabled()); verify(mock); } @Test public void testIsInfoEnabled() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); expect(mock.isLoggable(Level.INFO)).andReturn(true); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); assertTrue(logger.isInfoEnabled()); verify(mock); } @Test public void testIsWarnEnabled() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); expect(mock.isLoggable(Level.WARNING)).andReturn(true); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); assertTrue(logger.isWarnEnabled()); verify(mock); } @Test public void testIsErrorEnabled() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); expect(mock.isLoggable(Level.SEVERE)).andReturn(true); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); assertTrue(logger.isErrorEnabled()); verify(mock); } @Test public void testDebug() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.FINE, "foo", null, "a"); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.debug("a"); verify(mock); } @Test public void testDebugWithException() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.FINE, "foo", null, "a", e); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.debug("a", e); verify(mock); } @Test public void testInfo() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.INFO, "foo", null, "a"); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.info("a"); verify(mock); } @Test public void testInfoWithException() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.INFO, "foo", null, "a", e); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.info("a", e); verify(mock); } @Test public void testWarn() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.WARNING, "foo", null, "a"); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.warn("a"); verify(mock); } @Test public void testWarnWithException() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.WARNING, "foo", null, "a", e); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.warn("a", e); verify(mock); } @Test public void testError() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.SEVERE, "foo", null, "a"); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.error("a"); verify(mock); } @Test public void testErrorWithException() { java.util.logging.Logger mock = createStrictMock(java.util.logging.Logger.class); mock.logp(Level.SEVERE, "foo", null, "a", e); replay(mock); InternalLogger logger = new JdkLogger(mock, "foo"); logger.error("a", e); verify(mock); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/JBossLoggerFactoryTest.java0000644000175000017500000000303711054510506031465 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class JBossLoggerFactoryTest { @Test public void testCreation() { InternalLogger logger = new JBossLoggerFactory().newInstance("foo"); assertTrue(logger instanceof JBossLogger); assertEquals("foo", logger.toString()); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/JBossLoggerTest.java0000644000175000017500000001235411054510506030137 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.easymock.EasyMock.*; import static org.easymock.classextension.EasyMock.*; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class JBossLoggerTest { private static final Exception e = new Exception(); @Test @SuppressWarnings("deprecation") public void testIsDebugEnabled() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); expect(mock.isDebugEnabled()).andReturn(true); replay(mock); InternalLogger logger = new JBossLogger(mock); assertTrue(logger.isDebugEnabled()); verify(mock); } @Test @SuppressWarnings("deprecation") public void testIsInfoEnabled() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); expect(mock.isInfoEnabled()).andReturn(true); replay(mock); InternalLogger logger = new JBossLogger(mock); assertTrue(logger.isInfoEnabled()); verify(mock); } @Test public void testIsWarnEnabled() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); replay(mock); InternalLogger logger = new JBossLogger(mock); assertTrue(logger.isWarnEnabled()); verify(mock); } @Test public void testIsErrorEnabled() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); replay(mock); InternalLogger logger = new JBossLogger(mock); assertTrue(logger.isErrorEnabled()); verify(mock); } @Test public void testDebug() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.debug("a"); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.debug("a"); verify(mock); } @Test public void testDebugWithException() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.debug("a", e); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.debug("a", e); verify(mock); } @Test public void testInfo() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.info("a"); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.info("a"); verify(mock); } @Test public void testInfoWithException() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.info("a", e); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.info("a", e); verify(mock); } @Test public void testWarn() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.warn("a"); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.warn("a"); verify(mock); } @Test public void testWarnWithException() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.warn("a", e); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.warn("a", e); verify(mock); } @Test public void testError() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.error("a"); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.error("a"); verify(mock); } @Test public void testErrorWithException() { org.jboss.logging.Logger mock = createStrictMock(org.jboss.logging.Logger.class); mock.error("a", e); replay(mock); InternalLogger logger = new JBossLogger(mock); logger.error("a", e); verify(mock); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/CommonsLoggerFactoryTest.java0000644000175000017500000000304511054510506032057 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class CommonsLoggerFactoryTest { @Test public void testCreation() { InternalLogger logger = new CommonsLoggerFactory().newInstance("foo"); assertTrue(logger instanceof CommonsLogger); assertEquals("foo", logger.toString()); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/Slf4JLoggerFactoryTest.java0000644000175000017500000000303711054510506031367 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class Slf4JLoggerFactoryTest { @Test public void testCreation() { InternalLogger logger = new Slf4JLoggerFactory().newInstance("foo"); assertTrue(logger instanceof Slf4JLogger); assertEquals("foo", logger.toString()); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/CommonsLoggerTest.java0000644000175000017500000001273111054510506030531 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class CommonsLoggerTest { private static final Exception e = new Exception(); @Test public void testIsDebugEnabled() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); expect(mock.isDebugEnabled()).andReturn(true); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); assertTrue(logger.isDebugEnabled()); verify(mock); } @Test public void testIsInfoEnabled() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); expect(mock.isInfoEnabled()).andReturn(true); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); assertTrue(logger.isInfoEnabled()); verify(mock); } @Test public void testIsWarnEnabled() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); expect(mock.isWarnEnabled()).andReturn(true); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); assertTrue(logger.isWarnEnabled()); verify(mock); } @Test public void testIsErrorEnabled() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); expect(mock.isErrorEnabled()).andReturn(true); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); assertTrue(logger.isErrorEnabled()); verify(mock); } @Test public void testDebug() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.debug("a"); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.debug("a"); verify(mock); } @Test public void testDebugWithException() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.debug("a", e); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.debug("a", e); verify(mock); } @Test public void testInfo() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.info("a"); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.info("a"); verify(mock); } @Test public void testInfoWithException() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.info("a", e); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.info("a", e); verify(mock); } @Test public void testWarn() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.warn("a"); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.warn("a"); verify(mock); } @Test public void testWarnWithException() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.warn("a", e); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.warn("a", e); verify(mock); } @Test public void testError() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.error("a"); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.error("a"); verify(mock); } @Test public void testErrorWithException() { org.apache.commons.logging.Log mock = createStrictMock(org.apache.commons.logging.Log.class); mock.error("a", e); replay(mock); InternalLogger logger = new CommonsLogger(mock, "foo"); logger.error("a", e); verify(mock); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/InternalLoggerFactoryTest.java0000644000175000017500000001242411054510506032221 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.easymock.EasyMock.*; import static org.easymock.classextension.EasyMock.*; import static org.junit.Assert.*; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class InternalLoggerFactoryTest { private static final Exception e = new Exception(); private InternalLoggerFactory oldLoggerFactory; private InternalLogger mock; @Before public void init() { oldLoggerFactory = InternalLoggerFactory.getDefaultFactory(); InternalLoggerFactory mockFactory = createMock(InternalLoggerFactory.class); mock = createStrictMock(InternalLogger.class); expect(mockFactory.newInstance("mock")).andReturn(mock).anyTimes(); replay(mockFactory); InternalLoggerFactory.setDefaultFactory(mockFactory); } @After public void destroy() { reset(mock); InternalLoggerFactory.setDefaultFactory(oldLoggerFactory); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullDefaultFactory() { InternalLoggerFactory.setDefaultFactory(null); } @Test public void shouldReturnWrappedLogger() { assertNotSame(mock, InternalLoggerFactory.getInstance("mock")); } @Test public void testIsDebugEnabled() { expect(mock.isDebugEnabled()).andReturn(true); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); assertTrue(logger.isDebugEnabled()); verify(mock); } @Test public void testIsInfoEnabled() { expect(mock.isInfoEnabled()).andReturn(true); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); assertTrue(logger.isInfoEnabled()); verify(mock); } @Test public void testIsWarnEnabled() { expect(mock.isWarnEnabled()).andReturn(true); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); assertTrue(logger.isWarnEnabled()); verify(mock); } @Test public void testIsErrorEnabled() { expect(mock.isErrorEnabled()).andReturn(true); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); assertTrue(logger.isErrorEnabled()); verify(mock); } @Test public void testDebug() { mock.debug("a"); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.debug("a"); verify(mock); } @Test public void testDebugWithException() { mock.debug("a", e); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.debug("a", e); verify(mock); } @Test public void testInfo() { mock.info("a"); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.info("a"); verify(mock); } @Test public void testInfoWithException() { mock.info("a", e); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.info("a", e); verify(mock); } @Test public void testWarn() { mock.warn("a"); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.warn("a"); verify(mock); } @Test public void testWarnWithException() { mock.warn("a", e); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.warn("a", e); verify(mock); } @Test public void testError() { mock.error("a"); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.error("a"); verify(mock); } @Test public void testErrorWithException() { mock.error("a", e); replay(mock); InternalLogger logger = InternalLoggerFactory.getInstance("mock"); logger.error("a", e); verify(mock); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/Log4JLoggerFactoryTest.java0000644000175000017500000000303711054510506031364 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class Log4JLoggerFactoryTest { @Test public void testCreation() { InternalLogger logger = new Log4JLoggerFactory().newInstance("foo"); assertTrue(logger instanceof Log4JLogger); assertEquals("foo", logger.toString()); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/logging/JdkLoggerFactoryTest.java0000644000175000017500000000303111054510506031147 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 121 $, $Date: 2008-08-25 04:02:30 -0700 (Mon, 25 Aug 2008) $ * */ public class JdkLoggerFactoryTest { @Test public void testCreation() { InternalLogger logger = new JdkLoggerFactory().newInstance("foo"); assertTrue(logger instanceof JdkLogger); assertEquals("foo", logger.toString()); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/0000755000175000017500000000000011316313125023575 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/0000755000175000017500000000000011316313125025411 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/MapBackedSetTest.java0000644000175000017500000000702611165336702031414 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.util.Iterator; import java.util.Map; import java.util.Set; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class MapBackedSetTest { @Test @SuppressWarnings("unchecked") public void testSize() { Map map = createStrictMock(Map.class); expect(map.size()).andReturn(0); replay(map); assertEquals(0, new MapBackedSet(map).size()); verify(map); } @Test @SuppressWarnings("unchecked") public void testContains() { Map map = createStrictMock(Map.class); expect(map.containsKey("key")).andReturn(true); replay(map); assertTrue(new MapBackedSet(map).contains("key")); verify(map); } @Test @SuppressWarnings("unchecked") public void testRemove() { Map map = createStrictMock(Map.class); expect(map.remove("key")).andReturn(true); expect(map.remove("key")).andReturn(null); replay(map); assertTrue(new MapBackedSet(map).remove("key")); assertFalse(new MapBackedSet(map).remove("key")); verify(map); } @Test @SuppressWarnings("unchecked") public void testAdd() { Map map = createStrictMock(Map.class); expect(map.put("key", true)).andReturn(null); expect(map.put("key", true)).andReturn(true); replay(map); assertTrue(new MapBackedSet(map).add("key")); assertFalse(new MapBackedSet(map).add("key")); verify(map); } @Test @SuppressWarnings("unchecked") public void testClear() { Map map = createStrictMock(Map.class); map.clear(); replay(map); new MapBackedSet(map).clear(); verify(map); } @Test @SuppressWarnings("unchecked") public void testIterator() { Map map = createStrictMock(Map.class); Set keySet = createStrictMock(Set.class); Iterator keySetIterator = createStrictMock(Iterator.class); expect(map.keySet()).andReturn(keySet); expect(keySet.iterator()).andReturn(keySetIterator); replay(map); replay(keySet); replay(keySetIterator); assertSame(keySetIterator, new MapBackedSet(map).iterator()); verify(map); verify(keySet); verify(keySetIterator); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/SwitchableInputStreamTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/SwitchableInputStreamTest.j0000644000175000017500000000404611165336702032721 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import static org.easymock.EasyMock.*; import static org.easymock.classextension.EasyMock.*; import static org.junit.Assert.*; import java.io.InputStream; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class SwitchableInputStreamTest { @Test public void testSwitchStream() throws Exception { SwitchableInputStream sin = new SwitchableInputStream(); InputStream in1 = createStrictMock(InputStream.class); InputStream in2 = createStrictMock(InputStream.class); expect(in1.read()).andReturn(1); replay(in1, in2); sin.switchStream(in1); assertEquals(1, sin.read()); verify(in1, in2); reset(in1, in2); expect(in2.read()).andReturn(2); replay(in1, in2); sin.switchStream(in2); assertEquals(2, sin.read()); verify(in1, in2); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/ConversionUtilTest.java0000644000175000017500000000567211214341446032115 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1357 $, $Date: 2009-06-11 19:53:26 -0700 (Thu, 11 Jun 2009) $ * */ public class ConversionUtilTest { @Test public void testNumberToInt() { assertEquals(42, ConversionUtil.toInt(Long.valueOf(42))); } @Test public void testStringToInt() { assertEquals(42, ConversionUtil.toInt("42")); } @Test public void testBooleanToBoolean() { assertTrue(ConversionUtil.toBoolean(Boolean.TRUE)); assertFalse(ConversionUtil.toBoolean(Boolean.FALSE)); } @Test public void testNumberToBoolean() { assertTrue(ConversionUtil.toBoolean(Integer.valueOf(42))); assertFalse(ConversionUtil.toBoolean(Integer.valueOf(0))); } @Test public void testStringToBoolean() { assertTrue(ConversionUtil.toBoolean("y")); assertTrue(ConversionUtil.toBoolean("Y")); assertTrue(ConversionUtil.toBoolean("yes")); assertTrue(ConversionUtil.toBoolean("YES")); assertTrue(ConversionUtil.toBoolean("yeah")); assertTrue(ConversionUtil.toBoolean("YEAH")); assertTrue(ConversionUtil.toBoolean("t")); assertTrue(ConversionUtil.toBoolean("T")); assertTrue(ConversionUtil.toBoolean("true")); assertTrue(ConversionUtil.toBoolean("TRUE")); assertTrue(ConversionUtil.toBoolean("42")); assertFalse(ConversionUtil.toBoolean("")); assertFalse(ConversionUtil.toBoolean("n")); assertFalse(ConversionUtil.toBoolean("no")); assertFalse(ConversionUtil.toBoolean("NO")); assertFalse(ConversionUtil.toBoolean("f")); assertFalse(ConversionUtil.toBoolean("false")); assertFalse(ConversionUtil.toBoolean("FALSE")); assertFalse(ConversionUtil.toBoolean("0")); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/StringUtilTest.java0000644000175000017500000000610211214706672031231 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import static org.junit.Assert.*; import org.junit.Test; /** * Unit test for {@link StringUtil}. *

* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Daniel Bevenius (dbevenius@jboss.com) * @version $Rev$, $Date$ */ public class StringUtilTest { @Test public void stripControlCharactersObjectNull() { assertNull(StringUtil.stripControlCharacters(null)); } @Test public void stripControlCharactersNull() { assertNull(StringUtil.stripControlCharacters((String) null)); } @Test public void stripControlCharactersRightTrim() { final char controlCode = 0x0000; final Object object = "abbb" + controlCode; assertEquals(5, ((String) object).length()); final String stripped = StringUtil.stripControlCharacters(object); assertFalse(object.equals(stripped)); assertEquals(4, stripped.length()); } @Test public void stripControlCharactersLeftTrim() { final char controlCode = 0x0000; final String string = controlCode + "abbb"; assertEquals(5, string.length()); final String stripped = StringUtil.stripControlCharacters(string); assertFalse(string.equals(stripped)); assertEquals(4, stripped.length()); } @Test public void stripControlCharacters() { for (char i = 0x0000; i <= 0x001F; i ++) { assertStripped(i); } for (char i = 0x007F; i <= 0x009F; i ++) { assertStripped(i); } } private void assertStripped(final char controlCode) { final Object object = "aaa" + controlCode + "bbb"; final String stripped = StringUtil.stripControlCharacters(object); assertEquals("aaa bbb", stripped); } @Test public void stripNonControlCharacter() { final char controlCode = 0x002F; final String string = controlCode + "abbb"; final String stripped = StringUtil.stripControlCharacters(string); assertEquals("The string should be unchanged", string, stripped); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/ImmediateExecutorTest.java0000644000175000017500000000403111214341446032533 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1357 $, $Date: 2009-06-11 19:53:26 -0700 (Thu, 11 Jun 2009) $ * */ public class ImmediateExecutorTest { @Test public void shouldExecuteImmediately() { ImmediateExecutor e = ImmediateExecutor.INSTANCE; long startTime = System.nanoTime(); e.execute(new Runnable() { public void run() { long startTime = System.nanoTime(); for (;;) { try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore } if (System.nanoTime() - startTime >= 1000000000L) { break; } } } }); assertTrue(System.nanoTime() - startTime >= 1000000000L); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/StackTraceSimplifierTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/StackTraceSimplifierTest.ja0000644000175000017500000001253111213672505032645 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import static org.easymock.EasyMock.*; import static org.easymock.classextension.EasyMock.*; import static org.junit.Assert.*; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.DefaultChannelPipeline; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.util.ThreadRenamingRunnable; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ public class StackTraceSimplifierTest { @Test public void testBasicSimplification() { Exception e = new Exception(); e.setStackTrace(new StackTraceElement[] { new StackTraceElement(ChannelBuffer.class.getName(), "a", null, 1), new StackTraceElement("com.example.Foo", "b", null, 1), new StackTraceElement(SimpleChannelHandler.class.getName(), "c", null, 1), new StackTraceElement(ThreadRenamingRunnable.class.getName(), "d", null, 1), }); StackTraceSimplifier.simplify(e); StackTraceElement[] simplified = e.getStackTrace(); assertEquals(2, simplified.length); assertEquals(ChannelBuffer.class.getName(), simplified[0].getClassName()); assertEquals("com.example.Foo", simplified[1].getClassName()); } @Test public void testNestedSimplification() { Exception e1 = new Exception(); e1.setStackTrace(new StackTraceElement[] { new StackTraceElement(ChannelBuffer.class.getName(), "a", null, 1), new StackTraceElement("com.example.Foo", "b", null, 1), new StackTraceElement(SimpleChannelHandler.class.getName(), "c", null, 1), new StackTraceElement(DefaultChannelPipeline.class.getName(), "d", null, 1), new StackTraceElement(ThreadRenamingRunnable.class.getName(), "e", null, 1), }); Exception e2 = new Exception(e1); e2.setStackTrace(new StackTraceElement[] { new StackTraceElement(Channel.class.getName(), "a", null, 1), new StackTraceElement("com.example.Bar", "b", null, 1), new StackTraceElement(SimpleChannelHandler.class.getName(), "c", null, 1), new StackTraceElement(DefaultChannelPipeline.class.getName(), "d", null, 1), new StackTraceElement(ThreadRenamingRunnable.class.getName(), "e", null, 1), }); StackTraceSimplifier.simplify(e2); StackTraceElement[] simplified1 = e1.getStackTrace(); assertEquals(2, simplified1.length); assertEquals(ChannelBuffer.class.getName(), simplified1[0].getClassName()); assertEquals("com.example.Foo", simplified1[1].getClassName()); StackTraceElement[] simplified2 = e2.getStackTrace(); assertEquals(2, simplified2.length); assertEquals(Channel.class.getName(), simplified2[0].getClassName()); assertEquals("com.example.Bar", simplified2[1].getClassName()); } @Test public void testNettyBugDetection() { Exception e = new Exception(); e.setStackTrace(new StackTraceElement[] { new StackTraceElement(DefaultChannelPipeline.class.getName(), "a", null, 1), new StackTraceElement(ChannelBuffer.class.getName(), "a", null, 1), new StackTraceElement("com.example.Foo", "b", null, 1), new StackTraceElement(SimpleChannelHandler.class.getName(), "c", null, 1), new StackTraceElement(ThreadRenamingRunnable.class.getName(), "d", null, 1), }); StackTraceSimplifier.simplify(e); StackTraceElement[] simplified = e.getStackTrace(); assertEquals(5, simplified.length); } @Test public void testEmptyStackTrace() { Exception e = new Exception(); e.setStackTrace(new StackTraceElement[0]); StackTraceSimplifier.simplify(e); assertEquals(0, e.getStackTrace().length); } @Test public void testNullStackTrace() { Exception e = createNiceMock(Exception.class); expect(e.getStackTrace()).andReturn(null).anyTimes(); replay(e); StackTraceSimplifier.simplify(e); assertNull(e.getStackTrace()); verify(e); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/internal/MapUtilTest.java0000644000175000017500000000735711165336702030513 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import static org.junit.Assert.*; import java.util.AbstractMap; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Set; import java.util.logging.Level; import java.util.logging.Logger; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class MapUtilTest { static { Logger logger = Logger.getLogger(MapUtil.class.getName()); logger.setLevel(Level.ALL); } @Test public void shouldReturnTrueIfLinkedHashMap() { assertTrue(MapUtil.isOrderedMap(new LinkedHashMap())); } @Test public void shouldReturnTrueIfMapImplementsOrderedMap() { assertTrue(MapUtil.isOrderedMap(new DummyOrderedMap())); } @Test public void shouldReturnFalseIfMapHasNoDefaultConstructor() { assertFalse(MapUtil.isOrderedMap( new MapWithoutDefaultConstructor( new HashMap()))); } @Test public void shouldReturnFalseIfMapIsNotOrdered() { assertFalse(MapUtil.isOrderedMap(new HashMap())); } @Test public void shouldReturnTrueIfMapIsOrdered() { assertTrue(MapUtil.isOrderedMap(new UnknownOrderedMap())); } interface OrderedMap { // A tag interface } static class DummyOrderedMap extends AbstractMap implements OrderedMap { private final Map map = new HashMap(); @Override public Set> entrySet() { return map.entrySet(); } } static class MapWithoutDefaultConstructor extends AbstractMap { private final Map map; MapWithoutDefaultConstructor(Map map) { this.map = map; } @Override public Set> entrySet() { return map.entrySet(); } } static class UnknownOrderedMap extends AbstractMap { private final Map map = new LinkedHashMap(); @Override public boolean containsKey(Object key) { return map.containsKey(key); } @Override public int size() { return map.size(); } @Override public V put(K key, V value) { return map.put(key, value); } @Override public Set keySet() { return map.keySet(); } @Override public Set> entrySet() { return map.entrySet(); } } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/TestUtil.java0000644000175000017500000000556211165336702026235 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import java.net.InetAddress; import java.net.UnknownHostException; import org.jboss.netty.util.internal.ConversionUtil; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ @org.junit.Ignore public final class TestUtil { private static final boolean ENABLED; private static final InetAddress LOCALHOST; static { String value = System.getProperty("exclude-timing-tests", "false").trim(); if (value.length() == 0) { value = "true"; } ENABLED = !ConversionUtil.toBoolean(value); if (!ENABLED) { System.err.println("Timing tests will be disabled as requested."); } InetAddress localhost = null; try { localhost = InetAddress.getLocalHost(); } catch (UnknownHostException e) { try { localhost = InetAddress.getByAddress(new byte[] { 127, 0, 0, 1 }); } catch (UnknownHostException e1) { try { localhost = InetAddress.getByAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1 }); } catch (UnknownHostException e2) { System.err.println("Failed to get the localhost."); e2.printStackTrace(); } } } LOCALHOST = localhost; } public static boolean isTimingTestEnabled() { return ENABLED; } public static InetAddress getLocalHost() { // We cache this because some machine takes almost forever to return // from InetAddress.getLocalHost(). I think it's due to the incorrect // /etc/hosts or /etc/resolve.conf. return LOCALHOST; } private TestUtil() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/DummyHandler.java0000644000175000017500000000165411060447260027043 0ustar deckerdeckerpackage org.jboss.netty.util; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelUpstreamHandler; /** * A dummy handler for a testing purpose. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 254 $, $Date: 2008-09-06 02:34:40 -0700 (Sat, 06 Sep 2008) $ */ @ChannelPipelineCoverage("all") public class DummyHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler { public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { ctx.sendUpstream(e); } public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { ctx.sendDownstream(e); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/DebugUtilTest.java0000644000175000017500000000526711054445641027206 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import static org.junit.Assert.*; import java.security.Permission; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 116 $, $Date: 2008-08-24 23:05:21 -0700 (Sun, 24 Aug 2008) $ * */ public class DebugUtilTest { public void shouldReturnFalseIfPropertyIsNotSet() { assertFalse(DebugUtil.isDebugEnabled()); } @Test public void shouldReturnTrueInDebugMode() { System.setProperty("org.jboss.netty.debug", "true"); assertTrue(DebugUtil.isDebugEnabled()); } @Test public void shouldReturnFalseInNonDebugMode() { System.setProperty("org.jboss.netty.debug", "false"); assertFalse(DebugUtil.isDebugEnabled()); } @Test public void shouldNotBombOutWhenSecurityManagerIsInAction() { System.setProperty("org.jboss.netty.debug", "true"); System.setSecurityManager(new SecurityManager() { @Override public void checkPropertyAccess(String key) { throw new SecurityException(); } @Override public void checkPermission(Permission perm, Object context) { // Allow } @Override public void checkPermission(Permission perm) { // Allow } }); try { assertFalse(DebugUtil.isDebugEnabled()); } finally { System.setSecurityManager(null); } } @Before @After public void cleanup() { System.clearProperty("org.jboss.netty.debug"); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/util/ThreadRenamingRunnableTest.java0000644000175000017500000000677511213672505031704 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.security.Permission; import java.util.concurrent.Executor; import org.jboss.netty.util.internal.ImmediateExecutor; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ public class ThreadRenamingRunnableTest { @Test(expected = NullPointerException.class) public void shouldNotAllowNullName() throws Exception { new ThreadRenamingRunnable(createMock(Runnable.class), null); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullRunnable() throws Exception { new ThreadRenamingRunnable(null, "foo"); } @Test public void testWithoutSecurityManager() throws Exception { final String oldThreadName = Thread.currentThread().getName(); Executor e = ImmediateExecutor.INSTANCE; e.execute(new ThreadRenamingRunnable( new Runnable() { public void run() { assertEquals("foo", Thread.currentThread().getName()); assertFalse(oldThreadName.equals(Thread.currentThread().getName())); } }, "foo")); assertEquals(oldThreadName, Thread.currentThread().getName()); } @Test public void testWithSecurityManager() throws Exception { final String oldThreadName = Thread.currentThread().getName(); Executor e = ImmediateExecutor.INSTANCE; System.setSecurityManager(new SecurityManager() { @Override public void checkAccess(Thread t) { throw new SecurityException(); } @Override public void checkPermission(Permission perm, Object context) { // Allow } @Override public void checkPermission(Permission perm) { // Allow } }); try { e.execute(new ThreadRenamingRunnable( new Runnable() { public void run() { assertEquals(oldThreadName, Thread.currentThread().getName()); } }, "foo")); } finally { System.setSecurityManager(null); assertEquals(oldThreadName, Thread.currentThread().getName()); } } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/0000755000175000017500000000000011316313123024633 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/BootstrapTest.java0000644000175000017500000002106011150053476030322 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; import java.util.Map.Entry; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.util.DummyHandler; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 931 $, $Date: 2009-02-21 11:34:22 -0800 (Sat, 21 Feb 2009) $ * */ public class BootstrapTest { @Test(expected = IllegalStateException.class) public void shouldNotReturnNullFactory() { new Bootstrap().getFactory(); } @Test(expected = IllegalStateException.class) public void shouldNotAllowInitialFactoryToChange() { new Bootstrap(createMock(ChannelFactory.class)).setFactory(createMock(ChannelFactory.class)); } @Test public void shouldNotAllowFactoryToChangeMoreThanOnce() { Bootstrap b = new Bootstrap(); ChannelFactory f = createMock(ChannelFactory.class); b.setFactory(f); assertSame(f, b.getFactory()); try { b.setFactory(createMock(ChannelFactory.class)); fail(); } catch (IllegalStateException e) { // Success. } } @Test(expected = NullPointerException.class) public void shouldNotAllowNullFactory() { new Bootstrap().setFactory(null); } @Test public void shouldHaveNonNullInitialPipeline() { assertNotNull(new Bootstrap().getPipeline()); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullPipeline() { new Bootstrap().setPipeline(null); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullPipelineMap() { new Bootstrap().setPipelineAsMap(null); } @Test public void shouldHaveNonNullInitialPipelineFactory() { assertNotNull(new Bootstrap().getPipelineFactory()); } @Test public void shouldUpdatePipelineFactoryIfPipelineIsSet() { Bootstrap b = new Bootstrap(); ChannelPipelineFactory oldPipelineFactory = b.getPipelineFactory(); b.setPipeline(createMock(ChannelPipeline.class)); assertNotSame(oldPipelineFactory, b.getPipelineFactory()); } @Test(expected = IllegalStateException.class) public void shouldNotReturnPipelineWhenPipelineFactoryIsSetByUser() { Bootstrap b = new Bootstrap(); b.setPipelineFactory(createMock(ChannelPipelineFactory.class)); b.getPipeline(); } @Test(expected = IllegalStateException.class) public void shouldNotReturnPipelineMapWhenPipelineFactoryIsSetByUser() { Bootstrap b = new Bootstrap(); b.setPipelineFactory(createMock(ChannelPipelineFactory.class)); b.getPipelineAsMap(); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullPipelineFactory() { new Bootstrap().setPipelineFactory(null); } @Test public void shouldHaveInitialEmptyPipelineMap() { assertTrue(new Bootstrap().getPipelineAsMap().isEmpty()); } @Test public void shouldReturnOrderedPipelineMap() { Bootstrap b = new Bootstrap(); ChannelPipeline p = b.getPipeline(); p.addLast("a", new DummyHandler()); p.addLast("b", new DummyHandler()); p.addLast("c", new DummyHandler()); p.addLast("d", new DummyHandler()); Iterator> m = b.getPipelineAsMap().entrySet().iterator(); Entry e; e = m.next(); assertEquals("a", e.getKey()); assertSame(p.get("a"), e.getValue()); e = m.next(); assertEquals("b", e.getKey()); assertSame(p.get("b"), e.getValue()); e = m.next(); assertEquals("c", e.getKey()); assertSame(p.get("c"), e.getValue()); e = m.next(); assertEquals("d", e.getKey()); assertSame(p.get("d"), e.getValue()); assertFalse(m.hasNext()); } @Test(expected = IllegalArgumentException.class) public void shouldNotAllowUnorderedPipelineMap() { Map m = new HashMap(); m.put("a", new DummyHandler()); m.put("b", new DummyHandler()); m.put("c", new DummyHandler()); m.put("d", new DummyHandler()); Bootstrap b = new Bootstrap(); b.setPipelineAsMap(m); } @Test public void shouldHaveOrderedPipelineWhenSetFromMap() { Map m = new LinkedHashMap(); m.put("a", new DummyHandler()); m.put("b", new DummyHandler()); m.put("c", new DummyHandler()); m.put("d", new DummyHandler()); Bootstrap b = new Bootstrap(); b.setPipelineAsMap(m); ChannelPipeline p = b.getPipeline(); assertSame(p.getFirst(), m.get("a")); assertEquals("a", p.getContext(p.getFirst()).getName()); p.removeFirst(); assertSame(p.getFirst(), m.get("b")); assertEquals("b", p.getContext(p.getFirst()).getName()); p.removeFirst(); assertSame(p.getFirst(), m.get("c")); assertEquals("c", p.getContext(p.getFirst()).getName()); p.removeFirst(); assertSame(p.getFirst(), m.get("d")); assertEquals("d", p.getContext(p.getFirst()).getName()); p.removeFirst(); try { p.removeFirst(); fail(); } catch (NoSuchElementException e) { // Success. } } @Test public void shouldHaveInitialEmptyOptionMap() { assertTrue(new Bootstrap().getOptions().isEmpty()); } @Test public void shouldUpdateOptionMapAsRequested1() { Bootstrap b = new Bootstrap(); b.setOption("s", "x"); b.setOption("b", true); b.setOption("i", 42); Map o = b.getOptions(); assertEquals(3, o.size()); assertEquals("x", o.get("s")); assertEquals(true, o.get("b")); assertEquals(42, o.get("i")); } @Test public void shouldUpdateOptionMapAsRequested2() { Bootstrap b = new Bootstrap(); Map o1 = new HashMap(); o1.put("s", "x"); o1.put("b", true); o1.put("i", 42); b.setOptions(o1); Map o2 = b.getOptions(); assertEquals(3, o2.size()); assertEquals("x", o2.get("s")); assertEquals(true, o2.get("b")); assertEquals(42, o2.get("i")); assertNotSame(o1, o2); assertEquals(o1, o2); } @Test public void shouldRemoveOptionIfValueIsNull() { Bootstrap b = new Bootstrap(); b.setOption("s", "x"); assertEquals("x", b.getOption("s")); b.setOption("s", null); assertNull(b.getOption("s")); assertTrue(b.getOptions().isEmpty()); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullOptionKeyOnGet() { new Bootstrap().getOption(null); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullOptionKeyOnSet() { new Bootstrap().setOption(null, "x"); } @Test(expected = NullPointerException.class) public void shouldNotAllowNullOptionMap() { new Bootstrap().setOptions(null); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/AbstractSocketServerBootstrapTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/AbstractSocketServerBootstrapTe0000644000175000017500000001742711172030314033061 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelPipelineException; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChildChannelStateEvent; import org.jboss.netty.channel.ServerChannelFactory; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.util.DummyHandler; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public abstract class AbstractSocketServerBootstrapTest { private static final boolean BUFSIZE_MODIFIABLE; static { boolean bufSizeModifiable = true; Socket s = new Socket(); try { s.setReceiveBufferSize(1234); try { if (s.getReceiveBufferSize() != 1234) { throw new IllegalStateException(); } } catch (Exception e) { bufSizeModifiable = false; System.err.println( "Socket.getReceiveBufferSize() does not work: " + e); } } catch (Exception e) { bufSizeModifiable = false; System.err.println( "Socket.setReceiveBufferSize() does not work: " + e); } finally { BUFSIZE_MODIFIABLE = bufSizeModifiable; try { s.close(); } catch (IOException e) { // Ignore. } } } private static ExecutorService executor; @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor); @Test(timeout = 30000, expected = ChannelException.class) public void testFailedBindAttempt() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap(); bootstrap.setFactory(newServerSocketChannelFactory(executor)); bootstrap.setOption("localAddress", new InetSocketAddress("255.255.255.255", 0)); bootstrap.bind(); } @Test(timeout = 30000) public void testSuccessfulBindAttempt() throws Exception { ServerBootstrap bootstrap = new ServerBootstrap( newServerSocketChannelFactory(executor)); bootstrap.setParentHandler(new ParentChannelHandler()); bootstrap.setOption("localAddress", new InetSocketAddress(0)); bootstrap.setOption("child.receiveBufferSize", 9753); bootstrap.setOption("child.sendBufferSize", 8642); bootstrap.getPipeline().addLast("dummy", new DummyHandler()); Channel channel = bootstrap.bind(); ParentChannelHandler pch = channel.getPipeline().get(ParentChannelHandler.class); Socket socket = null; try { socket = new Socket( TestUtil.getLocalHost(), ((InetSocketAddress) channel.getLocalAddress()).getPort()); // Wait until the connection is open in the server side. while (pch.child == null) { Thread.yield(); } SocketChannelConfig cfg = (SocketChannelConfig) pch.child.getConfig(); if (BUFSIZE_MODIFIABLE) { assertEquals(9753, cfg.getReceiveBufferSize()); assertEquals(8642, cfg.getSendBufferSize()); } } finally { if (socket != null) { try { socket.close(); } catch (IOException e) { // Ignore. } } channel.close().awaitUninterruptibly(); } // Wait until the child connection is closed in the client side. // We do not use Channel.close() to make sure it is closed automatically. while (pch.child.isOpen()) { try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore } } // Wait until all child events are fired. while (pch.result.length() < 2) { try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore } } // Confirm the received child events. assertEquals("12", pch.result.toString()); } @Test(expected = ChannelPipelineException.class) public void testFailedPipelineInitialization() throws Exception { ClientBootstrap bootstrap = new ClientBootstrap(createMock(ChannelFactory.class)); ChannelPipelineFactory pipelineFactory = createMock(ChannelPipelineFactory.class); bootstrap.setPipelineFactory(pipelineFactory); expect(pipelineFactory.getPipeline()).andThrow(new ChannelPipelineException()); replay(pipelineFactory); bootstrap.connect(new InetSocketAddress(TestUtil.getLocalHost(), 1)); } @Test(expected = IllegalStateException.class) public void shouldHaveLocalAddressOption() { new ServerBootstrap(createMock(ServerChannelFactory.class)).bind(); } @Test(expected = NullPointerException.class) public void shouldDisallowNullLocalAddressParameter() { new ServerBootstrap(createMock(ServerChannelFactory.class)).bind(null); } @ChannelPipelineCoverage("all") private static class ParentChannelHandler extends SimpleChannelUpstreamHandler { volatile Channel child; final StringBuffer result = new StringBuffer(); ParentChannelHandler() { super(); } @Override public void childChannelClosed(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { result.append('2'); } @Override public void childChannelOpen(ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { child = e.getChildChannel(); result.append('1'); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/NioSocketServerBootstrapTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/NioSocketServerBootstrapTest.ja0000644000175000017500000000320611055025234032776 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 143 $, $Date: 2008-08-26 09:09:00 -0700 (Tue, 26 Aug 2008) $ * */ public class NioSocketServerBootstrapTest extends AbstractSocketServerBootstrapTest { @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/OioSocketServerBootstrapTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/OioSocketServerBootstrapTest.ja0000644000175000017500000000320611055025234032777 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 143 $, $Date: 2008-08-26 09:09:00 -0700 (Tue, 26 Aug 2008) $ * */ public class OioSocketServerBootstrapTest extends AbstractSocketServerBootstrapTest { @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/OioSocketClientBootstrapTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/OioSocketClientBootstrapTest.ja0000644000175000017500000000317411055025234032753 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 143 $, $Date: 2008-08-26 09:09:00 -0700 (Tue, 26 Aug 2008) $ * */ public class OioSocketClientBootstrapTest extends AbstractSocketClientBootstrapTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/NioSocketClientBootstrapTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/NioSocketClientBootstrapTest.ja0000644000175000017500000000320611055025234032746 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 143 $, $Date: 2008-08-26 09:09:00 -0700 (Tue, 26 Aug 2008) $ * */ public class NioSocketClientBootstrapTest extends AbstractSocketClientBootstrapTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/AbstractSocketClientBootstrapTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/bootstrap/AbstractSocketClientBootstrapTe0000644000175000017500000001502111205435433033025 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import static org.easymock.EasyMock.*; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipelineException; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.util.DummyHandler; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1297 $, $Date: 2009-05-21 22:41:47 -0700 (Thu, 21 May 2009) $ * */ public abstract class AbstractSocketClientBootstrapTest { private static ExecutorService executor; @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract ChannelFactory newClientSocketChannelFactory(Executor executor); @Test(timeout = 10000) public void testFailedConnectionAttempt() throws Exception { ClientBootstrap bootstrap = new ClientBootstrap(); bootstrap.setFactory(newClientSocketChannelFactory(executor)); bootstrap.getPipeline().addLast("dummy", new DummyHandler()); bootstrap.setOption("remoteAddress", new InetSocketAddress("255.255.255.255", 1)); ChannelFuture future = bootstrap.connect(); future.awaitUninterruptibly(); assertFalse(future.isSuccess()); assertTrue(future.getCause() instanceof IOException); } @Test(timeout = 10000) public void testSuccessfulConnectionAttempt() throws Throwable { ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(0)); try { serverSocket.configureBlocking(false); ClientBootstrap bootstrap = new ClientBootstrap(newClientSocketChannelFactory(executor)); bootstrap.getPipeline().addLast("dummy", new DummyHandler()); bootstrap.setOption( "remoteAddress", new InetSocketAddress( TestUtil.getLocalHost(), serverSocket.socket().getLocalPort())); ChannelFuture future = bootstrap.connect(); serverSocket.accept(); future.awaitUninterruptibly(); if (future.getCause() != null) { throw future.getCause(); } assertTrue(future.isSuccess()); future.getChannel().close().awaitUninterruptibly(); } finally { try { serverSocket.close(); } catch (IOException e) { // Ignore. } } } @Test(timeout = 10000) public void testSuccessfulConnectionAttemptWithLocalAddress() throws Throwable { ServerSocketChannel serverSocket = ServerSocketChannel.open(); serverSocket.socket().bind(new InetSocketAddress(0)); try { serverSocket.configureBlocking(false); ClientBootstrap bootstrap = new ClientBootstrap(newClientSocketChannelFactory(executor)); bootstrap.getPipeline().addLast("dummy", new DummyHandler()); bootstrap.setOption( "remoteAddress", new InetSocketAddress( TestUtil.getLocalHost(), serverSocket.socket().getLocalPort())); bootstrap.setOption("localAddress", new InetSocketAddress(0)); ChannelFuture future = bootstrap.connect(); serverSocket.accept(); future.awaitUninterruptibly(); if (future.getCause() != null) { throw future.getCause(); } assertTrue(future.isSuccess()); future.getChannel().close().awaitUninterruptibly(); } finally { try { serverSocket.close(); } catch (IOException e) { // Ignore. } } } @Test(expected = ChannelPipelineException.class) public void testFailedPipelineInitialization() throws Exception { ClientBootstrap bootstrap = new ClientBootstrap(createMock(ChannelFactory.class)); ChannelPipelineFactory pipelineFactory = createMock(ChannelPipelineFactory.class); bootstrap.setPipelineFactory(pipelineFactory); expect(pipelineFactory.getPipeline()).andThrow(new ChannelPipelineException()); replay(pipelineFactory); bootstrap.connect(new InetSocketAddress(TestUtil.getLocalHost(), 1)); } @Test(expected = IllegalStateException.class) public void shouldHaveRemoteAddressOption() { new ClientBootstrap(createMock(ChannelFactory.class)).connect(); } @Test(expected = NullPointerException.class) public void shouldDisallowNullRemoteAddressParameter1() { new ClientBootstrap(createMock(ChannelFactory.class)).connect(null); } @Test(expected = NullPointerException.class) public void shouldDisallowNullRemoteAddressParameter2() { new ClientBootstrap(createMock(ChannelFactory.class)).connect(null, null); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/0000755000175000017500000000000011316313122024066 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/DuplicateChannelBufferTest.java0000644000175000017500000000355011057746110032142 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 237 $, $Date: 2008-09-04 04:53:44 -0700 (Thu, 04 Sep 2008) $ */ public class DuplicateChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = new DuplicatedChannelBuffer(ChannelBuffers.buffer(length)); assertEquals(0, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new DuplicatedChannelBuffer(null); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/ChannelBufferStreamTest.java0000644000175000017500000001251411055177625031472 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import java.io.EOFException; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 145 $, $Date: 2008-08-27 00:17:41 -0700 (Wed, 27 Aug 2008) $ * */ public class ChannelBufferStreamTest { @Test public void testAll() throws Exception { ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); try { new ChannelBufferOutputStream(null); fail(); } catch (NullPointerException e) { // Expected } ChannelBufferOutputStream out = new ChannelBufferOutputStream(buf); assertSame(buf, out.buffer()); out.writeBoolean(true); out.writeBoolean(false); out.writeByte(42); out.writeByte(224); out.writeBytes("Hello, World!"); out.writeChars("Hello, World"); out.writeChar('!'); out.writeDouble(42.0); out.writeFloat(42.0f); out.writeInt(42); out.writeLong(42); out.writeShort(42); out.writeShort(49152); out.writeUTF("Hello, World!"); out.writeBytes("The first line\r\r\n"); out.write(new byte[0]); out.write(new byte[] { 1, 2, 3, 4 }); out.write(new byte[] { 1, 3, 3, 4 }, 0, 0); out.close(); try { new ChannelBufferInputStream(null); fail(); } catch (NullPointerException e) { // Expected } try { new ChannelBufferInputStream(null, 0); fail(); } catch (NullPointerException e) { // Expected } try { new ChannelBufferInputStream(buf, -1); } catch (IllegalArgumentException e) { // Expected } try { new ChannelBufferInputStream(buf, buf.capacity() + 1); } catch (IndexOutOfBoundsException e) { // Expected } ChannelBufferInputStream in = new ChannelBufferInputStream(buf); assertTrue(in.markSupported()); in.mark(Integer.MAX_VALUE); assertEquals(buf.writerIndex(), in.skip(Long.MAX_VALUE)); assertFalse(buf.readable()); in.reset(); assertEquals(0, buf.readerIndex()); assertEquals(4, in.skip(4)); assertEquals(4, buf.readerIndex()); in.reset(); assertTrue(in.readBoolean()); assertFalse(in.readBoolean()); assertEquals(42, in.readByte()); assertEquals(224, in.readUnsignedByte()); byte[] tmp = new byte[13]; in.readFully(tmp); assertEquals("Hello, World!", new String(tmp, "ISO-8859-1")); assertEquals('H', in.readChar()); assertEquals('e', in.readChar()); assertEquals('l', in.readChar()); assertEquals('l', in.readChar()); assertEquals('o', in.readChar()); assertEquals(',', in.readChar()); assertEquals(' ', in.readChar()); assertEquals('W', in.readChar()); assertEquals('o', in.readChar()); assertEquals('r', in.readChar()); assertEquals('l', in.readChar()); assertEquals('d', in.readChar()); assertEquals('!', in.readChar()); assertEquals(42.0, in.readDouble(), 0.0); assertEquals(42.0f, in.readFloat(), 0.0); assertEquals(42, in.readInt()); assertEquals(42, in.readLong()); assertEquals(42, in.readShort()); assertEquals(49152, in.readUnsignedShort()); assertEquals("Hello, World!", in.readUTF()); assertEquals("The first line", in.readLine()); assertEquals(4, in.read(tmp)); assertEquals(1, tmp[0]); assertEquals(2, tmp[1]); assertEquals(3, tmp[2]); assertEquals(4, tmp[3]); assertEquals(-1, in.read()); assertEquals(-1, in.read(tmp)); try { in.readByte(); fail(); } catch (EOFException e) { // Expected } try { in.readFully(tmp, 0, -1); fail(); } catch (IndexOutOfBoundsException e) { // Expected } try { in.readFully(tmp); fail(); } catch (EOFException e) { // Expected } in.close(); assertEquals(buf.readerIndex(), in.readBytes()); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/BigEndianDirectChannelBufferTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/BigEndianDirectChannelBufferTest.j0000644000175000017500000000342511210153441032502 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import java.nio.ByteOrder; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1311 $, $Date: 2009-05-29 23:50:09 -0700 (Fri, 29 May 2009) $ */ public class BigEndianDirectChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.directBuffer(ByteOrder.BIG_ENDIAN, length); assertSame(ByteOrder.BIG_ENDIAN, buffer.order()); assertEquals(0, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/AbstractChannelBufferTest.java0000644000175000017500000016627611216122153032002 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.jboss.netty.buffer.ChannelBuffers.*; import static org.junit.Assert.*; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.nio.ByteBuffer; import java.nio.charset.UnsupportedCharsetException; import java.util.Arrays; import java.util.HashSet; import java.util.NoSuchElementException; import java.util.Random; import java.util.Set; import org.junit.After; import org.junit.Before; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1399 $, $Date: 2009-06-17 01:08:11 -0700 (Wed, 17 Jun 2009) $ */ public abstract class AbstractChannelBufferTest { private static final int CAPACITY = 4096; // Must be even private static final int BLOCK_SIZE = 128; private long seed; private Random random; private ChannelBuffer buffer; protected abstract ChannelBuffer newBuffer(int capacity); protected abstract ChannelBuffer[] components(); @Before public void init() { buffer = newBuffer(CAPACITY); seed = System.currentTimeMillis(); random = new Random(seed); } @After public void dispose() { buffer = null; } @Test public void initialState() { assertEquals(CAPACITY, buffer.capacity()); assertEquals(0, buffer.readerIndex()); } @Test(expected=IndexOutOfBoundsException.class) public void readerIndexBoundaryCheck1() { try { buffer.writerIndex(0); } catch (IndexOutOfBoundsException e) { fail(); } buffer.readerIndex(-1); } @Test(expected=IndexOutOfBoundsException.class) public void readerIndexBoundaryCheck2() { try { buffer.writerIndex(buffer.capacity()); } catch (IndexOutOfBoundsException e) { fail(); } buffer.readerIndex(buffer.capacity() + 1); } @Test(expected=IndexOutOfBoundsException.class) public void readerIndexBoundaryCheck3() { try { buffer.writerIndex(CAPACITY / 2); } catch (IndexOutOfBoundsException e) { fail(); } buffer.readerIndex(CAPACITY * 3 / 2); } @Test public void readerIndexBoundaryCheck4() { buffer.writerIndex(0); buffer.readerIndex(0); buffer.writerIndex(buffer.capacity()); buffer.readerIndex(buffer.capacity()); } @Test(expected=IndexOutOfBoundsException.class) public void writerIndexBoundaryCheck1() { buffer.writerIndex(-1); } @Test(expected=IndexOutOfBoundsException.class) public void writerIndexBoundaryCheck2() { try { buffer.writerIndex(CAPACITY); buffer.readerIndex(CAPACITY); } catch (IndexOutOfBoundsException e) { fail(); } buffer.writerIndex(buffer.capacity() + 1); } @Test(expected=IndexOutOfBoundsException.class) public void writerIndexBoundaryCheck3() { try { buffer.writerIndex(CAPACITY); buffer.readerIndex(CAPACITY / 2); } catch (IndexOutOfBoundsException e) { fail(); } buffer.writerIndex(CAPACITY / 4); } @Test public void writerIndexBoundaryCheck4() { buffer.writerIndex(0); buffer.readerIndex(0); buffer.writerIndex(CAPACITY); } @Test(expected=IndexOutOfBoundsException.class) public void getByteBoundaryCheck1() { buffer.getByte(-1); } @Test(expected=IndexOutOfBoundsException.class) public void getByteBoundaryCheck2() { buffer.getByte(buffer.capacity()); } @Test(expected=IndexOutOfBoundsException.class) public void getShortBoundaryCheck1() { buffer.getShort(-1); } @Test(expected=IndexOutOfBoundsException.class) public void getShortBoundaryCheck2() { buffer.getShort(buffer.capacity() - 1); } @Test(expected=IndexOutOfBoundsException.class) public void getMediumBoundaryCheck1() { buffer.getMedium(-1); } @Test(expected=IndexOutOfBoundsException.class) public void getMediumBoundaryCheck2() { buffer.getMedium(buffer.capacity() - 2); } @Test(expected=IndexOutOfBoundsException.class) public void getIntBoundaryCheck1() { buffer.getInt(-1); } @Test(expected=IndexOutOfBoundsException.class) public void getIntBoundaryCheck2() { buffer.getInt(buffer.capacity() - 3); } @Test(expected=IndexOutOfBoundsException.class) public void getLongBoundaryCheck1() { buffer.getLong(-1); } @Test(expected=IndexOutOfBoundsException.class) public void getLongBoundaryCheck2() { buffer.getLong(buffer.capacity() - 7); } @Test(expected=IndexOutOfBoundsException.class) public void getByteArrayBoundaryCheck1() { buffer.getBytes(-1, new byte[0]); } @Test(expected=IndexOutOfBoundsException.class) public void getByteArrayBoundaryCheck2() { buffer.getBytes(-1, new byte[0], 0, 0); } @Test public void getByteArrayBoundaryCheck3() { byte[] dst = new byte[4]; buffer.setInt(0, 0x01020304); try { buffer.getBytes(0, dst, -1, 4); fail(); } catch (IndexOutOfBoundsException e) { // Success } // No partial copy is expected. assertEquals(0, dst[0]); assertEquals(0, dst[1]); assertEquals(0, dst[2]); assertEquals(0, dst[3]); } @Test public void getByteArrayBoundaryCheck4() { byte[] dst = new byte[4]; buffer.setInt(0, 0x01020304); try { buffer.getBytes(0, dst, 1, 4); fail(); } catch (IndexOutOfBoundsException e) { // Success } // No partial copy is expected. assertEquals(0, dst[0]); assertEquals(0, dst[1]); assertEquals(0, dst[2]); assertEquals(0, dst[3]); } @Test(expected=IndexOutOfBoundsException.class) public void getByteBufferBoundaryCheck() { buffer.getBytes(-1, ByteBuffer.allocate(0)); } @Test(expected=IndexOutOfBoundsException.class) public void copyBoundaryCheck1() { buffer.copy(-1, 0); } @Test(expected=IndexOutOfBoundsException.class) public void copyBoundaryCheck2() { buffer.copy(0, buffer.capacity() + 1); } @Test(expected=IndexOutOfBoundsException.class) public void copyBoundaryCheck3() { buffer.copy(buffer.capacity() + 1, 0); } @Test(expected=IndexOutOfBoundsException.class) public void copyBoundaryCheck4() { buffer.copy(buffer.capacity(), 1); } @Test(expected=IndexOutOfBoundsException.class) public void setIndexBoundaryCheck1() { buffer.setIndex(-1, CAPACITY); } @Test(expected=IndexOutOfBoundsException.class) public void setIndexBoundaryCheck2() { buffer.setIndex(CAPACITY / 2, CAPACITY / 4); } @Test(expected=IndexOutOfBoundsException.class) public void setIndexBoundaryCheck3() { buffer.setIndex(0, CAPACITY + 1); } @Test public void getByteBufferState() { ByteBuffer dst = ByteBuffer.allocate(4); dst.position(1); dst.limit(3); buffer.setByte(0, (byte) 1); buffer.setByte(1, (byte) 2); buffer.setByte(2, (byte) 3); buffer.setByte(3, (byte) 4); buffer.getBytes(1, dst); assertEquals(3, dst.position()); assertEquals(3, dst.limit()); dst.clear(); assertEquals(0, dst.get(0)); assertEquals(2, dst.get(1)); assertEquals(3, dst.get(2)); assertEquals(0, dst.get(3)); } @Test(expected=IndexOutOfBoundsException.class) public void getDirectByteBufferBoundaryCheck() { buffer.getBytes(-1, ByteBuffer.allocateDirect(0)); } @Test public void getDirectByteBufferState() { ByteBuffer dst = ByteBuffer.allocateDirect(4); dst.position(1); dst.limit(3); buffer.setByte(0, (byte) 1); buffer.setByte(1, (byte) 2); buffer.setByte(2, (byte) 3); buffer.setByte(3, (byte) 4); buffer.getBytes(1, dst); assertEquals(3, dst.position()); assertEquals(3, dst.limit()); dst.clear(); assertEquals(0, dst.get(0)); assertEquals(2, dst.get(1)); assertEquals(3, dst.get(2)); assertEquals(0, dst.get(3)); } @Test public void testRandomByteAccess() { for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); buffer.setByte(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); assertEquals(value, buffer.getByte(i)); } } @Test public void testRandomUnsignedByteAccess() { for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); buffer.setByte(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i ++) { int value = random.nextInt() & 0xFF; assertEquals(value, buffer.getUnsignedByte(i)); } } @Test public void testRandomShortAccess() { for (int i = 0; i < buffer.capacity() - 1; i += 2) { short value = (short) random.nextInt(); buffer.setShort(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 1; i += 2) { short value = (short) random.nextInt(); assertEquals(value, buffer.getShort(i)); } } @Test public void testRandomUnsignedShortAccess() { for (int i = 0; i < buffer.capacity() - 1; i += 2) { short value = (short) random.nextInt(); buffer.setShort(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 1; i += 2) { int value = random.nextInt() & 0xFFFF; assertEquals(value, buffer.getUnsignedShort(i)); } } @Test public void testRandomMediumAccess() { for (int i = 0; i < buffer.capacity() - 2; i += 3) { int value = random.nextInt(); buffer.setMedium(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 2; i += 3) { int value = random.nextInt() << 8 >> 8; assertEquals(value, buffer.getMedium(i)); } } @Test public void testRandomUnsignedMediumAccess() { for (int i = 0; i < buffer.capacity() - 2; i += 3) { int value = random.nextInt(); buffer.setMedium(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 2; i += 3) { int value = random.nextInt() & 0x00FFFFFF; assertEquals(value, buffer.getUnsignedMedium(i)); } } @Test public void testRandomIntAccess() { for (int i = 0; i < buffer.capacity() - 3; i += 4) { int value = random.nextInt(); buffer.setInt(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 3; i += 4) { int value = random.nextInt(); assertEquals(value, buffer.getInt(i)); } } @Test public void testRandomUnsignedIntAccess() { for (int i = 0; i < buffer.capacity() - 3; i += 4) { int value = random.nextInt(); buffer.setInt(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 3; i += 4) { long value = random.nextInt() & 0xFFFFFFFFL; assertEquals(value, buffer.getUnsignedInt(i)); } } @Test public void testRandomLongAccess() { for (int i = 0; i < buffer.capacity() - 7; i += 8) { long value = random.nextLong(); buffer.setLong(i, value); } random.setSeed(seed); for (int i = 0; i < buffer.capacity() - 7; i += 8) { long value = random.nextLong(); assertEquals(value, buffer.getLong(i)); } } @Test public void testSetZero() { buffer.clear(); while (buffer.writable()) { buffer.writeByte((byte) 0xFF); } for (int i = 0; i < buffer.capacity();) { int length = Math.min(buffer.capacity() - i, random.nextInt(32)); buffer.setZero(i, length); i += length; } for (int i = 0; i < buffer.capacity(); i ++) { assertEquals(0, buffer.getByte(i)); } } @Test public void testSequentialByteAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeByte(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readByte()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test public void testSequentialUnsignedByteAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeByte(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i ++) { int value = random.nextInt() & 0xFF; assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readUnsignedByte()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test public void testSequentialShortAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i += 2) { short value = (short) random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeShort(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i += 2) { short value = (short) random.nextInt(); assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readShort()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test public void testSequentialUnsignedShortAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i += 2) { short value = (short) random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeShort(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i += 2) { int value = random.nextInt() & 0xFFFF; assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readUnsignedShort()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test public void testSequentialMediumAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) { int value = random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeMedium(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex()); assertEquals(buffer.capacity() % 3, buffer.writableBytes()); random.setSeed(seed); for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) { int value = random.nextInt() << 8 >> 8; assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readMedium()); } assertEquals(buffer.capacity() / 3 * 3, buffer.readerIndex()); assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex()); assertEquals(0, buffer.readableBytes()); assertEquals(buffer.capacity() % 3, buffer.writableBytes()); } @Test public void testSequentialUnsignedMediumAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) { int value = random.nextInt() & 0x00FFFFFF; assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeMedium(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex()); assertEquals(buffer.capacity() % 3, buffer.writableBytes()); random.setSeed(seed); for (int i = 0; i < buffer.capacity() / 3 * 3; i += 3) { int value = random.nextInt() & 0x00FFFFFF; assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readUnsignedMedium()); } assertEquals(buffer.capacity() / 3 * 3, buffer.readerIndex()); assertEquals(buffer.capacity() / 3 * 3, buffer.writerIndex()); assertEquals(0, buffer.readableBytes()); assertEquals(buffer.capacity() % 3, buffer.writableBytes()); } @Test public void testSequentialIntAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i += 4) { int value = random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeInt(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i += 4) { int value = random.nextInt(); assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readInt()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test public void testSequentialUnsignedIntAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i += 4) { int value = random.nextInt(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeInt(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i += 4) { long value = random.nextInt() & 0xFFFFFFFFL; assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readUnsignedInt()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test public void testSequentialLongAccess() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i += 8) { long value = random.nextLong(); assertEquals(i, buffer.writerIndex()); assertTrue(buffer.writable()); buffer.writeLong(value); } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.writable()); random.setSeed(seed); for (int i = 0; i < buffer.capacity(); i += 8) { long value = random.nextLong(); assertEquals(i, buffer.readerIndex()); assertTrue(buffer.readable()); assertEquals(value, buffer.readLong()); } assertEquals(buffer.capacity(), buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); assertFalse(buffer.readable()); assertFalse(buffer.writable()); } @Test public void testByteArrayTransfer() { byte[] value = new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue[j], value[j]); } } } @Test public void testRandomByteArrayTransfer1() { byte[] value= new byte[BLOCK_SIZE]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); buffer.setBytes(i, value); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); buffer.getBytes(i, value); for (int j = 0; j < BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value[j]); } } } @Test public void testRandomByteArrayTransfer2() { byte[] value= new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value[j]); } } } @Test public void testRandomHeapBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE]; ChannelBuffer value = wrappedBuffer(valueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setIndex(0, BLOCK_SIZE); buffer.setBytes(i, value); assertEquals(BLOCK_SIZE, value.readerIndex()); assertEquals(BLOCK_SIZE, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); value.clear(); buffer.getBytes(i, value); assertEquals(0, value.readerIndex()); assertEquals(BLOCK_SIZE, value.writerIndex()); for (int j = 0; j < BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } } } @Test public void testRandomHeapBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(valueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } } } @Test public void testRandomDirectBufferTransfer() { byte[] tmp = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(tmp); value.setBytes(0, tmp, 0, value.capacity()); buffer.setBytes(i, value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); } random.setSeed(seed); ChannelBuffer expectedValue = directBuffer(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(tmp); expectedValue.setBytes(0, tmp, 0, expectedValue.capacity()); int valueOffset = random.nextInt(BLOCK_SIZE); buffer.getBytes(i, value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } } } @Test public void testRandomByteBufferTransfer() { ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value.array()); value.clear().position(random.nextInt(BLOCK_SIZE)); value.limit(value.position() + BLOCK_SIZE); buffer.setBytes(i, value); } random.setSeed(seed); ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue.array()); int valueOffset = random.nextInt(BLOCK_SIZE); value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE); buffer.getBytes(i, value); assertEquals(valueOffset + BLOCK_SIZE, value.position()); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.get(j), value.get(j)); } } } @Test public void testSequentialByteArrayTransfer1() { byte[] value= new byte[BLOCK_SIZE]; buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value); for (int j = 0; j < BLOCK_SIZE; j ++) { assertEquals(expectedValue[j], value[j]); } } } @Test public void testSequentialByteArrayTransfer2() { byte[] value = new byte[BLOCK_SIZE * 2]; buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); buffer.writeBytes(value, readerIndex, BLOCK_SIZE); } random.setSeed(seed); byte[] expectedValue= new byte[BLOCK_SIZE * 2]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue[j], value[j]); } } } @Test public void testSequentialHeapBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(valueContent); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); assertEquals(0, value.readerIndex()); assertEquals(valueContent.length, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(0, value.readerIndex()); assertEquals(valueContent.length, value.writerIndex()); } } @Test public void testSequentialHeapBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(valueContent); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); value.readerIndex(readerIndex); value.writerIndex(readerIndex + BLOCK_SIZE); buffer.writeBytes(value); assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); assertEquals(value.writerIndex(), value.readerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); value.readerIndex(valueOffset); value.writerIndex(valueOffset); buffer.readBytes(value, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(valueOffset, value.readerIndex()); assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); } } @Test public void testSequentialDirectBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); value.setBytes(0, valueContent); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } } @Test public void testSequentialDirectBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = directBuffer(BLOCK_SIZE * 2); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); value.readerIndex(0); value.writerIndex(readerIndex + BLOCK_SIZE); value.readerIndex(readerIndex); buffer.writeBytes(value); assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); assertEquals(value.writerIndex(), value.readerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); value.setBytes(0, valueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); value.readerIndex(valueOffset); value.writerIndex(valueOffset); buffer.readBytes(value, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(valueOffset, value.readerIndex()); assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); } } @Test public void testSequentialByteBufferBackedHeapBufferTransfer1() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2)); value.writerIndex(0); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value, random.nextInt(BLOCK_SIZE), BLOCK_SIZE); assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); int valueOffset = random.nextInt(BLOCK_SIZE); value.setBytes(0, valueContent); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); buffer.readBytes(value, valueOffset, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(0, value.readerIndex()); assertEquals(0, value.writerIndex()); } } @Test public void testSequentialByteBufferBackedHeapBufferTransfer2() { byte[] valueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer value = wrappedBuffer(ByteBuffer.allocate(BLOCK_SIZE * 2)); value.writerIndex(0); buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(valueContent); value.setBytes(0, valueContent); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); int readerIndex = random.nextInt(BLOCK_SIZE); value.readerIndex(0); value.writerIndex(readerIndex + BLOCK_SIZE); value.readerIndex(readerIndex); buffer.writeBytes(value); assertEquals(readerIndex + BLOCK_SIZE, value.writerIndex()); assertEquals(value.writerIndex(), value.readerIndex()); } random.setSeed(seed); byte[] expectedValueContent = new byte[BLOCK_SIZE * 2]; ChannelBuffer expectedValue = wrappedBuffer(expectedValueContent); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValueContent); value.setBytes(0, valueContent); int valueOffset = random.nextInt(BLOCK_SIZE); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); value.readerIndex(valueOffset); value.writerIndex(valueOffset); buffer.readBytes(value, BLOCK_SIZE); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.getByte(j), value.getByte(j)); } assertEquals(valueOffset, value.readerIndex()); assertEquals(valueOffset + BLOCK_SIZE, value.writerIndex()); } } @Test public void testSequentialByteBufferTransfer() { buffer.writerIndex(0); ByteBuffer value = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(value.array()); value.clear().position(random.nextInt(BLOCK_SIZE)); value.limit(value.position() + BLOCK_SIZE); buffer.writeBytes(value); } random.setSeed(seed); ByteBuffer expectedValue = ByteBuffer.allocate(BLOCK_SIZE * 2); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue.array()); int valueOffset = random.nextInt(BLOCK_SIZE); value.clear().position(valueOffset).limit(valueOffset + BLOCK_SIZE); buffer.readBytes(value); assertEquals(valueOffset + BLOCK_SIZE, value.position()); for (int j = valueOffset; j < valueOffset + BLOCK_SIZE; j ++) { assertEquals(expectedValue.get(j), value.get(j)); } } } @Test public void testSequentialCopiedBufferTransfer1() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { byte[] value = new byte[BLOCK_SIZE]; random.nextBytes(value); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); ChannelBuffer actualValue = buffer.readBytes(BLOCK_SIZE); assertEquals(wrappedBuffer(expectedValue), actualValue); // Make sure if it is a copied buffer. actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1)); assertFalse(buffer.getByte(i) == actualValue.getByte(0)); } } @Test public void testSequentialCopiedBufferTransfer2() { buffer.clear(); buffer.writeZero(buffer.capacity()); try { buffer.readBytes(ChannelBufferIndexFinder.CR); fail(); } catch (NoSuchElementException e) { // Expected } assertSame(EMPTY_BUFFER, buffer.readBytes(ChannelBufferIndexFinder.NUL)); buffer.clear(); buffer.writeBytes(new byte[] { 1, 2, 3, 4, 0 }); ChannelBuffer copy = buffer.readBytes(ChannelBufferIndexFinder.NUL); assertEquals(wrappedBuffer(new byte[] { 1, 2, 3, 4 }), copy); // Make sure if it is a copied buffer. copy.setByte(0, (byte) (copy.getByte(0) + 1)); assertFalse(buffer.getByte(0) == copy.getByte(0)); } @Test public void testSequentialSlice1() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { byte[] value = new byte[BLOCK_SIZE]; random.nextBytes(value); assertEquals(0, buffer.readerIndex()); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(value); } random.setSeed(seed); byte[] expectedValue = new byte[BLOCK_SIZE]; for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { random.nextBytes(expectedValue); assertEquals(i, buffer.readerIndex()); assertEquals(CAPACITY, buffer.writerIndex()); ChannelBuffer actualValue = buffer.readSlice(BLOCK_SIZE); assertEquals(wrappedBuffer(expectedValue), actualValue); // Make sure if it is a sliced buffer. actualValue.setByte(0, (byte) (actualValue.getByte(0) + 1)); assertEquals(buffer.getByte(i), actualValue.getByte(0)); } } @Test public void testSequentialSlice2() { buffer.clear(); buffer.writeZero(buffer.capacity()); try { buffer.readSlice(ChannelBufferIndexFinder.CR); fail(); } catch (NoSuchElementException e) { // Expected } assertSame(EMPTY_BUFFER, buffer.readSlice(ChannelBufferIndexFinder.NUL)); buffer.clear(); buffer.writeBytes(new byte[] { 1, 2, 3, 4, 0 }); ChannelBuffer slice = buffer.readSlice(ChannelBufferIndexFinder.NUL); assertEquals(wrappedBuffer(new byte[] { 1, 2, 3, 4 }), slice); // Make sure if it is a sliced buffer. slice.setByte(0, (byte) (slice.getByte(0) + 1)); assertTrue(buffer.getByte(0) == slice.getByte(0)); } @Test public void testWriteZero() { try { buffer.writeZero(-1); fail(); } catch (IllegalArgumentException e) { // Expected } buffer.clear(); while (buffer.writable()) { buffer.writeByte((byte) 0xFF); } buffer.clear(); for (int i = 0; i < buffer.capacity();) { int length = Math.min(buffer.capacity() - i, random.nextInt(32)); buffer.writeZero(length); i += length; } assertEquals(0, buffer.readerIndex()); assertEquals(buffer.capacity(), buffer.writerIndex()); for (int i = 0; i < buffer.capacity(); i ++) { assertEquals(0, buffer.getByte(i)); } } @Test public void testDiscardReadBytes() { buffer.writerIndex(0); for (int i = 0; i < buffer.capacity(); i += 4) { buffer.writeInt(i); } ChannelBuffer copy = copiedBuffer(buffer); // Make sure there's no effect if called when readerIndex is 0. buffer.readerIndex(CAPACITY / 4); buffer.markReaderIndex(); buffer.writerIndex(CAPACITY / 3); buffer.markWriterIndex(); buffer.readerIndex(0); buffer.writerIndex(CAPACITY / 2); buffer.discardReadBytes(); assertEquals(0, buffer.readerIndex()); assertEquals(CAPACITY / 2, buffer.writerIndex()); assertEquals(copy.slice(0, CAPACITY / 2), buffer.slice(0, CAPACITY / 2)); buffer.resetReaderIndex(); assertEquals(CAPACITY / 4, buffer.readerIndex()); buffer.resetWriterIndex(); assertEquals(CAPACITY / 3, buffer.writerIndex()); // Make sure bytes after writerIndex is not copied. buffer.readerIndex(1); buffer.writerIndex(CAPACITY / 2); buffer.discardReadBytes(); assertEquals(0, buffer.readerIndex()); assertEquals(CAPACITY / 2 - 1, buffer.writerIndex()); assertEquals(copy.slice(1, CAPACITY / 2 - 1), buffer.slice(0, CAPACITY / 2 - 1)); assertEquals(copy.slice(CAPACITY / 2, CAPACITY / 2), buffer.slice(CAPACITY / 2, CAPACITY / 2)); // Marks also should be relocated. buffer.resetReaderIndex(); assertEquals(CAPACITY / 4 - 1, buffer.readerIndex()); buffer.resetWriterIndex(); assertEquals(CAPACITY / 3 - 1, buffer.writerIndex()); } @Test public void testStreamTransfer1() throws Exception { byte[] expected = new byte[buffer.capacity()]; random.nextBytes(expected); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE); assertEquals(BLOCK_SIZE, buffer.setBytes(i, in, BLOCK_SIZE)); assertEquals(-1, buffer.setBytes(i, in, 0)); } ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { buffer.getBytes(i, out, BLOCK_SIZE); } assertTrue(Arrays.equals(expected, out.toByteArray())); } @Test public void testStreamTransfer2() throws Exception { byte[] expected = new byte[buffer.capacity()]; random.nextBytes(expected); buffer.clear(); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { ByteArrayInputStream in = new ByteArrayInputStream(expected, i, BLOCK_SIZE); assertEquals(i, buffer.writerIndex()); buffer.writeBytes(in, BLOCK_SIZE); assertEquals(i + BLOCK_SIZE, buffer.writerIndex()); } ByteArrayOutputStream out = new ByteArrayOutputStream(); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { assertEquals(i, buffer.readerIndex()); buffer.readBytes(out, BLOCK_SIZE); assertEquals(i + BLOCK_SIZE, buffer.readerIndex()); } assertTrue(Arrays.equals(expected, out.toByteArray())); } @Test public void testCopy() { for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); buffer.setByte(i, value); } final int readerIndex = CAPACITY / 3; final int writerIndex = CAPACITY * 2 / 3; buffer.setIndex(readerIndex, writerIndex); // Make sure all properties are copied. ChannelBuffer copy = buffer.copy(); assertEquals(0, copy.readerIndex()); assertEquals(buffer.readableBytes(), copy.writerIndex()); assertEquals(buffer.readableBytes(), copy.capacity()); assertSame(buffer.order(), copy.order()); for (int i = 0; i < copy.capacity(); i ++) { assertEquals(buffer.getByte(i + readerIndex), copy.getByte(i)); } // Make sure the buffer content is independent from each other. buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1)); assertTrue(buffer.getByte(readerIndex) != copy.getByte(0)); copy.setByte(1, (byte) (copy.getByte(1) + 1)); assertTrue(buffer.getByte(readerIndex + 1) != copy.getByte(1)); } @Test public void testDuplicate() { for (int i = 0; i < buffer.capacity(); i ++) { byte value = (byte) random.nextInt(); buffer.setByte(i, value); } final int readerIndex = CAPACITY / 3; final int writerIndex = CAPACITY * 2 / 3; buffer.setIndex(readerIndex, writerIndex); // Make sure all properties are copied. ChannelBuffer duplicate = buffer.duplicate(); assertEquals(buffer.readerIndex(), duplicate.readerIndex()); assertEquals(buffer.writerIndex(), duplicate.writerIndex()); assertEquals(buffer.capacity(), duplicate.capacity()); assertSame(buffer.order(), duplicate.order()); for (int i = 0; i < duplicate.capacity(); i ++) { assertEquals(buffer.getByte(i), duplicate.getByte(i)); } // Make sure the buffer content is shared. buffer.setByte(readerIndex, (byte) (buffer.getByte(readerIndex) + 1)); assertTrue(buffer.getByte(readerIndex) == duplicate.getByte(readerIndex)); duplicate.setByte(1, (byte) (duplicate.getByte(1) + 1)); assertTrue(buffer.getByte(1) == duplicate.getByte(1)); } @Test public void testSlice() throws Exception { assertEquals(buffer.order(), buffer.slice(1, buffer.capacity() - 1).order()); } @Test public void testEquals() { assertFalse(buffer.equals(null)); assertFalse(buffer.equals(new Object())); byte[] value = new byte[32]; buffer.setIndex(0, value.length); random.nextBytes(value); buffer.setBytes(0, value); assertEquals(buffer, wrappedBuffer(BIG_ENDIAN, value)); assertEquals(buffer, wrappedBuffer(LITTLE_ENDIAN, value)); value[0] ++; assertFalse(buffer.equals(wrappedBuffer(BIG_ENDIAN, value))); assertFalse(buffer.equals(wrappedBuffer(LITTLE_ENDIAN, value))); } @Test public void testCompareTo() { try { buffer.compareTo(null); fail(); } catch (NullPointerException e) { // Expected } // Fill the random stuff byte[] value = new byte[32]; random.nextBytes(value); // Prevent overflow / underflow if (value[0] == 0) { value[0] ++; } else if (value[0] == -1) { value[0] --; } buffer.setIndex(0, value.length); buffer.setBytes(0, value); assertEquals(0, buffer.compareTo(wrappedBuffer(BIG_ENDIAN, value))); assertEquals(0, buffer.compareTo(wrappedBuffer(LITTLE_ENDIAN, value))); value[0] ++; assertTrue(buffer.compareTo(wrappedBuffer(BIG_ENDIAN, value)) < 0); assertTrue(buffer.compareTo(wrappedBuffer(LITTLE_ENDIAN, value)) < 0); value[0] -= 2; assertTrue(buffer.compareTo(wrappedBuffer(BIG_ENDIAN, value)) > 0); assertTrue(buffer.compareTo(wrappedBuffer(LITTLE_ENDIAN, value)) > 0); value[0] ++; assertTrue(buffer.compareTo(wrappedBuffer(BIG_ENDIAN, value, 0, 31)) > 0); assertTrue(buffer.compareTo(wrappedBuffer(LITTLE_ENDIAN, value, 0, 31)) > 0); assertTrue(buffer.slice(0, 31).compareTo(wrappedBuffer(BIG_ENDIAN, value)) < 0); assertTrue(buffer.slice(0, 31).compareTo(wrappedBuffer(LITTLE_ENDIAN, value)) < 0); } @Test public void testToString() { try { buffer.toString("UnsupportedCharsetName"); fail(); } catch (UnsupportedCharsetException e) { // Expected } buffer.clear(); buffer.writeBytes(copiedBuffer("Hello, World!", "ISO-8859-1")); assertEquals("Hello, World!", buffer.toString("ISO-8859-1")); // Same with the previous one assertEquals("Hello, World!", buffer.toString("ISO-8859-1", null)); // NUL not found. assertEquals("Hello, World!", buffer.toString("ISO-8859-1", ChannelBufferIndexFinder.NUL)); // Linear space found. assertEquals("Hello,", buffer.toString("ISO-8859-1", ChannelBufferIndexFinder.LINEAR_WHITESPACE)); } @Test public void testIndexOf() { buffer.clear(); buffer.writeByte((byte) 1); buffer.writeByte((byte) 2); buffer.writeByte((byte) 3); buffer.writeByte((byte) 2); buffer.writeByte((byte) 1); assertEquals(-1, buffer.indexOf(1, 4, (byte) 1)); assertEquals(-1, buffer.indexOf(4, 1, (byte) 1)); assertEquals(1, buffer.indexOf(1, 4, (byte) 2)); assertEquals(3, buffer.indexOf(4, 1, (byte) 2)); } @Test public void testToByteBuffer1() { byte[] value = new byte[buffer.capacity()]; random.nextBytes(value); buffer.clear(); buffer.writeBytes(value); assertEquals(ByteBuffer.wrap(value), buffer.toByteBuffer()); } @Test public void testToByteBuffer2() { byte[] value = new byte[buffer.capacity()]; random.nextBytes(value); buffer.clear(); buffer.writeBytes(value); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { assertEquals(ByteBuffer.wrap(value, i, BLOCK_SIZE), buffer.toByteBuffer(i, BLOCK_SIZE)); } } @Test public void testToByteBuffer3() { assertEquals(buffer.order(), buffer.toByteBuffer().order()); } @Test public void testToByteBuffers1() { byte[] value = new byte[buffer.capacity()]; random.nextBytes(value); buffer.clear(); buffer.writeBytes(value); ByteBuffer[] nioBuffers = buffer.toByteBuffers(); int length = 0; for (ByteBuffer b: nioBuffers) { length += b.remaining(); } ByteBuffer nioBuffer = ByteBuffer.allocate(length); for (ByteBuffer b: nioBuffers) { nioBuffer.put(b); } nioBuffer.flip(); assertEquals(ByteBuffer.wrap(value), nioBuffer); } @Test public void testToByteBuffers2() { byte[] value = new byte[buffer.capacity()]; random.nextBytes(value); buffer.clear(); buffer.writeBytes(value); for (int i = 0; i < buffer.capacity() - BLOCK_SIZE + 1; i += BLOCK_SIZE) { ByteBuffer[] nioBuffers = buffer.toByteBuffers(i, BLOCK_SIZE); ByteBuffer nioBuffer = ByteBuffer.allocate(BLOCK_SIZE); for (ByteBuffer b: nioBuffers) { nioBuffer.put(b); } nioBuffer.flip(); assertEquals(ByteBuffer.wrap(value, i, BLOCK_SIZE), nioBuffer); } } @Test public void testSkipBytes1() { buffer.setIndex(CAPACITY / 4, CAPACITY / 2); buffer.skipBytes(CAPACITY / 4); assertEquals(CAPACITY / 4 * 2, buffer.readerIndex()); try { buffer.skipBytes(CAPACITY / 4 + 1); fail(); } catch (IndexOutOfBoundsException e) { // Expected } // Should remain unchanged. assertEquals(CAPACITY / 4 * 2, buffer.readerIndex()); } @Test public void testSkipBytes2() { buffer.clear(); buffer.writeZero(buffer.capacity()); try { buffer.skipBytes(ChannelBufferIndexFinder.LF); fail(); } catch (NoSuchElementException e) { // Expected } buffer.skipBytes(ChannelBufferIndexFinder.NUL); assertEquals(0, buffer.readerIndex()); buffer.clear(); buffer.writeBytes(new byte[] { 1, 2, 3, 4, 0 }); buffer.skipBytes(ChannelBufferIndexFinder.NUL); assertEquals(4, buffer.readerIndex()); } @Test public void testHashCode() { ChannelBuffer elemA = buffer(15); ChannelBuffer elemB = directBuffer(15); elemA.writeBytes(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 0, 1, 2, 3, 4, 5 }); elemB.writeBytes(new byte[] { 6, 7, 8, 9, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 9 }); Set set = new HashSet(); set.add(elemA); set.add(elemB); assertEquals(2, set.size()); assertTrue(set.contains(elemA.copy())); assertTrue(set.contains(elemB.copy())); buffer.clear(); buffer.writeBytes(elemA.duplicate()); assertTrue(set.remove(buffer)); assertFalse(set.contains(elemA)); assertEquals(1, set.size()); buffer.clear(); buffer.writeBytes(elemB.duplicate()); assertTrue(set.remove(buffer)); assertFalse(set.contains(elemB)); assertEquals(0, set.size()); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/ReadOnlyChannelBufferTest.java0000644000175000017500000001642311057753271031756 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.easymock.EasyMock.*; import static org.jboss.netty.buffer.ChannelBuffers.*; import static org.junit.Assert.*; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 239 $, $Date: 2008-09-04 05:38:17 -0700 (Thu, 04 Sep 2008) $ * */ public class ReadOnlyChannelBufferTest { @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new ReadOnlyChannelBuffer(null); } @Test public void testUnmodifiableBuffer() { assertTrue(ChannelBuffers.unmodifiableBuffer(ChannelBuffers.buffer(1)) instanceof ReadOnlyChannelBuffer); } @Test public void testUnwrap() { ChannelBuffer buf = ChannelBuffers.buffer(1); assertSame(buf, ((WrappedChannelBuffer) ChannelBuffers.unmodifiableBuffer(buf)).unwrap()); } @Test public void shouldHaveSameByteOrder() { ChannelBuffer buf = ChannelBuffers.buffer(ChannelBuffers.LITTLE_ENDIAN, 1); assertSame(ChannelBuffers.LITTLE_ENDIAN, ChannelBuffers.unmodifiableBuffer(buf).order()); } @Test public void shouldReturnReadOnlyDerivedBuffer() { ChannelBuffer buf = ChannelBuffers.unmodifiableBuffer(ChannelBuffers.buffer(1)); assertTrue(buf.duplicate() instanceof ReadOnlyChannelBuffer); assertTrue(buf.slice() instanceof ReadOnlyChannelBuffer); assertTrue(buf.slice(0, 1) instanceof ReadOnlyChannelBuffer); assertTrue(buf.duplicate() instanceof ReadOnlyChannelBuffer); } @Test public void shouldReturnWritableCopy() { ChannelBuffer buf = ChannelBuffers.unmodifiableBuffer(ChannelBuffers.buffer(1)); assertFalse(buf.copy() instanceof ReadOnlyChannelBuffer); } @Test public void shouldForwardReadCallsBlindly() throws Exception { ChannelBuffer buf = createStrictMock(ChannelBuffer.class); expect(buf.readerIndex()).andReturn(0).anyTimes(); expect(buf.writerIndex()).andReturn(0).anyTimes(); expect(buf.capacity()).andReturn(0).anyTimes(); expect(buf.getBytes(1, (GatheringByteChannel) null, 2)).andReturn(3); buf.getBytes(4, (OutputStream) null, 5); buf.getBytes(6, (byte[]) null, 7, 8); buf.getBytes(9, (ChannelBuffer) null, 10, 11); buf.getBytes(12, (ByteBuffer) null); expect(buf.getByte(13)).andReturn(Byte.valueOf((byte) 14)); expect(buf.getShort(15)).andReturn(Short.valueOf((short) 16)); expect(buf.getUnsignedMedium(17)).andReturn(18); expect(buf.getInt(19)).andReturn(20); expect(buf.getLong(21)).andReturn(22L); ByteBuffer bb = ByteBuffer.allocate(100); ByteBuffer[] bbs = new ByteBuffer[] { ByteBuffer.allocate(101), ByteBuffer.allocate(102) }; expect(buf.toByteBuffer(23, 24)).andReturn(bb); expect(buf.toByteBuffers(25, 26)).andReturn(bbs); expect(buf.toString(27, 28, "29")).andReturn("30"); expect(buf.capacity()).andReturn(31); replay(buf); ChannelBuffer roBuf = unmodifiableBuffer(buf); assertEquals(3, roBuf.getBytes(1, (GatheringByteChannel) null, 2)); roBuf.getBytes(4, (OutputStream) null, 5); roBuf.getBytes(6, (byte[]) null, 7, 8); roBuf.getBytes(9, (ChannelBuffer) null, 10, 11); roBuf.getBytes(12, (ByteBuffer) null); assertEquals((byte) 14, roBuf.getByte(13)); assertEquals((short) 16, roBuf.getShort(15)); assertEquals(18, roBuf.getUnsignedMedium(17)); assertEquals(20, roBuf.getInt(19)); assertEquals(22L, roBuf.getLong(21)); ByteBuffer roBB = roBuf.toByteBuffer(23, 24); assertEquals(100, roBB.capacity()); assertTrue(roBB.isReadOnly()); ByteBuffer[] roBBs = roBuf.toByteBuffers(25, 26); assertEquals(2, roBBs.length); assertEquals(101, roBBs[0].capacity()); assertTrue(roBBs[0].isReadOnly()); assertEquals(102, roBBs[1].capacity()); assertTrue(roBBs[1].isReadOnly()); assertEquals("30", roBuf.toString(27, 28, "29")); assertEquals(31, roBuf.capacity()); verify(buf); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectDiscardReadBytes() { unmodifiableBuffer(EMPTY_BUFFER).discardReadBytes(); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetByte() { unmodifiableBuffer(EMPTY_BUFFER).setByte(0, (byte) 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetShort() { unmodifiableBuffer(EMPTY_BUFFER).setShort(0, (short) 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetMedium() { unmodifiableBuffer(EMPTY_BUFFER).setMedium(0, 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetInt() { unmodifiableBuffer(EMPTY_BUFFER).setInt(0, 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetLong() { unmodifiableBuffer(EMPTY_BUFFER).setLong(0, 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetBytes1() throws IOException { unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (InputStream) null, 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetBytes2() throws IOException { unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ScatteringByteChannel) null, 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetBytes3() { unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (byte[]) null, 0, 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetBytes4() { unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ChannelBuffer) null, 0, 0); } @Test(expected = UnsupportedOperationException.class) public void shouldRejectSetBytes5() { unmodifiableBuffer(EMPTY_BUFFER).setBytes(0, (ByteBuffer) null); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/BigEndianHeapChannelBufferTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/BigEndianHeapChannelBufferTest.jav0000644000175000017500000000352211057746110032504 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 237 $, $Date: 2008-09-04 04:53:44 -0700 (Thu, 04 Sep 2008) $ */ public class BigEndianHeapChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.buffer(length); assertEquals(0, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new BigEndianHeapChannelBuffer(null); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/ByteBufferBackedHeapChannelBufferTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/ByteBufferBackedHeapChannelBufferT0000644000175000017500000000351011057746110032515 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.nio.ByteBuffer; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 237 $, $Date: 2008-09-04 04:53:44 -0700 (Thu, 04 Sep 2008) $ */ public class ByteBufferBackedHeapChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = new ByteBufferBackedChannelBuffer(ByteBuffer.allocate(length)); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new ByteBufferBackedChannelBuffer(null); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/DynamicChannelBufferTest.java0000644000175000017500000000414011057746110031610 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 237 $, $Date: 2008-09-04 04:53:44 -0700 (Thu, 04 Sep 2008) $ */ public class DynamicChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.dynamicBuffer(length); // A dynamic buffer does lazy initialization. assertEquals(0, buffer.capacity()); // Initialize. buffer.writeZero(1); buffer.clear(); // And validate the initial capacity assertEquals(0, buffer.writerIndex()); assertEquals(length, buffer.capacity()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new DynamicChannelBuffer(null, 0); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/ChannelBufferIndexFinderTest.java0000644000175000017500000000710311055243260032421 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 146 $, $Date: 2008-08-27 05:21:04 -0700 (Wed, 27 Aug 2008) $ * */ public class ChannelBufferIndexFinderTest { @Test public void testForward() { ChannelBuffer buf = ChannelBuffers.copiedBuffer( "abc\r\n\ndef\r\rghi\n\njkl\0\0mno \t\tx", "ISO-8859-1"); assertEquals(3, buf.indexOf(Integer.MIN_VALUE, buf.capacity(), ChannelBufferIndexFinder.CRLF)); assertEquals(6, buf.indexOf(3, buf.capacity(), ChannelBufferIndexFinder.NOT_CRLF)); assertEquals(9, buf.indexOf(6, buf.capacity(), ChannelBufferIndexFinder.CR)); assertEquals(11, buf.indexOf(9, buf.capacity(), ChannelBufferIndexFinder.NOT_CR)); assertEquals(14, buf.indexOf(11, buf.capacity(), ChannelBufferIndexFinder.LF)); assertEquals(16, buf.indexOf(14, buf.capacity(), ChannelBufferIndexFinder.NOT_LF)); assertEquals(19, buf.indexOf(16, buf.capacity(), ChannelBufferIndexFinder.NUL)); assertEquals(21, buf.indexOf(19, buf.capacity(), ChannelBufferIndexFinder.NOT_NUL)); assertEquals(24, buf.indexOf(21, buf.capacity(), ChannelBufferIndexFinder.LINEAR_WHITESPACE)); assertEquals(28, buf.indexOf(24, buf.capacity(), ChannelBufferIndexFinder.NOT_LINEAR_WHITESPACE)); assertEquals(-1, buf.indexOf(28, buf.capacity(), ChannelBufferIndexFinder.LINEAR_WHITESPACE)); } @Test public void testBackward() { ChannelBuffer buf = ChannelBuffers.copiedBuffer( "abc\r\n\ndef\r\rghi\n\njkl\0\0mno \t\tx", "ISO-8859-1"); assertEquals(27, buf.indexOf(Integer.MAX_VALUE, 0, ChannelBufferIndexFinder.LINEAR_WHITESPACE)); assertEquals(23, buf.indexOf(28, 0, ChannelBufferIndexFinder.NOT_LINEAR_WHITESPACE)); assertEquals(20, buf.indexOf(24, 0, ChannelBufferIndexFinder.NUL)); assertEquals(18, buf.indexOf(21, 0, ChannelBufferIndexFinder.NOT_NUL)); assertEquals(15, buf.indexOf(19, 0, ChannelBufferIndexFinder.LF)); assertEquals(13, buf.indexOf(16, 0, ChannelBufferIndexFinder.NOT_LF)); assertEquals(10, buf.indexOf(14, 0, ChannelBufferIndexFinder.CR)); assertEquals(8, buf.indexOf(11, 0, ChannelBufferIndexFinder.NOT_CR)); assertEquals(5, buf.indexOf(9, 0, ChannelBufferIndexFinder.CRLF)); assertEquals(2, buf.indexOf(6, 0, ChannelBufferIndexFinder.NOT_CRLF)); assertEquals(-1, buf.indexOf(3, 0, ChannelBufferIndexFinder.CRLF)); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/BigEndianCompositeChannelBufferTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/BigEndianCompositeChannelBufferTes0000644000175000017500000000641611113406371032626 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 527 $, $Date: 2008-11-26 18:59:05 -0800 (Wed, 26 Nov 2008) $ */ public class BigEndianCompositeChannelBufferTest extends AbstractChannelBufferTest { private List buffers; private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffers = new ArrayList(); for (int i = 0; i < length; i += 10) { buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[1])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[2])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[3])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[4])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[5])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[6])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[7])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[8])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(new byte[9])); buffers.add(ChannelBuffers.EMPTY_BUFFER); } buffer = ChannelBuffers.wrappedBuffer(buffers.toArray(new ChannelBuffer[buffers.size()])); buffer.writerIndex(length); buffer = ChannelBuffers.wrappedBuffer(buffer); assertEquals(length, buffer.capacity()); assertEquals(length, buffer.readableBytes()); assertFalse(buffer.writable()); buffer.writerIndex(0); return buffer; } @Override protected ChannelBuffer[] components() { return buffers.toArray(new ChannelBuffer[buffers.size()]); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/SlicedChannelBufferTest.java0000644000175000017500000000374711057746110031443 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import java.util.Random; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 237 $, $Date: 2008-09-04 04:53:44 -0700 (Thu, 04 Sep 2008) $ */ public class SlicedChannelBufferTest extends AbstractChannelBufferTest { private final Random random = new Random(); private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.wrappedBuffer( new byte[length * 2], random.nextInt(length - 1) + 1, length); assertEquals(length, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new SlicedChannelBuffer(null, 0, 0); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/ChannelBuffersTest.java0000644000175000017500000004012011055243260030460 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.jboss.netty.buffer.ChannelBuffers.*; import static org.junit.Assert.*; import java.io.InputStream; import java.nio.ByteBuffer; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.easymock.classextension.EasyMock; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 146 $, $Date: 2008-08-27 05:21:04 -0700 (Wed, 27 Aug 2008) $ * */ public class ChannelBuffersTest { @Test public void testCompositeWrappedBuffer() { ChannelBuffer header = dynamicBuffer(12); ChannelBuffer payload = dynamicBuffer(512); header.writeBytes(new byte[12]); payload.writeBytes(new byte[512]); ChannelBuffer buffer = wrappedBuffer(header, payload); assertTrue(header.readableBytes() == 12); assertTrue(payload.readableBytes() == 512); assertEquals(12 + 512, buffer.readableBytes()); assertEquals(12 + 512, buffer.toByteBuffer(0, 12 + 512).remaining()); } @Test public void testHashCode() { Map map = new LinkedHashMap(); map.put(new byte[0], 1); map.put(new byte[] { 1 }, 32); map.put(new byte[] { 2 }, 33); map.put(new byte[] { 0, 1 }, 962); map.put(new byte[] { 1, 2 }, 994); map.put(new byte[] { 0, 1, 2, 3, 4, 5 }, 63504931); map.put(new byte[] { 6, 7, 8, 9, 0, 1 }, (int) 97180294697L); map.put(new byte[] { -1, -1, -1, (byte) 0xE1 }, 1); for (Entry e: map.entrySet()) { assertEquals( e.getValue().intValue(), ChannelBuffers.hashCode(wrappedBuffer(e.getKey()))); } } @Test public void testEquals() { ChannelBuffer a, b; // Different length. a = wrappedBuffer(new byte[] { 1 }); b = wrappedBuffer(new byte[] { 1, 2 }); assertFalse(ChannelBuffers.equals(a, b)); // Same content, same firstIndex, short length. a = wrappedBuffer(new byte[] { 1, 2, 3 }); b = wrappedBuffer(new byte[] { 1, 2, 3 }); assertTrue(ChannelBuffers.equals(a, b)); // Same content, different firstIndex, short length. a = wrappedBuffer(new byte[] { 1, 2, 3 }); b = wrappedBuffer(new byte[] { 0, 1, 2, 3, 4 }, 1, 3); assertTrue(ChannelBuffers.equals(a, b)); // Different content, same firstIndex, short length. a = wrappedBuffer(new byte[] { 1, 2, 3 }); b = wrappedBuffer(new byte[] { 1, 2, 4 }); assertFalse(ChannelBuffers.equals(a, b)); // Different content, different firstIndex, short length. a = wrappedBuffer(new byte[] { 1, 2, 3 }); b = wrappedBuffer(new byte[] { 0, 1, 2, 4, 5 }, 1, 3); assertFalse(ChannelBuffers.equals(a, b)); // Same content, same firstIndex, long length. a = wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); b = wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); assertTrue(ChannelBuffers.equals(a, b)); // Same content, different firstIndex, long length. a = wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); b = wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11}, 1, 10); assertTrue(ChannelBuffers.equals(a, b)); // Different content, same firstIndex, long length. a = wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); b = wrappedBuffer(new byte[] { 1, 2, 3, 4, 6, 7, 8, 5, 9, 10 }); assertFalse(ChannelBuffers.equals(a, b)); // Different content, different firstIndex, long length. a = wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }); b = wrappedBuffer(new byte[] { 0, 1, 2, 3, 4, 6, 7, 8, 5, 9, 10, 11 }, 1, 10); assertFalse(ChannelBuffers.equals(a, b)); } @Test public void testCompare() { List expected = new ArrayList(); expected.add(wrappedBuffer(new byte[] { 1 })); expected.add(wrappedBuffer(new byte[] { 1, 2 })); expected.add(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 })); expected.add(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 })); expected.add(wrappedBuffer(new byte[] { 2 })); expected.add(wrappedBuffer(new byte[] { 2, 3 })); expected.add(wrappedBuffer(new byte[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 })); expected.add(wrappedBuffer(new byte[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13 })); expected.add(wrappedBuffer(new byte[] { 2, 3, 4 }, 1, 1)); expected.add(wrappedBuffer(new byte[] { 1, 2, 3, 4 }, 2, 2)); expected.add(wrappedBuffer(new byte[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, 1, 10)); expected.add(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, 2, 12)); expected.add(wrappedBuffer(new byte[] { 2, 3, 4, 5 }, 2, 1)); expected.add(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5 }, 3, 2)); expected.add(wrappedBuffer(new byte[] { 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, 2, 10)); expected.add(wrappedBuffer(new byte[] { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15 }, 3, 12)); for (int i = 0; i < expected.size(); i ++) { for (int j = 0; j < expected.size(); j ++) { if (i == j) { assertEquals(0, compare(expected.get(i), expected.get(j))); } else if (i < j) { assertTrue(compare(expected.get(i), expected.get(j)) < 0); } else { assertTrue(compare(expected.get(i), expected.get(j)) > 0); } } } } @Test public void shouldReturnEmptyBufferWhenLengthIsZero() { assertSame(EMPTY_BUFFER, buffer(0)); assertSame(EMPTY_BUFFER, buffer(LITTLE_ENDIAN, 0)); assertSame(EMPTY_BUFFER, directBuffer(0)); assertSame(EMPTY_BUFFER, wrappedBuffer(new byte[0])); assertSame(EMPTY_BUFFER, wrappedBuffer(LITTLE_ENDIAN, new byte[0])); assertSame(EMPTY_BUFFER, wrappedBuffer(new byte[8], 0, 0)); assertSame(EMPTY_BUFFER, wrappedBuffer(LITTLE_ENDIAN, new byte[8], 0, 0)); assertSame(EMPTY_BUFFER, wrappedBuffer(new byte[8], 8, 0)); assertSame(EMPTY_BUFFER, wrappedBuffer(LITTLE_ENDIAN, new byte[8], 8, 0)); assertSame(EMPTY_BUFFER, wrappedBuffer(ByteBuffer.allocateDirect(0))); assertSame(EMPTY_BUFFER, wrappedBuffer(EMPTY_BUFFER)); assertSame(EMPTY_BUFFER, wrappedBuffer(new byte[0][])); assertSame(EMPTY_BUFFER, wrappedBuffer(new byte[][] { new byte[0] })); assertSame(EMPTY_BUFFER, wrappedBuffer(new ByteBuffer[0])); assertSame(EMPTY_BUFFER, wrappedBuffer(new ByteBuffer[] { ByteBuffer.allocate(0) })); assertSame(EMPTY_BUFFER, wrappedBuffer(new ByteBuffer[] { ByteBuffer.allocate(0), ByteBuffer.allocate(0) })); assertSame(EMPTY_BUFFER, wrappedBuffer(new ChannelBuffer[0])); assertSame(EMPTY_BUFFER, wrappedBuffer(new ChannelBuffer[] { buffer(0) })); assertSame(EMPTY_BUFFER, wrappedBuffer(new ChannelBuffer[] { buffer(0), buffer(0) })); assertSame(EMPTY_BUFFER, copiedBuffer(new byte[0])); assertSame(EMPTY_BUFFER, copiedBuffer(LITTLE_ENDIAN, new byte[0])); assertSame(EMPTY_BUFFER, copiedBuffer(new byte[8], 0, 0)); assertSame(EMPTY_BUFFER, copiedBuffer(LITTLE_ENDIAN, new byte[8], 0, 0)); assertSame(EMPTY_BUFFER, copiedBuffer(new byte[8], 8, 0)); assertSame(EMPTY_BUFFER, copiedBuffer(LITTLE_ENDIAN, new byte[8], 8, 0)); assertSame(EMPTY_BUFFER, copiedBuffer(ByteBuffer.allocateDirect(0))); assertSame(EMPTY_BUFFER, copiedBuffer(EMPTY_BUFFER)); assertSame(EMPTY_BUFFER, copiedBuffer(new byte[0][])); assertSame(EMPTY_BUFFER, copiedBuffer(new byte[][] { new byte[0] })); assertSame(EMPTY_BUFFER, copiedBuffer(new ByteBuffer[0])); assertSame(EMPTY_BUFFER, copiedBuffer(new ByteBuffer[] { ByteBuffer.allocate(0) })); assertSame(EMPTY_BUFFER, copiedBuffer(new ByteBuffer[] { ByteBuffer.allocate(0), ByteBuffer.allocate(0) })); assertSame(EMPTY_BUFFER, copiedBuffer(new ChannelBuffer[0])); assertSame(EMPTY_BUFFER, copiedBuffer(new ChannelBuffer[] { buffer(0) })); assertSame(EMPTY_BUFFER, copiedBuffer(new ChannelBuffer[] { buffer(0), buffer(0) })); } @Test(expected = NullPointerException.class) public void shouldDisallowNullEndian1() { buffer(null, 0); } @Test(expected = NullPointerException.class) public void shouldDisallowNullEndian2() { directBuffer(null, 0); } @Test(expected = NullPointerException.class) public void shouldDisallowNullEndian3() { wrappedBuffer(null, new byte[0]); } @Test(expected = NullPointerException.class) public void shouldDisallowNullEndian4() { wrappedBuffer(null, new byte[0], 0, 0); } @Test public void shouldAllowEmptyBufferToCreateCompositeBuffer() { ChannelBuffer buf = wrappedBuffer( EMPTY_BUFFER, wrappedBuffer(LITTLE_ENDIAN, new byte[16]), EMPTY_BUFFER); assertEquals(16, buf.capacity()); } @Test public void testWrappedBuffer() { assertEquals(16, wrappedBuffer(ByteBuffer.allocateDirect(16)).capacity()); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), wrappedBuffer(new byte[][] { new byte[] { 1, 2, 3 } })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), wrappedBuffer( new byte[] { 1 }, new byte[] { 2 }, new byte[] { 3 })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), wrappedBuffer(new ChannelBuffer[] { wrappedBuffer(new byte[] { 1, 2, 3 }) })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), wrappedBuffer( wrappedBuffer(new byte[] { 1 }), wrappedBuffer(new byte[] { 2 }), wrappedBuffer(new byte[] { 3 }))); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), wrappedBuffer(new ByteBuffer[] { ByteBuffer.wrap(new byte[] { 1, 2, 3 }) })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), wrappedBuffer( ByteBuffer.wrap(new byte[] { 1 }), ByteBuffer.wrap(new byte[] { 2 }), ByteBuffer.wrap(new byte[] { 3 }))); } @Test public void testCopiedBuffer() { assertEquals(16, copiedBuffer(ByteBuffer.allocateDirect(16)).capacity()); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), copiedBuffer(new byte[][] { new byte[] { 1, 2, 3 } })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), copiedBuffer( new byte[] { 1 }, new byte[] { 2 }, new byte[] { 3 })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), copiedBuffer(new ChannelBuffer[] { wrappedBuffer(new byte[] { 1, 2, 3 }) })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), copiedBuffer( wrappedBuffer(new byte[] { 1 }), wrappedBuffer(new byte[] { 2 }), wrappedBuffer(new byte[] { 3 }))); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), copiedBuffer(new ByteBuffer[] { ByteBuffer.wrap(new byte[] { 1, 2, 3 }) })); assertEquals( wrappedBuffer(new byte[] { 1, 2, 3 }), copiedBuffer( ByteBuffer.wrap(new byte[] { 1 }), ByteBuffer.wrap(new byte[] { 2 }), ByteBuffer.wrap(new byte[] { 3 }))); try { copiedBuffer("", "UnsupportedCharset"); fail(); } catch (UnsupportedCharsetException e) { // Expected } } @Test public void testHexDump() { assertEquals("", hexDump(EMPTY_BUFFER)); assertEquals("123456", hexDump(wrappedBuffer( new byte[] { 0x12, 0x34, 0x56 }))); assertEquals("1234567890abcdef", hexDump(wrappedBuffer( new byte[] { 0x12, 0x34, 0x56, 0x78, (byte) 0x90, (byte) 0xAB, (byte) 0xCD, (byte) 0xEF }))); } @Test public void testSwapMedium() { assertEquals(0x563412, swapMedium(0x123456)); assertEquals(0x80, swapMedium(0x800000)); } @Test public void testUnmodifiableBuffer() throws Exception { ChannelBuffer buf = unmodifiableBuffer(buffer(16)); try { buf.discardReadBytes(); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setByte(0, (byte) 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setBytes(0, EMPTY_BUFFER, 0, 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setBytes(0, new byte[0], 0, 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setBytes(0, ByteBuffer.allocate(0)); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setShort(0, (short) 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setMedium(0, 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setInt(0, 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setLong(0, 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setBytes(0, EasyMock.createMock(InputStream.class), 0); fail(); } catch (UnsupportedOperationException e) { // Expected } try { buf.setBytes(0, EasyMock.createMock(ScatteringByteChannel.class), 0); fail(); } catch (UnsupportedOperationException e) { // Expected } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/LittleEndianDirectChannelBufferTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/LittleEndianDirectChannelBufferTes0000644000175000017500000000343611210153441032624 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import java.nio.ByteOrder; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1311 $, $Date: 2009-05-29 23:50:09 -0700 (Fri, 29 May 2009) $ */ public class LittleEndianDirectChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, length); assertSame(ByteOrder.LITTLE_ENDIAN, buffer.order()); assertEquals(0, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/LittleEndianHeapChannelBufferTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/LittleEndianHeapChannelBufferTest.0000644000175000017500000000361511057746110032542 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import java.nio.ByteOrder; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 237 $, $Date: 2008-09-04 04:53:44 -0700 (Thu, 04 Sep 2008) $ */ public class LittleEndianHeapChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.buffer(ByteOrder.LITTLE_ENDIAN, length); assertEquals(0, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new LittleEndianHeapChannelBuffer(null); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/TruncatedChannelBufferTest.java0000644000175000017500000000360311057746110032160 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import org.junit.Test; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 237 $, $Date: 2008-09-04 04:53:44 -0700 (Thu, 04 Sep 2008) $ */ public class TruncatedChannelBufferTest extends AbstractChannelBufferTest { private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffer = ChannelBuffers.wrappedBuffer( new byte[length * 2], 0, length); assertEquals(length, buffer.writerIndex()); return buffer; } @Override protected ChannelBuffer[] components() { return new ChannelBuffer[] { buffer }; } @Test(expected = NullPointerException.class) public void shouldNotAllowNullInConstructor() { new TruncatedChannelBuffer(null, 0); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/LittleEndianCompositeChannelBufferTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/buffer/LittleEndianCompositeChannelBuffer0000644000175000017500000000704011055243260032701 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import static org.junit.Assert.*; import java.util.ArrayList; import java.util.List; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 146 $, $Date: 2008-08-27 05:21:04 -0700 (Wed, 27 Aug 2008) $ */ public class LittleEndianCompositeChannelBufferTest extends AbstractChannelBufferTest { private List buffers; private ChannelBuffer buffer; @Override protected ChannelBuffer newBuffer(int length) { buffers = new ArrayList(); for (int i = 0; i < length; i += 10) { buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[1])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[2])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[3])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[4])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[5])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[6])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[7])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[8])); buffers.add(ChannelBuffers.EMPTY_BUFFER); buffers.add(ChannelBuffers.wrappedBuffer(ChannelBuffers.LITTLE_ENDIAN, new byte[9])); buffers.add(ChannelBuffers.EMPTY_BUFFER); } buffer = ChannelBuffers.wrappedBuffer(buffers.toArray(new ChannelBuffer[buffers.size()])); buffer.writerIndex(length); buffer = ChannelBuffers.wrappedBuffer(buffer); assertEquals(length, buffer.capacity()); assertEquals(length, buffer.readableBytes()); assertFalse(buffer.writable()); buffer.writerIndex(0); return buffer; } @Override protected ChannelBuffer[] components() { return buffers.toArray(new ChannelBuffer[buffers.size()]); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/0000755000175000017500000000000011316313123024233 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/ssl/0000755000175000017500000000000011316313123025034 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/ssl/NioNioSocketSslEchoTest.java0000644000175000017500000000355011055465326032404 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.ssl; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 149 $, $Date: 2008-08-28 02:07:34 -0700 (Thu, 28 Aug 2008) $ * */ public class NioNioSocketSslEchoTest extends AbstractSocketSslEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/ssl/OioOioSocketSslEchoTest.java0000644000175000017500000000366411104611625032402 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.ssl; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 434 $, $Date: 2008-11-06 07:56:05 -0800 (Thu, 06 Nov 2008) $ * */ public class OioOioSocketSslEchoTest extends AbstractSocketSslEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } @Override protected boolean isExecutorRequired() { return true; } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/ssl/OioNioSocketSslEchoTest.java0000644000175000017500000000353611055465326032411 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.ssl; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 149 $, $Date: 2008-08-28 02:07:34 -0700 (Thu, 28 Aug 2008) $ * */ public class OioNioSocketSslEchoTest extends AbstractSocketSslEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/ssl/AbstractSocketSslEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/ssl/AbstractSocketSslEchoTest.jav0000644000175000017500000002132011172030314032567 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.ssl; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import javax.net.ssl.SSLEngine; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.example.securechat.SecureChatSslContextFactory; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public abstract class AbstractSocketSslEchoTest { static final InternalLogger logger = InternalLoggerFactory.getInstance(AbstractSocketSslEchoTest.class); private static final Random random = new Random(); static final byte[] data = new byte[1048576]; private static ExecutorService executor; private static ExecutorService eventExecutor; static { random.nextBytes(data); } @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); eventExecutor = new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor, eventExecutor); } protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract ChannelFactory newClientSocketChannelFactory(Executor executor); protected boolean isExecutorRequired() { return false; } @Test public void testSslEcho() throws Throwable { ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor)); ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor)); EchoHandler sh = new EchoHandler(true); EchoHandler ch = new EchoHandler(false); SSLEngine sse = SecureChatSslContextFactory.getServerContext().createSSLEngine(); SSLEngine cse = SecureChatSslContextFactory.getClientContext().createSSLEngine(); sse.setUseClientMode(false); cse.setUseClientMode(true); // Workaround for blocking I/O transport write-write dead lock. sb.setOption("receiveBufferSize", 1048576); sb.setOption("receiveBufferSize", 1048576); sb.getPipeline().addFirst("ssl", new SslHandler(sse)); sb.getPipeline().addLast("handler", sh); cb.getPipeline().addFirst("ssl", new SslHandler(cse)); cb.getPipeline().addLast("handler", ch); if (isExecutorRequired()) { sb.getPipeline().addFirst("executor",new ExecutionHandler(eventExecutor)); cb.getPipeline().addFirst("executor",new ExecutionHandler(eventExecutor)); } Channel sc = sb.bind(new InetSocketAddress(0)); int port = ((InetSocketAddress) sc.getLocalAddress()).getPort(); ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port)); ccf.awaitUninterruptibly(); if (!ccf.isSuccess()) { logger.error("Connection attempt failed", ccf.getCause()); sc.close().awaitUninterruptibly(); } assertTrue(ccf.isSuccess()); Channel cc = ccf.getChannel(); ChannelFuture hf = cc.getPipeline().get(SslHandler.class).handshake(cc); hf.awaitUninterruptibly(); if (!hf.isSuccess()) { logger.error("Handshake failed", hf.getCause()); sh.channel.close().awaitUninterruptibly(); ch.channel.close().awaitUninterruptibly(); sc.close().awaitUninterruptibly(); } assertTrue(hf.isSuccess()); for (int i = 0; i < data.length;) { int length = Math.min(random.nextInt(1024 * 64), data.length - i); cc.write(ChannelBuffers.wrappedBuffer(data, i, length)); i += length; } while (ch.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } while (sh.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } sh.channel.close().awaitUninterruptibly(); ch.channel.close().awaitUninterruptibly(); sc.close().awaitUninterruptibly(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } @ChannelPipelineCoverage("one") private class EchoHandler extends SimpleChannelUpstreamHandler { volatile Channel channel; final AtomicReference exception = new AtomicReference(); volatile int counter; private final boolean server; EchoHandler(boolean server) { this.server = server; } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer m = (ChannelBuffer) e.getMessage(); byte[] actual = new byte[m.readableBytes()]; m.getBytes(0, actual); int lastIdx = counter; for (int i = 0; i < actual.length; i ++) { assertEquals(data[i + lastIdx], actual[i]); } if (channel.getParent() != null) { channel.write(m); } counter += actual.length; } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { logger.warn( "Unexpected exception from the " + (server? "server" : "client") + " side", e.getCause()); exception.compareAndSet(null, e.getCause()); e.getChannel().close(); } } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/ssl/NioOioSocketSslEchoTest.java0000644000175000017500000000355011055465326032405 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.ssl; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 149 $, $Date: 2008-08-28 02:07:34 -0700 (Thu, 28 Aug 2008) $ * */ public class NioOioSocketSslEchoTest extends AbstractSocketSslEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/0000755000175000017500000000000011316313124025311 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/0000755000175000017500000000000011316313124026403 5ustar deckerdecker././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/OioNioSocketFixedLengthEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/OioNioSocketFixedLeng0000644000175000017500000000356611055515253032502 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioNioSocketFixedLengthEchoTest extends AbstractSocketFixedLengthEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/NioOioSocketFixedLengthEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/NioOioSocketFixedLeng0000644000175000017500000000360011055515253032467 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioOioSocketFixedLengthEchoTest extends AbstractSocketFixedLengthEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/AbstractSocketFixedLengthEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/AbstractSocketFixedLe0000644000175000017500000001541611172030314032507 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public abstract class AbstractSocketFixedLengthEchoTest { private static final Random random = new Random(); static final byte[] data = new byte[1048576]; private static ExecutorService executor; static { random.nextBytes(data); } @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract ChannelFactory newClientSocketChannelFactory(Executor executor); @Test public void testFixedLengthEcho() throws Throwable { ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor)); ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor)); EchoHandler sh = new EchoHandler(); EchoHandler ch = new EchoHandler(); sb.getPipeline().addLast("decoder", new FixedLengthFrameDecoder(1024)); sb.getPipeline().addAfter("decoder", "handler", sh); cb.getPipeline().addLast("decoder", new FixedLengthFrameDecoder(1024)); cb.getPipeline().addAfter("decoder", "handler", ch); Channel sc = sb.bind(new InetSocketAddress(0)); int port = ((InetSocketAddress) sc.getLocalAddress()).getPort(); ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port)); assertTrue(ccf.awaitUninterruptibly().isSuccess()); Channel cc = ccf.getChannel(); for (int i = 0; i < data.length;) { int length = Math.min(random.nextInt(1024 * 64), data.length - i); cc.write(ChannelBuffers.wrappedBuffer(data, i, length)); i += length; } while (ch.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } while (sh.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } sh.channel.close().awaitUninterruptibly(); ch.channel.close().awaitUninterruptibly(); sc.close().awaitUninterruptibly(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } @ChannelPipelineCoverage("one") private class EchoHandler extends SimpleChannelUpstreamHandler { volatile Channel channel; final AtomicReference exception = new AtomicReference(); volatile int counter; EchoHandler() { super(); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer m = (ChannelBuffer) e.getMessage(); assertEquals(1024, m.readableBytes()); byte[] actual = new byte[m.readableBytes()]; m.getBytes(0, actual); int lastIdx = counter; for (int i = 0; i < actual.length; i ++) { assertEquals(data[i + lastIdx], actual[i]); } if (channel.getParent() != null) { channel.write(m); } counter += actual.length; } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (exception.compareAndSet(null, e.getCause())) { e.getChannel().close(); } } } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/OioOioSocketFixedLengthEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/OioOioSocketFixedLeng0000644000175000017500000000356611055515253032503 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioOioSocketFixedLengthEchoTest extends AbstractSocketFixedLengthEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/NioNioSocketFixedLengthEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/frame/NioNioSocketFixedLeng0000644000175000017500000000360011055515253032466 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioNioSocketFixedLengthEchoTest extends AbstractSocketFixedLengthEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/http/0000755000175000017500000000000011316313123026267 5ustar deckerdecker././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/http/CookieDecoderTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/http/CookieDecoderTest.java0000644000175000017500000003130411216747541032510 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import static org.junit.Assert.*; import java.util.Date; import java.util.Iterator; import java.util.Set; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class CookieDecoderTest { @Test public void testDecodingSingleCookieV0() { String cookieString = "myCookie=myValue;expires=XXX;path=/apathsomewhere;domain=.adomainsomewhere;secure;"; cookieString = cookieString.replace("XXX", new CookieDateFormat().format(new Date(System.currentTimeMillis() + 50000))); CookieDecoder cookieDecoder = new CookieDecoder(); Set cookies = cookieDecoder.decode(cookieString); assertEquals(1, cookies.size()); Cookie cookie = cookies.iterator().next(); assertNotNull(cookie); assertEquals("myValue", cookie.getValue()); assertNull(cookie.getComment()); assertNull(cookie.getCommentUrl()); assertEquals(".adomainsomewhere", cookie.getDomain()); assertFalse(cookie.isDiscard()); boolean fail = true; for (int i = 40; i <= 60; i ++) { if (cookie.getMaxAge() == i) { fail = false; break; } } if (fail) { fail("expected: 50, actual: " + cookie.getMaxAge()); } assertEquals("/apathsomewhere", cookie.getPath()); assertTrue(cookie.getPorts().isEmpty()); assertTrue(cookie.isSecure()); assertEquals(0, cookie.getVersion()); } @Test public void testDecodingSingleCookieV0ExtraParamsIgnored() { String cookieString = "myCookie=myValue;max-age=50;path=/apathsomewhere;domain=.adomainsomewhere;secure;comment=this is a comment;version=0;commentURL=http://aurl.com;port=\"80,8080\";discard;"; CookieDecoder cookieDecoder = new CookieDecoder(); Set cookies = cookieDecoder.decode(cookieString); assertEquals(1, cookies.size()); Cookie cookie = cookies.iterator().next(); assertNotNull(cookie); assertEquals("myValue", cookie.getValue()); assertNull(cookie.getComment()); assertNull(cookie.getCommentUrl()); assertEquals(".adomainsomewhere", cookie.getDomain()); assertFalse(cookie.isDiscard()); assertEquals(50, cookie.getMaxAge()); assertEquals("/apathsomewhere", cookie.getPath()); assertTrue(cookie.getPorts().isEmpty()); assertTrue(cookie.isSecure()); assertEquals(0, cookie.getVersion()); } @Test public void testDecodingSingleCookieV1() { String cookieString = "myCookie=myValue;max-age=50;path=/apathsomewhere;domain=.adomainsomewhere;secure;comment=this is a comment;version=1;"; CookieDecoder cookieDecoder = new CookieDecoder(); Set cookies = cookieDecoder.decode(cookieString); assertEquals(1, cookies.size()); Cookie cookie = cookies.iterator().next(); assertEquals("myValue", cookie.getValue()); assertNotNull(cookie); assertEquals("this is a comment", cookie.getComment()); assertNull(cookie.getCommentUrl()); assertEquals(".adomainsomewhere", cookie.getDomain()); assertFalse(cookie.isDiscard()); assertEquals(50, cookie.getMaxAge()); assertEquals("/apathsomewhere", cookie.getPath()); assertTrue(cookie.getPorts().isEmpty()); assertTrue(cookie.isSecure()); assertEquals(1, cookie.getVersion()); } @Test public void testDecodingSingleCookieV1ExtraParamsIgnored() { String cookieString = "myCookie=myValue;max-age=50;path=/apathsomewhere;domain=.adomainsomewhere;secure;comment=this is a comment;version=1;commentURL=http://aurl.com;port='80,8080';discard;"; CookieDecoder cookieDecoder = new CookieDecoder(); Set cookies = cookieDecoder.decode(cookieString); assertEquals(1, cookies.size()); Cookie cookie = cookies.iterator().next(); assertNotNull(cookie); assertEquals("myValue", cookie.getValue()); assertEquals("this is a comment", cookie.getComment()); assertNull(cookie.getCommentUrl()); assertEquals(".adomainsomewhere", cookie.getDomain()); assertFalse(cookie.isDiscard()); assertEquals(50, cookie.getMaxAge()); assertEquals("/apathsomewhere", cookie.getPath()); assertTrue(cookie.getPorts().isEmpty()); assertTrue(cookie.isSecure()); assertEquals(1, cookie.getVersion()); } @Test public void testDecodingSingleCookieV2() { String cookieString = "myCookie=myValue;max-age=50;path=/apathsomewhere;domain=.adomainsomewhere;secure;comment=this is a comment;version=2;commentURL=http://aurl.com;port=\"80,8080\";discard;"; CookieDecoder cookieDecoder = new CookieDecoder(); Set cookies = cookieDecoder.decode(cookieString); assertEquals(1, cookies.size()); Cookie cookie = cookies.iterator().next(); assertNotNull(cookie); assertEquals("myValue", cookie.getValue()); assertEquals("this is a comment", cookie.getComment()); assertEquals("http://aurl.com", cookie.getCommentUrl()); assertEquals(".adomainsomewhere", cookie.getDomain()); assertTrue(cookie.isDiscard()); assertEquals(50, cookie.getMaxAge()); assertEquals("/apathsomewhere", cookie.getPath()); assertEquals(2, cookie.getPorts().size()); assertTrue(cookie.getPorts().contains(80)); assertTrue(cookie.getPorts().contains(8080)); assertTrue(cookie.isSecure()); assertEquals(2, cookie.getVersion()); } @Test public void testDecodingMultipleCookies() { String c1 = "myCookie=myValue;max-age=50;path=/apathsomewhere;domain=.adomainsomewhere;secure;comment=this is a comment;version=2;commentURL=\"http://aurl.com\";port='80,8080';discard;"; String c2 = "myCookie2=myValue2;max-age=0;path=/anotherpathsomewhere;domain=.anotherdomainsomewhere;comment=this is another comment;version=2;commentURL=http://anotherurl.com;"; String c3 = "myCookie3=myValue3;max-age=0;version=2;"; CookieDecoder decoder = new CookieDecoder(); Set cookies = decoder.decode(c1 + c2 + c3); assertEquals(3, cookies.size()); Iterator it = cookies.iterator(); Cookie cookie = it.next(); assertNotNull(cookie); assertEquals("myValue", cookie.getValue()); assertEquals("this is a comment", cookie.getComment()); assertEquals("http://aurl.com", cookie.getCommentUrl()); assertEquals(".adomainsomewhere", cookie.getDomain()); assertTrue(cookie.isDiscard()); assertEquals(50, cookie.getMaxAge()); assertEquals("/apathsomewhere", cookie.getPath()); assertEquals(2, cookie.getPorts().size()); assertTrue(cookie.getPorts().contains(80)); assertTrue(cookie.getPorts().contains(8080)); assertTrue(cookie.isSecure()); assertEquals(2, cookie.getVersion()); cookie = it.next(); assertNotNull(cookie); assertEquals("myValue2", cookie.getValue()); assertEquals("this is another comment", cookie.getComment()); assertEquals("http://anotherurl.com", cookie.getCommentUrl()); assertEquals(".anotherdomainsomewhere", cookie.getDomain()); assertFalse(cookie.isDiscard()); assertEquals(0, cookie.getMaxAge()); assertEquals("/anotherpathsomewhere", cookie.getPath()); assertTrue(cookie.getPorts().isEmpty()); assertFalse(cookie.isSecure()); assertEquals(2, cookie.getVersion()); cookie = it.next(); assertNotNull(cookie); assertEquals("myValue3", cookie.getValue()); assertNull( cookie.getComment()); assertNull(cookie.getCommentUrl()); assertNull(cookie.getDomain()); assertFalse(cookie.isDiscard()); assertEquals(0, cookie.getMaxAge()); assertNull(cookie.getPath()); assertTrue(cookie.getPorts().isEmpty()); assertFalse(cookie.isSecure()); assertEquals(2, cookie.getVersion()); } @Test public void testDecodingClientSideCookies() { String source = "$Version=\"1\"; " + "Part_Number=\"Riding_Rocket_0023\"; $Path=\"/acme/ammo\"; " + "Part_Number=\"Rocket_Launcher_0001\"; $Path=\"/acme\""; Set cookies = new CookieDecoder().decode(source); Iterator it = cookies.iterator(); Cookie c; c = it.next(); assertEquals(1, c.getVersion()); assertEquals("Part_Number", c.getName()); assertEquals("Rocket_Launcher_0001", c.getValue()); assertEquals("/acme", c.getPath()); assertNull(c.getComment()); assertNull(c.getCommentUrl()); assertNull(c.getDomain()); assertTrue(c.getPorts().isEmpty()); assertEquals(-1, c.getMaxAge()); c = it.next(); assertEquals(1, c.getVersion()); assertEquals("Part_Number", c.getName()); assertEquals("Riding_Rocket_0023", c.getValue()); assertEquals("/acme/ammo", c.getPath()); assertNull(c.getComment()); assertNull(c.getCommentUrl()); assertNull(c.getDomain()); assertTrue(c.getPorts().isEmpty()); assertEquals(-1, c.getMaxAge()); } @Test public void testDecodingCommaSeparatedClientSideCookies() { String source = "$Version=\"1\"; session_id=\"1234\", " + "$Version=\"1\"; session_id=\"1111\"; $Domain=\".cracker.edu\""; Set cookies = new CookieDecoder().decode(source); Iterator it = cookies.iterator(); Cookie c; c = it.next(); assertEquals(1, c.getVersion()); assertEquals("session_id", c.getName()); assertEquals("1234", c.getValue()); assertNull(c.getPath()); assertNull(c.getComment()); assertNull(c.getCommentUrl()); assertNull(c.getDomain()); assertTrue(c.getPorts().isEmpty()); assertEquals(-1, c.getMaxAge()); c = it.next(); assertEquals(1, c.getVersion()); assertEquals("session_id", c.getName()); assertEquals("1111", c.getValue()); assertEquals(".cracker.edu", c.getDomain()); assertNull(c.getPath()); assertNull(c.getComment()); assertNull(c.getCommentUrl()); assertTrue(c.getPorts().isEmpty()); assertEquals(-1, c.getMaxAge()); } @Test public void testDecodingQuotedCookie() { String source = "a=\"\"," + "b=\"1\"," + "c=\"\\\"1\\\"2\\\"\"," + "d=\"1\\\"2\\\"3\"," + "e=\"\\\"\\\"\"," + "f=\"1\\\"\\\"2\"," + "g=\"\\\\\""; Set cookies = new CookieDecoder().decode(source); Iterator it = cookies.iterator(); Cookie c; c = it.next(); assertEquals("a", c.getName()); assertEquals("", c.getValue()); c = it.next(); assertEquals("b", c.getName()); assertEquals("1", c.getValue()); c = it.next(); assertEquals("c", c.getName()); assertEquals("\"1\"2\"", c.getValue()); c = it.next(); assertEquals("d", c.getName()); assertEquals("1\"2\"3", c.getValue()); c = it.next(); assertEquals("e", c.getName()); assertEquals("\"\"", c.getValue()); c = it.next(); assertEquals("f", c.getName()); assertEquals("1\"\"2", c.getValue()); c = it.next(); assertEquals("g", c.getName()); assertEquals("\\", c.getValue()); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/http/CookieEncoderTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/http/CookieEncoderTest.java0000644000175000017500000001344111216747541032524 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import static org.junit.Assert.*; import java.text.DateFormat; import java.util.Date; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class CookieEncoderTest { @Test public void testEncodingSingleCookieV0() { String result = "myCookie=myValue;Expires=XXX;Path=/apathsomewhere;Domain=.adomainsomewhere;Secure"; DateFormat df = new CookieDateFormat(); Cookie cookie = new DefaultCookie("myCookie", "myValue"); CookieEncoder encoder = new CookieEncoder(true); encoder.addCookie(cookie); cookie.setComment("this is a Comment"); cookie.setCommentUrl("http://aurl.com"); cookie.setDomain(".adomainsomewhere"); cookie.setDiscard(true); cookie.setMaxAge(50); cookie.setPath("/apathsomewhere"); cookie.setPorts(80, 8080); cookie.setSecure(true); String encodedCookie = encoder.encode(); long currentTime = System.currentTimeMillis(); boolean fail = true; // +/- 10-second tolerance for (int delta = 0; delta <= 20000; delta += 250) { if (encodedCookie.equals(result.replace( "XXX", df.format(new Date(currentTime + 40000 + delta))))) { fail = false; break; } } if (fail) { fail("Expected: " + result + ", Actual: " + encodedCookie); } } @Test public void testEncodingSingleCookieV1() { String result = "myCookie=myValue;Max-Age=50;Path=\"/apathsomewhere\";Domain=.adomainsomewhere;Secure;Comment=\"this is a Comment\";Version=1"; Cookie cookie = new DefaultCookie("myCookie", "myValue"); CookieEncoder encoder = new CookieEncoder(true); encoder.addCookie(cookie); cookie.setVersion(1); cookie.setComment("this is a Comment"); cookie.setDomain(".adomainsomewhere"); cookie.setMaxAge(50); cookie.setPath("/apathsomewhere"); cookie.setSecure(true); String encodedCookie = encoder.encode(); assertEquals(result, encodedCookie); } @Test public void testEncodingSingleCookieV2() { String result = "myCookie=myValue;Max-Age=50;Path=\"/apathsomewhere\";Domain=.adomainsomewhere;Secure;Comment=\"this is a Comment\";Version=1;CommentURL=\"http://aurl.com\";Port=\"80,8080\";Discard"; Cookie cookie = new DefaultCookie("myCookie", "myValue"); CookieEncoder encoder = new CookieEncoder(true); encoder.addCookie(cookie); cookie.setVersion(1); cookie.setComment("this is a Comment"); cookie.setCommentUrl("http://aurl.com"); cookie.setDomain(".adomainsomewhere"); cookie.setDiscard(true); cookie.setMaxAge(50); cookie.setPath("/apathsomewhere"); cookie.setPorts(80, 8080); cookie.setSecure(true); String encodedCookie = encoder.encode(); assertEquals(result, encodedCookie); } @Test public void testEncodingMultipleCookies() { String c1 = "myCookie=myValue;Max-Age=50;Path=\"/apathsomewhere\";Domain=.adomainsomewhere;Secure;Comment=\"this is a Comment\";Version=1;CommentURL=\"http://aurl.com\";Port=\"80,8080\";Discard;"; String c2 = "myCookie2=myValue2;Path=\"/anotherpathsomewhere\";Domain=.anotherdomainsomewhere;Comment=\"this is another Comment\";Version=1;CommentURL=\"http://anotherurl.com\";"; String c3 = "myCookie3=myValue3;Version=1"; CookieEncoder encoder = new CookieEncoder(true); Cookie cookie = new DefaultCookie("myCookie", "myValue"); cookie.setVersion(1); cookie.setComment("this is a Comment"); cookie.setCommentUrl("http://aurl.com"); cookie.setDomain(".adomainsomewhere"); cookie.setDiscard(true); cookie.setMaxAge(50); cookie.setPath("/apathsomewhere"); cookie.setPorts(80, 8080); cookie.setSecure(true); encoder.addCookie(cookie); Cookie cookie2 = new DefaultCookie("myCookie2", "myValue2"); cookie2.setVersion(1); cookie2.setComment("this is another Comment"); cookie2.setCommentUrl("http://anotherurl.com"); cookie2.setDomain(".anotherdomainsomewhere"); cookie2.setDiscard(false); cookie2.setPath("/anotherpathsomewhere"); cookie2.setSecure(false); encoder.addCookie(cookie2); Cookie cookie3 = new DefaultCookie("myCookie3", "myValue3"); cookie3.setVersion(1); encoder.addCookie(cookie3); String encodedCookie = encoder.encode(); assertEquals(c1 + c2 + c3, encodedCookie); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/0000755000175000017500000000000011316313123026616 5ustar deckerdecker././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/NioNioSocketStringEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/NioNioSocketStringEc0000644000175000017500000000356711055515253032567 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.string; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioNioSocketStringEchoTest extends AbstractSocketStringEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/OioNioSocketStringEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/OioNioSocketStringEc0000644000175000017500000000355511055515253032565 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.string; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioNioSocketStringEchoTest extends AbstractSocketStringEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/NioOioSocketStringEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/NioOioSocketStringEc0000644000175000017500000000356711055515253032570 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.string; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioOioSocketStringEchoTest extends AbstractSocketStringEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/AbstractSocketStringEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/AbstractSocketString0000644000175000017500000001624611172030314032653 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.string; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public abstract class AbstractSocketStringEchoTest { static final Random random = new Random(); static final String[] data = new String[1024]; private static ExecutorService executor; static { for (int i = 0; i < data.length; i ++) { int eLen = random.nextInt(512); char[] e = new char[eLen]; for (int j = 0; j < eLen; j ++) { e[j] = (char) ('a' + random.nextInt(26)); } data[i] = new String(e); } } @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract ChannelFactory newClientSocketChannelFactory(Executor executor); @Test public void testStringEcho() throws Throwable { ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor)); ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor)); EchoHandler sh = new EchoHandler(); EchoHandler ch = new EchoHandler(); sb.getPipeline().addLast("framer", new DelimiterBasedFrameDecoder(512, Delimiters.lineDelimiter())); sb.getPipeline().addLast("decoder", new StringDecoder("ISO-8859-1")); sb.getPipeline().addBefore("decoder", "encoder", new StringEncoder("ISO-8859-1")); sb.getPipeline().addAfter("decoder", "handler", sh); cb.getPipeline().addLast("framer", new DelimiterBasedFrameDecoder(512, Delimiters.lineDelimiter())); cb.getPipeline().addLast("decoder", new StringDecoder("ISO-8859-1")); cb.getPipeline().addBefore("decoder", "encoder", new StringEncoder("ISO-8859-1")); cb.getPipeline().addAfter("decoder", "handler", ch); Channel sc = sb.bind(new InetSocketAddress(0)); int port = ((InetSocketAddress) sc.getLocalAddress()).getPort(); ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port)); assertTrue(ccf.awaitUninterruptibly().isSuccess()); Channel cc = ccf.getChannel(); for (String element : data) { String delimiter = random.nextBoolean() ? "\r\n" : "\n"; cc.write(element + delimiter); } while (ch.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } while (sh.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } sh.channel.close().awaitUninterruptibly(); ch.channel.close().awaitUninterruptibly(); sc.close().awaitUninterruptibly(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } @ChannelPipelineCoverage("one") private class EchoHandler extends SimpleChannelUpstreamHandler { volatile Channel channel; final AtomicReference exception = new AtomicReference(); volatile int counter; EchoHandler() { super(); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String m = (String) e.getMessage(); assertEquals(data[counter], m); if (channel.getParent() != null) { String delimiter = random.nextBoolean() ? "\r\n" : "\n"; channel.write(m + delimiter); } counter ++; } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (exception.compareAndSet(null, e.getCause())) { e.getChannel().close(); } } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/OioOioSocketStringEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/string/OioOioSocketStringEc0000644000175000017500000000355511055515253032566 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.string; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioOioSocketStringEchoTest extends AbstractSocketStringEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/0000755000175000017500000000000011316313124030166 5ustar deckerdecker././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioOioSocketObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioOioSocketO0000644000175000017500000000360011055515253032604 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioOioSocketObjectStreamEchoTest extends AbstractSocketObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioOioSocketCompatibleObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioOioSocketC0000644000175000017500000000363611055515253032600 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioOioSocketCompatibleObjectStreamEchoTest extends AbstractSocketCompatibleObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioNioSocketObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioNioSocketO0000644000175000017500000000360011055515253032603 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioNioSocketObjectStreamEchoTest extends AbstractSocketObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioOioSocketCompatibleObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioOioSocketC0000644000175000017500000000362411055515253032576 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioOioSocketCompatibleObjectStreamEchoTest extends AbstractSocketCompatibleObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000017700000000000011572 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/AbstractSocketObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/AbstractSocke0000644000175000017500000001512311172030314032640 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public abstract class AbstractSocketObjectStreamEchoTest { static final Random random = new Random(); static final String[] data = new String[1024]; private static ExecutorService executor; static { for (int i = 0; i < data.length; i ++) { int eLen = random.nextInt(512); char[] e = new char[eLen]; for (int j = 0; j < eLen; j ++) { e[j] = (char) ('a' + random.nextInt(26)); } data[i] = new String(e); } } @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract ChannelFactory newClientSocketChannelFactory(Executor executor); @Test public void testObjectEcho() throws Throwable { ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor)); ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor)); EchoHandler sh = new EchoHandler(); EchoHandler ch = new EchoHandler(); sb.getPipeline().addLast("decoder", new ObjectDecoder()); sb.getPipeline().addLast("encoder", new ObjectEncoder()); sb.getPipeline().addLast("handler", sh); cb.getPipeline().addLast("decoder", new ObjectDecoder()); cb.getPipeline().addLast("encoder", new ObjectEncoder()); cb.getPipeline().addLast("handler", ch); Channel sc = sb.bind(new InetSocketAddress(0)); int port = ((InetSocketAddress) sc.getLocalAddress()).getPort(); ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port)); assertTrue(ccf.awaitUninterruptibly().isSuccess()); Channel cc = ccf.getChannel(); for (String element : data) { cc.write(element); } while (ch.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } while (sh.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } sh.channel.close().awaitUninterruptibly(); ch.channel.close().awaitUninterruptibly(); sc.close().awaitUninterruptibly(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } @ChannelPipelineCoverage("one") private class EchoHandler extends SimpleChannelUpstreamHandler { volatile Channel channel; final AtomicReference exception = new AtomicReference(); volatile int counter; EchoHandler() { super(); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String m = (String) e.getMessage(); assertEquals(data[counter], m); if (channel.getParent() != null) { channel.write(m); } counter ++; } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (exception.compareAndSet(null, e.getCause())) { e.getChannel().close(); } } } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioNioSocketCompatibleObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioNioSocketC0000644000175000017500000000363611055515253032577 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioNioSocketCompatibleObjectStreamEchoTest extends AbstractSocketCompatibleObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000020700000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioNioSocketCompatibleObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/OioNioSocketC0000644000175000017500000000362411055515253032575 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class OioNioSocketCompatibleObjectStreamEchoTest extends AbstractSocketCompatibleObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new OioClientSocketChannelFactory(executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioNioSocketObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioNioSocketO0000644000175000017500000000361211055515253032605 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioNioSocketObjectStreamEchoTest extends AbstractSocketObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000021100000000000011557 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/AbstractSocketCompatibleObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/AbstractSocke0000644000175000017500000001526411172030314032646 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import static org.junit.Assert.*; import java.io.IOException; import java.net.InetSocketAddress; import java.util.Random; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.util.TestUtil; import org.jboss.netty.util.internal.ExecutorUtil; import org.junit.AfterClass; import org.junit.BeforeClass; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ public abstract class AbstractSocketCompatibleObjectStreamEchoTest { static final Random random = new Random(); static final String[] data = new String[1024]; private static ExecutorService executor; static { for (int i = 0; i < data.length; i ++) { int eLen = random.nextInt(512); char[] e = new char[eLen]; for (int j = 0; j < eLen; j ++) { e[j] = (char) ('a' + random.nextInt(26)); } data[i] = new String(e); } } @BeforeClass public static void init() { executor = Executors.newCachedThreadPool(); } @AfterClass public static void destroy() { ExecutorUtil.terminate(executor); } protected abstract ChannelFactory newServerSocketChannelFactory(Executor executor); protected abstract ChannelFactory newClientSocketChannelFactory(Executor executor); @Test @SuppressWarnings("deprecation") public void testCompatibleObjectEcho() throws Throwable { ServerBootstrap sb = new ServerBootstrap(newServerSocketChannelFactory(executor)); ClientBootstrap cb = new ClientBootstrap(newClientSocketChannelFactory(executor)); EchoHandler sh = new EchoHandler(); EchoHandler ch = new EchoHandler(); sb.getPipeline().addLast("decoder", new CompatibleObjectDecoder()); sb.getPipeline().addLast("encoder", new CompatibleObjectEncoder()); sb.getPipeline().addLast("handler", sh); cb.getPipeline().addLast("decoder", new CompatibleObjectDecoder()); cb.getPipeline().addLast("encoder", new CompatibleObjectEncoder()); cb.getPipeline().addLast("handler", ch); Channel sc = sb.bind(new InetSocketAddress(0)); int port = ((InetSocketAddress) sc.getLocalAddress()).getPort(); ChannelFuture ccf = cb.connect(new InetSocketAddress(TestUtil.getLocalHost(), port)); assertTrue(ccf.awaitUninterruptibly().isSuccess()); Channel cc = ccf.getChannel(); for (String element : data) { cc.write(element); } while (ch.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } while (sh.counter < data.length) { if (sh.exception.get() != null) { break; } if (ch.exception.get() != null) { break; } try { Thread.sleep(1); } catch (InterruptedException e) { // Ignore. } } sh.channel.close().awaitUninterruptibly(); ch.channel.close().awaitUninterruptibly(); sc.close().awaitUninterruptibly(); if (sh.exception.get() != null && !(sh.exception.get() instanceof IOException)) { throw sh.exception.get(); } if (ch.exception.get() != null && !(ch.exception.get() instanceof IOException)) { throw ch.exception.get(); } if (sh.exception.get() != null) { throw sh.exception.get(); } if (ch.exception.get() != null) { throw ch.exception.get(); } } @ChannelPipelineCoverage("one") private class EchoHandler extends SimpleChannelUpstreamHandler { volatile Channel channel; final AtomicReference exception = new AtomicReference(); volatile int counter; EchoHandler() { super(); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String m = (String) e.getMessage(); assertEquals(data[counter], m); if (channel.getParent() != null) { channel.write(m); } counter ++; } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (exception.compareAndSet(null, e.getCause())) { e.getChannel().close(); } } } } ././@LongLink0000000000000000000000000000017500000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioOioSocketObjectStreamEchoTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/serialization/NioOioSocketO0000644000175000017500000000361211055515253032606 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 154 $, $Date: 2008-08-28 05:31:39 -0700 (Thu, 28 Aug 2008) $ * */ public class NioOioSocketObjectStreamEchoTest extends AbstractSocketObjectStreamEchoTest { @Override protected ChannelFactory newClientSocketChannelFactory(Executor executor) { return new NioClientSocketChannelFactory(executor, executor); } @Override protected ChannelFactory newServerSocketChannelFactory(Executor executor) { return new OioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/replay/0000755000175000017500000000000011316313124026605 5ustar deckerdecker././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/replay/ReplayingDecoderTest.javalibnetty-java-3.1.0.CR1.orig/src/test/java/org/jboss/netty/handler/codec/replay/ReplayingDecoderTest0000644000175000017500000000556111216747541032634 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.replay; import static org.junit.Assert.*; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferIndexFinder; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.embedder.DecoderEmbedder; import org.junit.Test; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class ReplayingDecoderTest { @Test public void testLineProtocol() { DecoderEmbedder e = new DecoderEmbedder( new LineDecoder()); // Ordinary input e.offer(ChannelBuffers.wrappedBuffer(new byte[] { 'A' })); assertNull(e.poll()); e.offer(ChannelBuffers.wrappedBuffer(new byte[] { 'B' })); assertNull(e.poll()); e.offer(ChannelBuffers.wrappedBuffer(new byte[] { 'C' })); assertNull(e.poll()); e.offer(ChannelBuffers.wrappedBuffer(new byte[] { '\n' })); assertEquals(ChannelBuffers.wrappedBuffer(new byte[] { 'A', 'B', 'C' }), e.poll()); // Truncated input e.offer(ChannelBuffers.wrappedBuffer(new byte[] { 'A' })); assertNull(e.poll()); e.finish(); assertNull(e.poll()); } private static final class LineDecoder extends ReplayingDecoder { LineDecoder() { super(); } @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, VoidEnum state) throws Exception { ChannelBuffer msg = buffer.readBytes(ChannelBufferIndexFinder.LF); buffer.skipBytes(1); return msg; } } } libnetty-java-3.1.0.CR1.orig/src/main/0000755000175000017500000000000011316313154016574 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/0000755000175000017500000000000011316313126017514 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/0000755000175000017500000000000011316313126020303 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/0000755000175000017500000000000011316313126021423 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/0000755000175000017500000000000011316313152022565 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/0000755000175000017500000000000011316313140024172 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelDownstreamHandler.java0000644000175000017500000001345611216125162031764 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; /** * Handles or intercepts a downstream {@link ChannelEvent}, and sends a * {@link ChannelEvent} to the previous or next handler in a * {@link ChannelPipeline}. * *

Downstream events

*

* A downstream event is an event which is supposed to be processed from the * last handler to the first handler in a {@link ChannelPipeline}. * For example, all I/O requests made by a user application are downstream * events. *

* The most common use case of this interface is to intercept an I/O request * such as {@link Channel#write(Object)} and {@link Channel#close()}. The * received {@link ChannelEvent} object is interpreted as described in the * following table: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Event nameEvent type and conditionMeaning
{@code "write"}{@link MessageEvent}Send a message to the {@link Channel}.
{@code "bind"}{@link ChannelStateEvent}
(state = {@link ChannelState#BOUND BOUND}, value = {@link SocketAddress})
Bind the {@link Channel} to the specified local address.
{@code "unbind"}{@link ChannelStateEvent}
(state = {@link ChannelState#BOUND BOUND}, value = {@code null})
Unbind the {@link Channel} from the current local address.
{@code "connect"}{@link ChannelStateEvent}
(state = {@link ChannelState#CONNECTED CONNECTED}, value = {@link SocketAddress})
Connect the {@link Channel} to the specified remote address.
{@code "disconnect"}{@link ChannelStateEvent}
(state = {@link ChannelState#CONNECTED CONNECTED}, value = {@code null})
Disconnect the {@link Channel} from the current remote address.
{@code "close"}{@link ChannelStateEvent}
(state = {@link ChannelState#OPEN OPEN}, value = {@code false})
Close the {@link Channel}.
*

* Other event types and conditions which were not addressed here will be * ignored and discarded. Please note that there's no {@code "open"} in the * table. It is because a {@link Channel} is always open when it is created * by a {@link ChannelFactory}. * *

Additional resources worth reading

*

* You might want to refer to {@link ChannelUpstreamHandler} to see how a * {@link ChannelEvent} is interpreted when going upstream. Also, please refer * to the {@link ChannelEvent} and {@link ChannelPipeline} documentation to find * out what an upstream event and a downstream event are, what fundamental * differences they have, and how they flow in a pipeline. * *

Firing an event to the previous or next handler

*

* You can forward the received event downstream or upstream. In most cases, * {@link ChannelDownstreamHandler} will pass the event to the previous * handler (downstream) although it is legal to pass the event to the next * handler (upstream): * *

 * // Sending the event forward (downstream)
 * void handleDownstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *     ...
 *     ctx.sendDownstream(e);
 *     ...
 * }
 *
 * // Sending the event backward (upstream)
 * void handleDownstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *     ...
 *     ctx.sendUpstream(new DefaultChannelStateEvent(...));
 *     ...
 * }
 * 
* *

Using the helper class to send an event

*

* You will also find various helper methods in {@link Channels} to be useful * to generate and send an artificial or manipulated event. * *

Thread safety

*

* {@link #handleDownstream(ChannelHandlerContext, ChannelEvent) handleDownstream} * may be invoked by more than one thread simultaneously. If the handler * accesses a shared resource or stores stateful information, you might need * proper synchronization in the handler implementation. *

* Also, please refer to the {@link ChannelPipelineCoverage} annotation to * understand the relationship between a handler and its stateful properties. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1403 $, $Date: 2009-06-17 01:33:54 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.exclude ^org\.jboss\.netty\.handler\..*$ */ public interface ChannelDownstreamHandler extends ChannelHandler { /** * Handles the specified downstream event. * * @param ctx the context object for this handler * @param e the downstream event to process or intercept */ void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception; } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/AdaptiveReceiveBufferSizePredictor.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/AdaptiveReceiveBufferSizePredicto0000644000175000017500000001367011175570036032657 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.ArrayList; import java.util.List; /** * The {@link ReceiveBufferSizePredictor} that automatically increases and * decreases the predicted buffer size on feed back. *

* It gradually increases the expected number of readable bytes if the previous * read fully filled the allocated buffer. It gradually decreases the expected * number of readable bytes if the read operation was not able to fill a certain * amount of the allocated buffer two times consecutively. Otherwise, it keeps * returning the same prediction. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1258 $, $Date: 2009-04-28 05:01:34 -0700 (Tue, 28 Apr 2009) $ * */ public class AdaptiveReceiveBufferSizePredictor implements ReceiveBufferSizePredictor { private static final int INDEX_INCREMENT = 4; private static final int INDEX_DECREMENT = 1; private static final int[] SIZE_TABLE; static { List sizeTable = new ArrayList(); for (int i = 1; i <= 8; i ++) { sizeTable.add(i); } for (int i = 4; i < 32; i ++) { long v = 1L << i; long inc = v >>> 4; v -= inc << 3; for (int j = 0; j < 8; j ++) { v += inc; if (v > Integer.MAX_VALUE) { sizeTable.add(Integer.MAX_VALUE); } else { sizeTable.add((int) v); } } } SIZE_TABLE = new int[sizeTable.size()]; for (int i = 0; i < SIZE_TABLE.length; i ++) { SIZE_TABLE[i] = sizeTable.get(i); } } private static int getSizeTableIndex(final int size) { if (size <= 16) { return size - 1; } int bits = 0; int v = size; do { v >>>= 1; bits ++; } while (v != 0); final int baseIdx = bits << 3; final int startIdx = baseIdx - 18; final int endIdx = baseIdx - 25; for (int i = startIdx; i >= endIdx; i --) { if (size >= SIZE_TABLE[i]) { return i; } } throw new Error("shouldn't reach here; please file a bug report."); } private static final int DEFAULT_MINIMUM = 64; private static final int DEFAULT_INITIAL = 1024; private static final int DEFAULT_MAXIMUM = 65536; private final int minIndex; private final int maxIndex; private int index; private int nextReceiveBufferSize; private boolean decreaseNow; /** * Creates a new predictor with the default parameters. With the default * parameters, the expected buffer size starts from {@code 1024}, does not * go down below {@code 64}, and does not go up above {@code 65536}. */ public AdaptiveReceiveBufferSizePredictor() { this(DEFAULT_MINIMUM, DEFAULT_INITIAL, DEFAULT_MAXIMUM); } /** * Creates a new predictor with the specified parameters. * * @param minimum the inclusive lower bound of the expected buffer size * @param initial the initial buffer size when no feed back was received * @param maximum the inclusive upper bound of the expected buffer size */ public AdaptiveReceiveBufferSizePredictor(int minimum, int initial, int maximum) { if (minimum <= 0) { throw new IllegalArgumentException("minimum: " + minimum); } if (initial < minimum) { throw new IllegalArgumentException("initial: " + initial); } if (maximum < initial) { throw new IllegalArgumentException("maximum: " + maximum); } int minIndex = getSizeTableIndex(minimum); if (SIZE_TABLE[minIndex] < minimum) { this.minIndex = minIndex + 1; } else { this.minIndex = minIndex; } int maxIndex = getSizeTableIndex(maximum); if (SIZE_TABLE[maxIndex] > maximum) { this.maxIndex = maxIndex - 1; } else { this.maxIndex = maxIndex; } index = getSizeTableIndex(initial); nextReceiveBufferSize = SIZE_TABLE[index]; } public int nextReceiveBufferSize() { return nextReceiveBufferSize; } public void previousReceiveBufferSize(int previousReceiveBufferSize) { if (previousReceiveBufferSize <= SIZE_TABLE[Math.max(0, index - INDEX_DECREMENT - 1)]) { if (decreaseNow) { index = Math.max(index - INDEX_DECREMENT, minIndex); nextReceiveBufferSize = SIZE_TABLE[index]; decreaseNow = false; } else { decreaseNow = true; } } else if (previousReceiveBufferSize >= nextReceiveBufferSize) { index = Math.min(index + INDEX_INCREMENT, maxIndex); nextReceiveBufferSize = SIZE_TABLE[index]; decreaseNow = false; } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ReceiveBufferSizePredictor.java0000644000175000017500000000477311216134140032273 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import org.jboss.netty.buffer.ChannelBuffer; /** * Predicts the number of readable bytes in the receive buffer of a * {@link Channel}. *

* It calculates the close-to-optimal capacity of the {@link ChannelBuffer} * for the next read operation depending on the actual number of read bytes * in the previous read operation. More accurate the prediction is, more * effective the memory utilization will be. *

* Once a read operation is performed and the actual number of read bytes is * known, an I/O thread will call {@link #previousReceiveBufferSize(int)} to * update the predictor so it can predict more accurately next time. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ * */ public interface ReceiveBufferSizePredictor { /** * Predicts the capacity of the {@link ChannelBuffer} for the next * read operation depending on the actual number of read bytes in the * previous read operation. * * @return the expected number of readable bytes this time */ int nextReceiveBufferSize(); /** * Updates this predictor by specifying the actual number of read bytes * in the previous read operation. * * @param previousReceiveBufferSize * the actual number of read bytes in the previous read operation */ void previousReceiveBufferSize(int previousReceiveBufferSize); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultServerChannelConfig.java0000644000175000017500000000727311216742257032256 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.Map; import java.util.Map.Entry; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.HeapChannelBufferFactory; import org.jboss.netty.channel.socket.ServerSocketChannelConfig; import org.jboss.netty.handler.timeout.WriteTimeoutHandler; /** * The default {@link ServerSocketChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1479 $, $Date: 2009-06-19 10:02:39 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultServerChannelConfig implements ChannelConfig { private volatile ChannelPipelineFactory pipelineFactory; private volatile ChannelBufferFactory bufferFactory = HeapChannelBufferFactory.getInstance(); /** * Creates a new instance. */ public DefaultServerChannelConfig() { super(); } public void setOptions(Map options) { for (Entry e: options.entrySet()) { setOption(e.getKey(), e.getValue()); } } /** * Sets an individual option. You can override this method to support * additional configuration parameters. */ public boolean setOption(String key, Object value) { if (key.equals("pipelineFactory")) { setPipelineFactory((ChannelPipelineFactory) value); } else if (key.equals("bufferFactory")) { setBufferFactory((ChannelBufferFactory) value); } else { return false; } return true; } public ChannelPipelineFactory getPipelineFactory() { return pipelineFactory; } public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) { if (pipelineFactory == null) { throw new NullPointerException("pipelineFactory"); } this.pipelineFactory = pipelineFactory; } public ChannelBufferFactory getBufferFactory() { return bufferFactory; } public void setBufferFactory(ChannelBufferFactory bufferFactory) { if (bufferFactory == null) { throw new NullPointerException("bufferFactory"); } this.bufferFactory = bufferFactory; } public int getConnectTimeoutMillis() { return 0; } public void setConnectTimeoutMillis(int connectTimeoutMillis) { // Unused } /** * @deprecated Use {@link WriteTimeoutHandler} instead. */ @Deprecated public int getWriteTimeoutMillis() { return 0; } /** * @deprecated Use {@link WriteTimeoutHandler} instead. */ @Deprecated public void setWriteTimeoutMillis(int writeTimeoutMillis) { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelHandlerContext.java0000644000175000017500000001475111216136021031260 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * Provides the properties and operations which are specific to a * {@link ChannelHandler} and the {@link ChannelPipeline} it belongs to. * Via a {@link ChannelHandlerContext}, a {@link ChannelHandler} can send * an upstream or downstream {@link ChannelEvent} to the next or previous * {@link ChannelHandler} in a pipeline, modify the behavior of the pipeline, * or store the information (attachment) which is specific to the handler. *

 *         n = the number of the handler entries in a pipeline
 *
 * +---------+ 1 .. 1 +----------+ 1    n +---------+ n    m +---------+
 * | Channel |--------| Pipeline |--------| Context |--------| Handler |
 * +---------+        +----------+        +----+----+        +----+----+
 *                                             | 1..1             |
 *                                       +-----+------+           |
 *                                       | Attachment |<----------+
 *                                       +------------+    stores
 * 
* Please note that a {@link ChannelHandler} instance can be added to more than * one {@link ChannelPipeline}. It means a single {@link ChannelHandler} * instance can have more than one {@link ChannelHandlerContext} and therefore * the single instance can be invoked with different * {@link ChannelHandlerContext}s if it is added to one or more * {@link ChannelPipeline}s more than once. *

* For example, the following handler will have as many independent attachments * as how many times it is added to pipelines, regardless if it is added to the * same pipeline multiple times or added to different pipelines multiple times: *

 * public class FactorialHandler extends SimpleUpstreamChannelHandler {
 *
 *   // This handler will receive a sequence of increasing integers starting
 *   // from 1.
 *   public void messageReceived(ChannelHandlerContext ctx, MessageEvent evt) {
 *     Integer a = (Integer) ctx.getAttachment();
 *     Integer b = (Integer) evt.getMessage();
 *
 *     if (a == null) {
 *       a = 1;
 *     }
 *
 *     ctx.setAttachment(Integer.valueOf(a * b));
 *   }
 * }
 *
 * // Different context objects are given to "f1", "f2", "f3", and "f4" even if
 * // they refer to the same handler instance.  Because the FactorialHandler
 * // stores its state in a context object (as an attachment), the factorial is
 * // calculated correctly 4 times once the two pipelines (p1 and p2) are active.
 * FactorialHandler fh = new FactorialHandler();
 *
 * ChannelPipeline p1 = Channels.pipeline();
 * p1.addLast("f1", fh);
 * p1.addLast("f2", fh);
 *
 * ChannelPipeline p2 = Channels.pipeline();
 * p2.addLast("f3", fh);
 * p2.addLast("f4", fh);
 * 
* *

Additional resources worth reading

*

* Please refer to the {@link ChannelHandler}, {@link ChannelEvent}, and * {@link ChannelPipeline} to find out what a upstream event and a downstream * event are, what fundamental differences they have, and how they flow in a * pipeline. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1407 $, $Date: 2009-06-17 02:49:05 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.owns org.jboss.netty.channel.ChannelHandler */ public interface ChannelHandlerContext { /** * Returns the {@link Channel} that the {@link ChannelPipeline} belongs to. * This method is a shortcut to getPipeline().getChannel(). */ Channel getChannel(); /** * Returns the {@link ChannelPipeline} that the {@link ChannelHandler} * belongs to. */ ChannelPipeline getPipeline(); /** * Returns the name of the {@link ChannelHandler} in the * {@link ChannelPipeline}. */ String getName(); /** * Returns the {@link ChannelHandler} that this context object is * serving. */ ChannelHandler getHandler(); /** * Returns {@code true} if and only if the {@link ChannelHandler} is an * instance of {@link ChannelUpstreamHandler}. */ boolean canHandleUpstream(); /** * Returns {@code true} if and only if the {@link ChannelHandler} is an * instance of {@link ChannelDownstreamHandler}. */ boolean canHandleDownstream(); /** * Sends the specified {@link ChannelEvent} to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline}. It is * recommended to use the event generation methods in {@link Channels} * rather than calling this method directly. */ void sendUpstream(ChannelEvent e); /** * Sends the specified {@link ChannelEvent} to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline}. It is * recommended to use the event generation methods in {@link Channels} * rather than calling this method directly. */ void sendDownstream(ChannelEvent e); /** * Retrieves an object which is {@link #setAttachment(Object) attached} to * this context. *

* As an alternative, you might want to use a {@link ChannelLocal} variable. * * @return {@code null} if no object was attached or * {@code null} was attached */ Object getAttachment(); /** * Attaches an object to this context to store a stateful information * specific to the {@link ChannelHandler} which is associated with this * context. *

* As an alternative, you might want to use a {@link ChannelLocal} variable. */ void setAttachment(Object attachment); }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/Channel.java0000644000175000017500000002554011175571125026427 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.InetSocketAddress; import java.net.SocketAddress; /** * A nexus to a network socket or a component which is capable of I/O * operations such as read, write, connect, and bind. *

* A channel provides a user: *

    *
  • the current state of the channel (e.g. is it open? is it connected?),
  • *
  • the {@linkplain ChannelConfig configuration parameters} of the channel (e.g. receive buffer size),
  • *
  • the I/O operations that the channel supports (e.g. read, write, connect, and bind), and
  • *
  • the {@link ChannelPipeline} which handles all {@linkplain ChannelEvent I/O events and requests} * associated with the channel.
  • *
* *

All I/O operations are asynchronous.

* * All I/O operations in Netty are asynchronous. It means any I/O calls will * return immediately with no guarantee that the requested I/O operation has * been completed at the end of the call. Instead, you will be returned with * a {@link ChannelFuture} instance which tells you when the requested I/O * operation has succeeded, failed, or canceled. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1259 $, $Date: 2009-04-28 05:11:01 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark * @apiviz.composedOf org.jboss.netty.channel.ChannelConfig * @apiviz.composedOf org.jboss.netty.channel.ChannelPipeline * * @apiviz.exclude ^org\.jboss\.netty\.channel\.([a-z]+\.)+[^\.]+Channel$ */ public interface Channel extends Comparable{ /** * The {@link #getInterestOps() interestOps} value which tells that the * I/O thread will not read a message from the channel but will perform * the requested write operation immediately. */ static int OP_NONE = 0; /** * The {@link #getInterestOps() interestOps} value which tells that the * I/O thread will read a message from the channel and will perform the * requested write operation immediately. */ static int OP_READ = 1; /** * The {@link #getInterestOps() interestOps} value which tells that the * I/O thread will not read a message from the channel and will not perform * the requested write operation immediately. Any write requests made when * {@link #OP_WRITE} flag is set are queued until the I/O thread is ready * to process the queued write requests. */ static int OP_WRITE = 4; /** * The {@link #getInterestOps() interestOps} value which tells that the * I/O thread will read a message from the channel but will not perform * the requested write operation immediately. Any write requests made when * {@link #OP_WRITE} flag is set are queued until the I/O thread is ready * to process the queued write requests. */ static int OP_READ_WRITE = OP_READ | OP_WRITE; /** * Returns the unique integer ID of this channel. */ Integer getId(); /** * Returns the {@link ChannelFactory} which created this channel. */ ChannelFactory getFactory(); /** * Returns the parent of this channel. * * @return the parent channel. * {@code null} if this channel does not have a parent channel. */ Channel getParent(); /** * Returns the configuration of this channel. */ ChannelConfig getConfig(); /** * Returns the {@link ChannelPipeline} which handles {@link ChannelEvent}s * associated with this channel. */ ChannelPipeline getPipeline(); /** * Returns {@code true} if and only if this channel is open. */ boolean isOpen(); /** * Returns {@code true} if and only if this channel is bound to a * {@linkplain #getLocalAddress() local address}. */ boolean isBound(); /** * Returns {@code true} if and only if this channel is connected to a * {@linkplain #getRemoteAddress() remote address}. */ boolean isConnected(); /** * Returns the local address where this channel is bound to. The returned * {@link SocketAddress} is supposed to be down-cast into more concrete * type such as {@link InetSocketAddress} to retrieve the detailed * information. * * @return the local address of this channel. * {@code null} if this channel is not bound. */ SocketAddress getLocalAddress(); /** * Returns the remote address where this channel is connected to. The * returned {@link SocketAddress} is supposed to be down-cast into more * concrete type such as {@link InetSocketAddress} to retrieve the detailed * information. * * @return the remote address of this channel. * {@code null} if this channel is not connected. */ SocketAddress getRemoteAddress(); /** * Sends a message to this channel asynchronously. * * @param message the message to write * * @return the {@link ChannelFuture} which will be notified when the * write request succeeds or fails * * @throws NullPointerException if the specified message is {@code null} */ ChannelFuture write(Object message); /** * Sends a message to this channel asynchronously. It has an additional * parameter that allows a user to specify where to send the specified * message instead of this channel's current remote address. * * @param message the message to write * @param remoteAddress where to send the specified message. * This method is identical to {@link #write(Object)} * if {@code null} is specified here. * * @return the {@link ChannelFuture} which will be notified when the * write request succeeds or fails * * @throws NullPointerException if the specified message is {@code null} */ ChannelFuture write(Object message, SocketAddress remoteAddress); /** * Binds this channel to the specified local address asynchronously. * * @param localAddress where to bind * * @return the {@link ChannelFuture} which will be notified when the * bind request succeeds or fails * * @throws NullPointerException if the specified address is {@code null} */ ChannelFuture bind(SocketAddress localAddress); /** * Connects this channel to the specified remote address asynchronously. * * @param remoteAddress where to connect * * @return the {@link ChannelFuture} which will be notified when the * connection request succeeds or fails * * @throws NullPointerException if the specified address is {@code null} */ ChannelFuture connect(SocketAddress remoteAddress); /** * Disconnects this channel from the current remote address asynchronously. * * @return the {@link ChannelFuture} which will be notified when the * disconnection request succeeds or fails */ ChannelFuture disconnect(); /** * Unbinds this channel from the current local address asynchronously. * * @return the {@link ChannelFuture} which will be notified when the * unbind request succeeds or fails */ ChannelFuture unbind(); /** * Closes this channel asynchronously. If this channel is bound or * connected, it will be disconnected and unbound first. Once a channel * is closed, it can not be open again. Calling this method on a closed * channel has no effect. Please note that this method always returns the * same future instance. * * @return the {@link ChannelFuture} which will be notified when the * close request succeeds or fails */ ChannelFuture close(); /** * Returns the {@link ChannelFuture} which will be notified when this * channel is closed. This method always returns the same future instance. */ ChannelFuture getCloseFuture(); /** * Returns the current {@code interestOps} of this channel. * * @return {@link #OP_NONE}, {@link #OP_READ}, {@link #OP_WRITE}, or * {@link #OP_READ_WRITE} */ int getInterestOps(); /** * Returns {@code true} if and only if the I/O thread will read a message * from this channel. This method is a shortcut to the following code: *
     * return (getInterestOps() & OP_READ) != 0;
     * 
*/ boolean isReadable(); /** * Returns {@code true} if and only if the I/O thread will perform the * requested write operation immediately. Any write requests made when * this method returns {@code false} are queued until the I/O thread is * ready to process the queued write requests. This method is a shortcut * to the following code: *
     * return (getInterestOps() & OP_WRITE) != 0;
     * 
*/ boolean isWritable(); /** * Changes the {@code interestOps} of this channel asynchronously. * * @param interestOps the new {@code interestOps} * * @return the {@link ChannelFuture} which will be notified when the * {@code interestOps} change request succeeds or fails */ ChannelFuture setInterestOps(int interestOps); /** * Suspends or resumes the read operation of the I/O thread asynchronously. * This method is a shortcut to the following code: *
     * int interestOps = getInterestOps();
     * if (readable) {
     *     setInterestOps(interestOps | OP_READ);
     * } else {
     *     setInterestOps(interestOps & ~OP_READ);
     * }
     * 
* * @param readable {@code true} to resume the read operation and * {@code false} to suspend the read operation * * @return the {@link ChannelFuture} which will be notified when the * {@code interestOps} change request succeeds or fails */ ChannelFuture setReadable(boolean readable); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/FailedChannelFuture.java0000644000175000017500000000400011047765477030730 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * The {@link CompleteChannelFuture} which is failed already. It is * recommended to use {@link Channels#failedFuture(Channel, Throwable)} * instead of calling the constructor of this future. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 50 $, $Date: 2008-08-11 00:33:19 -0700 (Mon, 11 Aug 2008) $ */ public class FailedChannelFuture extends CompleteChannelFuture { private final Throwable cause; /** * Creates a new instance. * * @param channel the {@link Channel} associated with this future * @param cause the cause of failure */ public FailedChannelFuture(Channel channel, Throwable cause) { super(channel); if (cause == null) { throw new NullPointerException("cause"); } this.cause = cause; } public Throwable getCause() { return cause; } public boolean isSuccess() { return false; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelPipelineFactory.java0000644000175000017500000000332711216134140031430 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * Creates a new {@link ChannelPipeline} for a new {@link Channel}. *

* This interface was introduced to initialize the {@link ChannelPipeline} of * the child channel accepted by a {@link ServerChannel}, but it is safe to use * it for any other purposes. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.has org.jboss.netty.channel.ChannelPipeline oneway - - creates */ public interface ChannelPipelineFactory { /** * Returns a newly created {@link ChannelPipeline}. */ ChannelPipeline getPipeline() throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/WriteCompletionEvent.java0000644000175000017500000000346111142473445031203 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link ChannelEvent} which represents the notification of the completion * of a write request on a {@link Channel}. This event is for going upstream * only. Please refer to the {@link ChannelEvent} documentation to find out * what an upstream event and a downstream event are and what fundamental * differences they have. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 760 $, $Date: 2009-02-04 21:20:37 -0800 (Wed, 04 Feb 2009) $ */ public interface WriteCompletionEvent extends ChannelEvent { /** * Returns the amount of data written. * * @return the number of written bytes or messages, depending on the * type of the transport */ int getWrittenAmount(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/AbstractChannel.java0000644000175000017500000002260311165336702030107 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; import java.util.concurrent.ConcurrentMap; import org.jboss.netty.util.internal.ConcurrentHashMap; /** * A skeletal {@link Channel} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public abstract class AbstractChannel implements Channel { static final ConcurrentMap allChannels = new ConcurrentHashMap(); private static final IdDeallocator ID_DEALLOCATOR = new IdDeallocator(); private static Integer allocateId(Channel channel) { Integer id = Integer.valueOf(System.identityHashCode(channel)); for (;;) { // Loop until a unique ID is acquired. // It should be found in one loop practically. if (allChannels.putIfAbsent(id, channel) == null) { // Successfully acquired. return id; } else { // Taken by other channel at almost the same moment. id = Integer.valueOf(id.intValue() + 1); } } } private static final class IdDeallocator implements ChannelFutureListener { IdDeallocator() { super(); } public void operationComplete(ChannelFuture future) throws Exception { allChannels.remove(future.getChannel().getId()); } } private final Integer id = allocateId(this); private final Channel parent; private final ChannelFactory factory; private final ChannelPipeline pipeline; private final ChannelFuture succeededFuture = new SucceededChannelFuture(this); private final ChannelFuture closeFuture = new UnfailingChannelFuture(this, false); private volatile int interestOps = OP_READ; /** Cache for the string representation of this channel */ private String strVal; /** * Creates a new instance. * * @param parent * the parent of this channel. {@code null} if there's no parent. * @param factory * the factory which created this channel * @param pipeline * the pipeline which is going to be attached to this channel * @param sink * the sink which will receive downstream events from the pipeline * and send upstream events to the pipeline */ protected AbstractChannel( Channel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { this.parent = parent; this.factory = factory; this.pipeline = pipeline; closeFuture.addListener(ID_DEALLOCATOR); pipeline.attach(this, sink); } public final Integer getId() { return id; } public Channel getParent() { return parent; } public ChannelFactory getFactory() { return factory; } public ChannelPipeline getPipeline() { return pipeline; } /** * Returns the cached {@link SucceededChannelFuture} instance. */ protected ChannelFuture getSucceededFuture() { return succeededFuture; } /** * Returns the {@link FailedChannelFuture} whose cause is an * {@link UnsupportedOperationException}. */ protected ChannelFuture getUnsupportedOperationFuture() { return new FailedChannelFuture(this, new UnsupportedOperationException()); } /** * Returns the {@linkplain System#identityHashCode(Object) identity hash code} * of this channel. */ @Override public final int hashCode() { return System.identityHashCode(this); } /** * Returns {@code true} if and only if the specified object is identical * with this channel (i.e: {@code this == o}). */ @Override public final boolean equals(Object o) { return this == o; } /** * Compares the {@linkplain #getId() ID} of the two channels. */ public final int compareTo(Channel o) { return getId().compareTo(o.getId()); } public boolean isOpen() { return !closeFuture.isDone(); } /** * Marks this channel as closed. This method is intended to be called by * an internal component - please do not call it unless you know what you * are doing. * * @return {@code true} if and only if this channel was not marked as * closed yet */ protected boolean setClosed() { return closeFuture.setSuccess(); } public ChannelFuture bind(SocketAddress localAddress) { return Channels.bind(this, localAddress); } public ChannelFuture unbind() { return Channels.unbind(this); } public ChannelFuture close() { ChannelFuture returnedCloseFuture = Channels.close(this); assert closeFuture == returnedCloseFuture; return closeFuture; } public ChannelFuture getCloseFuture() { return closeFuture; } public ChannelFuture connect(SocketAddress remoteAddress) { return Channels.connect(this, remoteAddress); } public ChannelFuture disconnect() { return Channels.disconnect(this); } public int getInterestOps() { return interestOps; } public ChannelFuture setInterestOps(int interestOps) { return Channels.setInterestOps(this, interestOps); } /** * Sets the {@link #getInterestOps() interestOps} property of this channel * immediately. This method is intended to be called by an internal * component - please do not call it unless you know what you are doing. */ protected void setInterestOpsNow(int interestOps) { this.interestOps = interestOps; } public boolean isReadable() { return (getInterestOps() & OP_READ) != 0; } public boolean isWritable() { return (getInterestOps() & OP_WRITE) == 0; } public ChannelFuture setReadable(boolean readable) { if (readable) { return setInterestOps(getInterestOps() | OP_READ); } else { return setInterestOps(getInterestOps() & ~OP_READ); } } public ChannelFuture write(Object message) { return Channels.write(this, message); } public ChannelFuture write(Object message, SocketAddress remoteAddress) { return Channels.write(this, message, remoteAddress); } /** * Returns the {@link String} representation of this channel. The returned * string contains the {@linkplain #getId() ID}, {@linkplain #getLocalAddress() local address}, * and {@linkplain #getRemoteAddress() remote address} of this channel for * easier identification. */ @Override public String toString() { boolean connected = isConnected(); if (connected && strVal != null) { return strVal; } StringBuilder buf = new StringBuilder(128); buf.append("[id: 0x"); buf.append(getIdString()); if (connected) { buf.append(", "); if (getParent() == null) { buf.append(getLocalAddress()); buf.append(" => "); buf.append(getRemoteAddress()); } else { buf.append(getRemoteAddress()); buf.append(" => "); buf.append(getLocalAddress()); } } else if (isBound()) { buf.append(", "); buf.append(getLocalAddress()); } buf.append(']'); String strVal = buf.toString(); if (connected) { this.strVal = strVal; } else { this.strVal = null; } return strVal; } private String getIdString() { String answer = Integer.toHexString(id.intValue()); switch (answer.length()) { case 0: answer = "00000000"; break; case 1: answer = "0000000" + answer; break; case 2: answer = "000000" + answer; break; case 3: answer = "00000" + answer; break; case 4: answer = "0000" + answer; break; case 5: answer = "000" + answer; break; case 6: answer = "00" + answer; break; case 7: answer = "0" + answer; break; } return answer; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelFuture.java0000644000175000017500000002271111175603073027615 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.concurrent.TimeUnit; import org.jboss.netty.handler.execution.ExecutionHandler; /** * The result of an asynchronous {@link Channel} I/O operation. *

* All I/O operations in Netty are asynchronous. It means any I/O calls will * return immediately with no guarantee that the requested I/O operation has * been completed at the end of the call. Instead, you will be returned with * a {@link ChannelFuture} instance which tells you when the requested I/O * operation has succeeded, failed, or cancelled. *

* Various methods are provided to let you check if the I/O operation has been * completed, wait for the completion, and retrieve the result of the I/O * operation. It also allows you to add more than one {@link ChannelFutureListener} * so you can get notified when the I/O operation has been completed. * *

Prefer {@link #addListener(ChannelFutureListener)} to {@link #await()}

* * It is recommended to prefer {@link #addListener(ChannelFutureListener)} to * {@link #await()} wherever possible to get notified when an I/O operation is * done and to do any follow-up tasks. *

* {@link #addListener(ChannelFutureListener)} is non-blocking. It simply adds * the specified {@link ChannelFutureListener} to the {@link ChannelFuture}, and * I/O thread will notify the listeners when the I/O operation associated with * the future is done. {@link ChannelFutureListener} yields the best * performance and resource utilization because it does not block at all, but * it could be tricky to implement a sequential logic if you are not used to * event-driven programming. *

* By contrast, {@link #await()} is a blocking operation. Once called, the * caller thread blocks until the operation is done. It is easier to implement * a sequential logic with {@link #await()}, but the caller thread blocks * unnecessarily until the I/O operation is done and there's relatively * expensive cost of inter-thread notification. Moreover, there's a chance of * dead lock in a particular circumstance, which is described below. * *

Do not call {@link #await()} inside {@link ChannelHandler}

*

* The event handler methods in {@link ChannelHandler} is often called by * an I/O thread unless an {@link ExecutionHandler} is in the * {@link ChannelPipeline}. If {@link #await()} is called by an event handler * method, which is called by the I/O thread, the I/O operation it is waiting * for might never be complete because {@link #await()} can block the I/O * operation it is waiting for, which is a dead lock. *

 * // BAD - NEVER DO THIS
 * public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     if (e.getMessage() instanceof GoodByeMessage) {
 *         ChannelFuture future = e.getChannel().close();
 *         future.awaitUninterruptibly();
 *         // Perform post-closure operation
 *         // ...
 *     }
 * }
 *
 * // GOOD
 * public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     if (e.getMessage() instanceof GoodByeMessage) {
 *         ChannelFuture future = e.getChannel().close();
 *         future.addListener(new ChannelFutureListener() {
 *             public void operationComplete(ChannelFuture future) {
 *                 // Perform post-closure operation
 *                 // ...
 *             }
 *         });
 *     }
 * }
 * 
*

* In spite of the disadvantages mentioned above, there are certainly the cases * where it is more convenient to call {@link #await()}. In such a case, please * make sure you do not call {@link #await()} in an I/O thread. Otherwise, * {@link IllegalStateException} will be raised to prevent a dead lock. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1262 $, $Date: 2009-04-28 06:35:55 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark * @apiviz.owns org.jboss.netty.channel.ChannelFutureListener - - notifies */ public interface ChannelFuture { /** * Returns a channel where the I/O operation associated with this * future takes place. */ Channel getChannel(); /** * Returns {@code true} if and only if this future is * complete, regardless of whether the operation was successful, failed, * or cancelled. */ boolean isDone(); /** * Returns {@code true} if and only if this future was * cancelled by a {@link #cancel()} method. */ boolean isCancelled(); /** * Returns {@code true} if and only if the I/O operation was completed * successfully. */ boolean isSuccess(); /** * Returns the cause of the failed I/O operation if the I/O operation has * failed. * * @return the cause of the failure. * {@code null} if succeeded or this future is not * completed yet. */ Throwable getCause(); /** * Cancels the I/O operation associated with this future * and notifies all listeners if canceled successfully. * * @return {@code true} if and only if the operation has been canceled. * {@code false} if the operation can't be canceled or is already * completed. */ boolean cancel(); /** * Marks this future as a success and notifies all * listeners. * * @return {@code true} if and only if successfully marked this future as * a success. Otherwise {@code false} because this future is * already marked as either a success or a failure. */ boolean setSuccess(); /** * Marks this future as a failure and notifies all * listeners. * * @return {@code true} if and only if successfully marked this future as * a failure. Otherwise {@code false} because this future is * already marked as either a success or a failure. */ boolean setFailure(Throwable cause); /** * Adds the specified listener to this future. The * specified listener is notified when this future is * {@linkplain #isDone() done}. If this future is already * completed, the specified listener is notified immediately. */ void addListener(ChannelFutureListener listener); /** * Removes the specified listener from this future. * The specified listener is no longer notified when this * future is {@linkplain #isDone() done}. If this * future is already completed, this method has no effect * and returns silently. */ void removeListener(ChannelFutureListener listener); /** * Waits for this future to be completed. * * @throws InterruptedException * if the current thread was interrupted */ ChannelFuture await() throws InterruptedException; /** * Waits for this future to be completed without * interruption. This method catches an {@link InterruptedException} and * discards it silently. */ ChannelFuture awaitUninterruptibly(); /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeout, TimeUnit unit) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeoutMillis) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeout, TimeUnit unit); /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeoutMillis); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/0000755000175000017500000000000011316313131025326 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/ChannelGroup.java0000644000175000017500000001635311175574252030606 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.group; import java.net.SocketAddress; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ServerChannel; /** * A thread-safe {@link Set} that contains open {@link Channel}s and provides * various bulk operations on them. Using {@link ChannelGroup}, you can * categorize {@link Channel}s into a meaningful group (e.g. on a per-service * or per-state basis.) A closed {@link Channel} is automatically removed from * the collection, so that you don't need to worry about the life cycle of the * added {@link Channel}. A {@link Channel} can belong to more than one * {@link ChannelGroup}. * *

Broadcast a message to multiple {@link Channel}s

*

* If you need to broadcast a message to more than one {@link Channel}, you can * add the {@link Channel}s associated with the recipients and call {@link ChannelGroup#write(Object)}: *

 * ChannelGroup recipients = new DefaultChannelGroup();
 * recipients.add(channelA);
 * recipients.add(channelB);
 * ..
 * recipients.write(ChannelBuffers.copiedBuffer(
 *         "Service will shut down for maintenance in 5 minutes.", "UTF-8"));
 * 
* *

Simplify shutdown process with {@link ChannelGroup}

*

* If both {@link ServerChannel}s and non-{@link ServerChannel}s exist in the * same {@link ChannelGroup}, any requested I/O operations on the group are * performed for the {@link ServerChannel}s first and then for the others. *

* This rule is very useful when you shut down a server in one shot: * *

 * ChannelGroup allChannels = new DefaultChannelGroup();
 *
 * public static void main(String[] args) throws Exception {
 *     ServerBootstrap b = new ServerBootstrap(..);
 *     ...
 *
 *     // Start the server
 *     b.getPipeline().addLast("handler", new MyHandler());
 *     Channel serverChannel = b.bind(..);
 *     allChannels.add(serverChannel);
 *
 *     ... Wait until the shutdown signal reception ...
 *
 *     // Close the serverChannel and then all accepted connections.
 *     allChannels.close().awaitUninterruptibly();
 *     b.releaseExternalResources();
 * }
 *
 * public class MyHandler extends SimpleChannelUpstreamHandler {
 *     public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) {
 *         // Add all open channels to the global group so that they are
 *         // closed on shutdown.
 *         allChannels.add(e.getChannel());
 *     }
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1261 $, $Date: 2009-04-28 05:38:02 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark * @apiviz.has org.jboss.netty.channel.group.ChannelGroupFuture oneway - - returns */ public interface ChannelGroup extends Set, Comparable { /** * Returns the name of this group. A group name is purely for helping * you to distinguish one group from others. */ String getName(); /** * Returns the {@link Channel} whose ID matches the specified integer. * * @return the matching {@link Channel} if found. {@code null} otherwise. */ Channel find(Integer id); /** * Calls {@link Channel#setInterestOps(int)} for all {@link Channel}s in * this group with the specified {@code interestOps}. Please note that * this operation is asynchronous as {@link Channel#setInterestOps(int)} is. * * @return the {@link ChannelGroupFuture} instance that notifies when * the operation is done for all channels */ ChannelGroupFuture setInterestOps(int interestOps); /** * Calls {@link Channel#setReadable(boolean)} for all {@link Channel}s in * this group with the specified boolean flag. Please note that this * operation is asynchronous as {@link Channel#setReadable(boolean)} is. * * @return the {@link ChannelGroupFuture} instance that notifies when * the operation is done for all channels */ ChannelGroupFuture setReadable(boolean readable); /** * Writes the specified {@code message} to all {@link Channel}s in this * group. If the specified {@code message} is an instance of * {@link ChannelBuffer}, it is automatically * {@linkplain ChannelBuffer#duplicate() duplicated} to avoid a race * condition. Please note that this operation is asynchronous as * {@link Channel#write(Object)} is. * * @return the {@link ChannelGroupFuture} instance that notifies when * the operation is done for all channels */ ChannelGroupFuture write(Object message); /** * Writes the specified {@code message} with the specified * {@code remoteAddress} to all {@link Channel}s in this group. If the * specified {@code message} is an instance of {@link ChannelBuffer}, it is * automatically {@linkplain ChannelBuffer#duplicate() duplicated} to avoid * a race condition. Please note that this operation is asynchronous as * {@link Channel#write(Object, SocketAddress)} is. * * @return the {@link ChannelGroupFuture} instance that notifies when * the operation is done for all channels */ ChannelGroupFuture write(Object message, SocketAddress remoteAddress); /** * Disconnects all {@link Channel}s in this group from their remote peers. * * @return the {@link ChannelGroupFuture} instance that notifies when * the operation is done for all channels */ ChannelGroupFuture disconnect(); /** * Unbinds all {@link Channel}s in this group from their local address. * * @return the {@link ChannelGroupFuture} instance that notifies when * the operation is done for all channels */ ChannelGroupFuture unbind(); /** * Closes all {@link Channel}s in this group. If the {@link Channel} is * connected to a remote peer or bound to a local address, it is * automatically disconnected and unbound. * * @return the {@link ChannelGroupFuture} instance that notifies when * the operation is done for all channels */ ChannelGroupFuture close(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/ChannelGroupFuture.java0000644000175000017500000002431511175603073031770 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.group; import java.util.Iterator; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.execution.ExecutionHandler; /** * The result of an asynchronous {@link ChannelGroup} operation. * {@link ChannelGroupFuture} is composed of {@link ChannelFuture}s which * represent the outcome of the individual I/O operations that affect the * {@link Channel}s in the {@link ChannelGroup}. * *

* All I/O operations in {@link ChannelGroup} are asynchronous. It means any * I/O calls will return immediately with no guarantee that the requested I/O * operations have been completed at the end of the call. Instead, you will be * returned with a {@link ChannelGroupFuture} instance which tells you when the * requested I/O operations have succeeded, failed, or cancelled. *

* Various methods are provided to let you check if the I/O operations has been * completed, wait for the completion, and retrieve the result of the I/O * operation. It also allows you to add more than one * {@link ChannelGroupFutureListener} so you can get notified when the I/O * operation have been completed. * *

Prefer {@link #addListener(ChannelGroupFutureListener)} to {@link #await()}

* * It is recommended to prefer {@link #addListener(ChannelGroupFutureListener)} to * {@link #await()} wherever possible to get notified when I/O operations are * done and to do any follow-up tasks. *

* {@link #addListener(ChannelGroupFutureListener)} is non-blocking. It simply * adds the specified {@link ChannelGroupFutureListener} to the * {@link ChannelGroupFuture}, and I/O thread will notify the listeners when * the I/O operations associated with the future is done. * {@link ChannelGroupFutureListener} yields the best performance and resource * utilization because it does not block at all, but it could be tricky to * implement a sequential logic if you are not used to event-driven programming. *

* By contrast, {@link #await()} is a blocking operation. Once called, the * caller thread blocks until all I/O operations are done. It is easier to * implement a sequential logic with {@link #await()}, but the caller thread * blocks unnecessarily until all I/O operations are done and there's relatively * expensive cost of inter-thread notification. Moreover, there's a chance of * dead lock in a particular circumstance, which is described below. * *

Do not call {@link #await()} inside {@link ChannelHandler}

*

* The event handler methods in {@link ChannelHandler} is often called by * an I/O thread unless an {@link ExecutionHandler} is in the * {@link ChannelPipeline}. If {@link #await()} is called by an event handler * method, which is called by the I/O thread, the I/O operation it is waiting * for might never be complete because {@link #await()} can block the I/O * operation it is waiting for, which is a dead lock. *

 * // BAD - NEVER DO THIS
 * public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     if (e.getMessage() instanceof ShutdownMessage) {
 *         ChannelGroup allChannels = MyServer.getAllChannels();
 *         ChannelGroupFuture future = allChannels.close();
 *         future.awaitUninterruptibly();
 *         // Perform post-shutdown operation
 *         // ...
 *     }
 * }
 *
 * // GOOD
 * public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     if (e.getMessage() instanceof ShutdownMessage) {
 *         ChannelGroup allChannels = MyServer.getAllChannels();
 *         ChannelGroupFuture future = allChannels.close();
 *         future.addListener(new ChannelGroupFutureListener() {
 *             public void operationComplete(ChannelGroupFuture future) {
 *                 // Perform post-closure operation
 *                 // ...
 *             }
 *         });
 *     }
 * }
 * 
*

* In spite of the disadvantages mentioned above, there are certainly the cases * where it is more convenient to call {@link #await()}. In such a case, please * make sure you do not call {@link #await()} in an I/O thread. Otherwise, * {@link IllegalStateException} will be raised to prevent a dead lock. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1262 $, $Date: 2009-04-28 06:35:55 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.owns org.jboss.netty.channel.group.ChannelGroupFutureListener - - notifies */ public interface ChannelGroupFuture extends Iterable{ /** * Returns the {@link ChannelGroup} which is associated with this future. */ ChannelGroup getGroup(); /** * Returns the {@link ChannelFuture} of the individual I/O operation which * is associated with the {@link Channel} whose ID matches the specified * integer. * * @return the matching {@link ChannelFuture} if found. * {@code null} otherwise. */ ChannelFuture find(Integer channelId); /** * Returns the {@link ChannelFuture} of the individual I/O operation which * is associated with the specified {@link Channel}. * * @return the matching {@link ChannelFuture} if found. * {@code null} otherwise. */ ChannelFuture find(Channel channel); /** * Returns {@code true} if and only if this future is * complete, regardless of whether the operation was successful, failed, * or canceled. */ boolean isDone(); /** * Returns {@code true} if and only if all I/O operations associated with * this future were successful without any failure. */ boolean isCompleteSuccess(); /** * Returns {@code true} if and only if the I/O operations associated with * this future were partially successful with some failure. */ boolean isPartialSuccess(); /** * Returns {@code true} if and only if all I/O operations associated with * this future have failed without any success. */ boolean isCompleteFailure(); /** * Returns {@code true} if and only if the I/O operations associated with * this future have failed partially with some success. */ boolean isPartialFailure(); /** * Adds the specified listener to this future. The * specified listener is notified when this future is * {@linkplain #isDone() done}. If this future is already * completed, the specified listener is notified immediately. */ void addListener(ChannelGroupFutureListener listener); /** * Removes the specified listener from this future. * The specified listener is no longer notified when this * future is {@linkplain #isDone() done}. If this * future is already completed, this method has no effect * and returns silently. */ void removeListener(ChannelGroupFutureListener listener); /** * Waits for this future to be completed. * * @throws InterruptedException * if the current thread was interrupted */ ChannelGroupFuture await() throws InterruptedException; /** * Waits for this future to be completed without * interruption. This method catches an {@link InterruptedException} and * discards it silently. */ ChannelGroupFuture awaitUninterruptibly(); /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeout, TimeUnit unit) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit. * * @return {@code true} if and only if the future was completed within * the specified time limit * * @throws InterruptedException * if the current thread was interrupted */ boolean await(long timeoutMillis) throws InterruptedException; /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeout, TimeUnit unit); /** * Waits for this future to be completed within the * specified time limit without interruption. This method catches an * {@link InterruptedException} and discards it silently. * * @return {@code true} if and only if the future was completed within * the specified time limit */ boolean awaitUninterruptibly(long timeoutMillis); /** * Returns the {@link Iterator} that enumerates all {@link ChannelFuture}s * which are associated with this future. Please note that the returned * {@link Iterator} is is unmodifiable, which means a {@link ChannelFuture} * cannot be removed from this future. */ Iterator iterator(); } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/DefaultChannelGroupFuture.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/DefaultChannelGroupFuture.j0000644000175000017500000002535711174012523032605 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.group; import static java.util.concurrent.TimeUnit.*; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.IoWorkerRunnable; /** * The default {@link ChannelGroupFuture} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1241 $, $Date: 2009-04-23 00:14:27 -0700 (Thu, 23 Apr 2009) $ */ public class DefaultChannelGroupFuture implements ChannelGroupFuture { private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelGroupFuture.class); private final ChannelGroup group; final Map futures; private volatile ChannelGroupFutureListener firstListener; private volatile List otherListeners; private boolean done; int successCount; int failureCount; private int waiters; private final ChannelFutureListener childListener = new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { boolean success = future.isSuccess(); boolean callSetDone = false; synchronized (DefaultChannelGroupFuture.this) { if (success) { successCount ++; } else { failureCount ++; } callSetDone = successCount + failureCount == futures.size(); assert successCount + failureCount <= futures.size(); } if (callSetDone) { setDone(); } } }; /** * Creates a new instance. */ public DefaultChannelGroupFuture(ChannelGroup group, Collection futures) { if (group == null) { throw new NullPointerException("group"); } if (futures == null) { throw new NullPointerException("futures"); } this.group = group; Map futureMap = new HashMap(); for (ChannelFuture f: futures) { futureMap.put(f.getChannel().getId(), f); } this.futures = Collections.unmodifiableMap(futureMap); for (ChannelFuture f: this.futures.values()) { f.addListener(childListener); } // Done on arrival? if (this.futures.isEmpty()) { setDone(); } } DefaultChannelGroupFuture(ChannelGroup group, Map futures) { this.group = group; this.futures = Collections.unmodifiableMap(futures); for (ChannelFuture f: this.futures.values()) { f.addListener(childListener); } // Done on arrival? if (this.futures.isEmpty()) { setDone(); } } public ChannelGroup getGroup() { return group; } public ChannelFuture find(Integer channelId) { return futures.get(channelId); } public ChannelFuture find(Channel channel) { return futures.get(channel.getId()); } public Iterator iterator() { return futures.values().iterator(); } public synchronized boolean isDone() { return done; } public synchronized boolean isCompleteSuccess() { return successCount == futures.size(); } public synchronized boolean isPartialSuccess() { return !futures.isEmpty() && successCount != 0; } public synchronized boolean isPartialFailure() { return !futures.isEmpty() && failureCount != 0; } public synchronized boolean isCompleteFailure() { return failureCount == futures.size(); } public void addListener(ChannelGroupFutureListener listener) { if (listener == null) { throw new NullPointerException("listener"); } boolean notifyNow = false; synchronized (this) { if (done) { notifyNow = true; } else { if (firstListener == null) { firstListener = listener; } else { if (otherListeners == null) { otherListeners = new ArrayList(1); } otherListeners.add(listener); } } } if (notifyNow) { notifyListener(listener); } } public void removeListener(ChannelGroupFutureListener listener) { if (listener == null) { throw new NullPointerException("listener"); } synchronized (this) { if (!done) { if (listener == firstListener) { if (otherListeners != null && !otherListeners.isEmpty()) { firstListener = otherListeners.remove(0); } else { firstListener = null; } } else if (otherListeners != null) { otherListeners.remove(listener); } } } } public ChannelGroupFuture await() throws InterruptedException { synchronized (this) { while (!done) { checkDeadLock(); waiters++; try { this.wait(); } finally { waiters--; } } } return this; } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return await0(unit.toNanos(timeout), true); } public boolean await(long timeoutMillis) throws InterruptedException { return await0(MILLISECONDS.toNanos(timeoutMillis), true); } public ChannelGroupFuture awaitUninterruptibly() { synchronized (this) { while (!done) { checkDeadLock(); waiters++; try { this.wait(); } catch (InterruptedException e) { // Ignore. } finally { waiters--; } } } return this; } public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { try { return await0(unit.toNanos(timeout), false); } catch (InterruptedException e) { throw new InternalError(); } } public boolean awaitUninterruptibly(long timeoutMillis) { try { return await0(MILLISECONDS.toNanos(timeoutMillis), false); } catch (InterruptedException e) { throw new InternalError(); } } private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException { long startTime = timeoutNanos <= 0 ? 0 : System.nanoTime(); long waitTime = timeoutNanos; synchronized (this) { if (done) { return done; } else if (waitTime <= 0) { return done; } checkDeadLock(); waiters++; try { for (;;) { try { this.wait(waitTime / 1000000, (int) (waitTime % 1000000)); } catch (InterruptedException e) { if (interruptable) { throw e; } } if (done) { return true; } else { waitTime = timeoutNanos - (System.nanoTime() - startTime); if (waitTime <= 0) { return done; } } } } finally { waiters--; } } } private void checkDeadLock() { if (IoWorkerRunnable.IN_IO_THREAD.get()) { throw new IllegalStateException( "await*() in I/O thread causes a dead lock or " + "sudden performance drop. Use addListener() instead or " + "call await*() from a different thread."); } } boolean setDone() { synchronized (this) { // Allow only once. if (done) { return false; } done = true; if (waiters > 0) { notifyAll(); } } notifyListeners(); return true; } private void notifyListeners() { // There won't be any visibility problem or concurrent modification // because 'ready' flag will be checked against both addListener and // removeListener calls. if (firstListener != null) { notifyListener(firstListener); firstListener = null; if (otherListeners != null) { for (ChannelGroupFutureListener l: otherListeners) { notifyListener(l); } otherListeners = null; } } } private void notifyListener(ChannelGroupFutureListener l) { try { l.operationComplete(this); } catch (Throwable t) { logger.warn( "An exception was thrown by " + ChannelFutureListener.class.getSimpleName() + ".", t); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/package-info.java0000644000175000017500000000241011174033231030514 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * A channel registry which helps a user maintain the list of open * {@link org.jboss.netty.channel.Channel}s and perform bulk operations on them. * * @apiviz.exclude ^java * @apiviz.exclude \.DefaultChannelGroupFuture$ */ package org.jboss.netty.channel.group; ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/ChannelGroupFutureListener.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/ChannelGroupFutureListener.0000644000175000017500000000365111174031563032632 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.group; import java.util.EventListener; /** * Listens to the result of a {@link ChannelGroupFuture}. The result of the * asynchronous {@link ChannelGroup} I/O operations is notified once this * listener is added by calling {@link ChannelGroupFuture#addListener(ChannelGroupFutureListener)} * and all I/O operations are complete. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1242 $, $Date: 2009-04-23 02:22:59 -0700 (Thu, 23 Apr 2009) $ */ public interface ChannelGroupFutureListener extends EventListener { /** * Invoked when all I/O operations associated with the * {@link ChannelGroupFuture} have been completed. * * @param future The source {@link ChannelGroupFuture} which called this * callback. */ void operationComplete(ChannelGroupFuture future) throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/group/DefaultChannelGroup.java0000644000175000017500000002403711174033231032073 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.group; import java.net.SocketAddress; import java.util.AbstractSet; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; import java.util.Iterator; import java.util.Map; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ServerChannel; import org.jboss.netty.util.internal.CombinedIterator; import org.jboss.netty.util.internal.ConcurrentHashMap; /** * The default {@link ChannelGroup} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1243 $, $Date: 2009-04-23 02:36:25 -0700 (Thu, 23 Apr 2009) $ * * @apiviz.landmark */ public class DefaultChannelGroup extends AbstractSet implements ChannelGroup { private static final AtomicInteger nextId = new AtomicInteger(); private final String name; private final ConcurrentMap serverChannels = new ConcurrentHashMap(); private final ConcurrentMap nonServerChannels = new ConcurrentHashMap(); private final ChannelFutureListener remover = new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { remove(future.getChannel()); } }; /** * Creates a new group with a generated name. */ public DefaultChannelGroup() { this("group-0x" + Integer.toHexString(nextId.incrementAndGet())); } /** * Creates a new group with the specified {@code name}. Please note that * different groups can have the same name, which means no duplicate check * is done against group names. */ public DefaultChannelGroup(String name) { if (name == null) { throw new NullPointerException("name"); } this.name = name; } public String getName() { return name; } @Override public boolean isEmpty() { return nonServerChannels.isEmpty() && serverChannels.isEmpty(); } @Override public int size() { return nonServerChannels.size() + serverChannels.size(); } public Channel find(Integer id) { Channel c = nonServerChannels.get(id); if (c != null) { return c; } else { return serverChannels.get(id); } } @Override public boolean contains(Object o) { if (o instanceof Integer) { return nonServerChannels.containsKey(o) || serverChannels.containsKey(o); } else if (o instanceof Channel) { Channel c = (Channel) o; if (o instanceof ServerChannel) { return serverChannels.containsKey(c.getId()); } else { return nonServerChannels.containsKey(c.getId()); } } else { return false; } } @Override public boolean add(Channel channel) { ConcurrentMap map = channel instanceof ServerChannel? serverChannels : nonServerChannels; boolean added = map.putIfAbsent(channel.getId(), channel) == null; if (added) { channel.getCloseFuture().addListener(remover); } return added; } @Override public boolean remove(Object o) { Channel c = null; if (o instanceof Integer) { c = nonServerChannels.remove(o); if (c == null) { c = serverChannels.remove(o); } } else if (o instanceof Channel) { c = (Channel) o; if (c instanceof ServerChannel) { c = serverChannels.remove(c.getId()); } else { c = nonServerChannels.remove(c.getId()); } } if (c == null) { return false; } c.getCloseFuture().removeListener(remover); return true; } @Override public void clear() { nonServerChannels.clear(); serverChannels.clear(); } @Override public Iterator iterator() { return new CombinedIterator( serverChannels.values().iterator(), nonServerChannels.values().iterator()); } @Override public Object[] toArray() { Collection channels = new ArrayList(size()); channels.addAll(serverChannels.values()); channels.addAll(nonServerChannels.values()); return channels.toArray(); } @Override public T[] toArray(T[] a) { Collection channels = new ArrayList(size()); channels.addAll(serverChannels.values()); channels.addAll(nonServerChannels.values()); return channels.toArray(a); } public ChannelGroupFuture close() { Map futures = new HashMap(size()); for (Channel c: serverChannels.values()) { futures.put(c.getId(), c.close().awaitUninterruptibly()); } for (Channel c: nonServerChannels.values()) { futures.put(c.getId(), c.close()); } return new DefaultChannelGroupFuture(this, futures); } public ChannelGroupFuture disconnect() { Map futures = new HashMap(size()); for (Channel c: serverChannels.values()) { futures.put(c.getId(), c.disconnect().awaitUninterruptibly()); } for (Channel c: nonServerChannels.values()) { futures.put(c.getId(), c.disconnect()); } return new DefaultChannelGroupFuture(this, futures); } public ChannelGroupFuture setInterestOps(int interestOps) { Map futures = new HashMap(size()); for (Channel c: serverChannels.values()) { futures.put(c.getId(), c.setInterestOps(interestOps).awaitUninterruptibly()); } for (Channel c: nonServerChannels.values()) { futures.put(c.getId(), c.setInterestOps(interestOps)); } return new DefaultChannelGroupFuture(this, futures); } public ChannelGroupFuture setReadable(boolean readable) { Map futures = new HashMap(size()); for (Channel c: serverChannels.values()) { futures.put(c.getId(), c.setReadable(readable).awaitUninterruptibly()); } for (Channel c: nonServerChannels.values()) { futures.put(c.getId(), c.setReadable(readable)); } return new DefaultChannelGroupFuture(this, futures); } public ChannelGroupFuture unbind() { Map futures = new HashMap(size()); for (Channel c: serverChannels.values()) { futures.put(c.getId(), c.unbind().awaitUninterruptibly()); } for (Channel c: nonServerChannels.values()) { futures.put(c.getId(), c.unbind()); } return new DefaultChannelGroupFuture(this, futures); } public ChannelGroupFuture write(Object message) { Map futures = new HashMap(size()); if (message instanceof ChannelBuffer) { ChannelBuffer buf = (ChannelBuffer) message; for (Channel c: this) { futures.put(c.getId(), c.write(buf.duplicate())); } } else { for (Channel c: this) { futures.put(c.getId(), c.write(message)); } } return new DefaultChannelGroupFuture(this, futures); } public ChannelGroupFuture write(Object message, SocketAddress remoteAddress) { Map futures = new HashMap(size()); if (message instanceof ChannelBuffer) { ChannelBuffer buf = (ChannelBuffer) message; for (Channel c: this) { futures.put(c.getId(), c.write(buf.duplicate(), remoteAddress)); } } else { for (Channel c: this) { futures.put(c.getId(), c.write(message, remoteAddress)); } } return new DefaultChannelGroupFuture(this, futures); } @Override public int hashCode() { return System.identityHashCode(this); } @Override public boolean equals(Object o) { return this == o; } public int compareTo(ChannelGroup o) { int v = getName().compareTo(o.getName()); if (v != 0) { return v; } return System.identityHashCode(this) - System.identityHashCode(o); } @Override public String toString() { return getClass().getSimpleName() + "(name: " + getName() + ", size: " + size() + ')'; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelSink.java0000644000175000017500000000412111057236603027242 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * Receives and processes the terminal downstream {@link ChannelEvent}s. *

* A {@link ChannelSink} is an internal component which is supposed to be * implemented by a transport provider. Most users will not see this type * in their code. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 186 $, $Date: 2008-09-02 06:20:03 -0700 (Tue, 02 Sep 2008) $ * * @apiviz.uses org.jboss.netty.channel.ChannelPipeline - - sends events upstream */ public interface ChannelSink { /** * Invoked by {@link ChannelPipeline} when a downstream {@link ChannelEvent} * has reached its terminal (the head of the pipeline). */ void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception; /** * Invoked by {@link ChannelPipeline} when an exception was raised while * one of its {@link ChannelHandler}s process a {@link ChannelEvent}. */ void exceptionCaught(ChannelPipeline pipeline, ChannelEvent e, ChannelPipelineException cause) throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/AbstractServerChannel.java0000644000175000017500000000632411150044463031272 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; /** * A skeletal server-side {@link Channel} implementation. A server-side * {@link Channel} does not allow the following operations: *

    *
  • {@link #connect(SocketAddress)}
  • *
  • {@link #disconnect()}
  • *
  • {@link #getInterestOps()}
  • *
  • {@link #setInterestOps(int)}
  • *
  • {@link #write(Object)}
  • *
  • {@link #write(Object, SocketAddress)}
  • *
  • and the shortcut methods which calls the methods mentioned above *
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 922 $, $Date: 2009-02-21 10:34:27 -0800 (Sat, 21 Feb 2009) $ * */ public abstract class AbstractServerChannel extends AbstractChannel implements ServerChannel { /** * Creates a new instance. * * @param factory * the factory which created this channel * @param pipeline * the pipeline which is going to be attached to this channel * @param sink * the sink which will receive downstream events from the pipeline * and send upstream events to the pipeline */ protected AbstractServerChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { super(null, factory, pipeline, sink); } @Override public ChannelFuture connect(SocketAddress remoteAddress) { return getUnsupportedOperationFuture(); } @Override public ChannelFuture disconnect() { return getUnsupportedOperationFuture(); } @Override public int getInterestOps() { return OP_NONE; } @Override public ChannelFuture setInterestOps(int interestOps) { return getUnsupportedOperationFuture(); } @Override protected void setInterestOpsNow(int interestOps) { // Ignore. } @Override public ChannelFuture write(Object message) { return getUnsupportedOperationFuture(); } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { return getUnsupportedOperationFuture(); } public boolean isConnected() { return false; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/0000755000175000017500000000000011316313137025470 5ustar deckerdecker././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DefaultDatagramChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DefaultDatagramChannelConf0000644000175000017500000002056111216366721032551 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.io.IOException; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketException; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.DefaultChannelConfig; import org.jboss.netty.channel.FixedReceiveBufferSizePredictor; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.util.internal.ConversionUtil; /** * The default {@link DatagramChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1411 $, $Date: 2009-06-18 00:33:37 -0700 (Thu, 18 Jun 2009) $ * */ public class DefaultDatagramChannelConfig extends DefaultChannelConfig implements DatagramChannelConfig { private final DatagramSocket socket; private volatile ReceiveBufferSizePredictor predictor = new FixedReceiveBufferSizePredictor(768); /** * Creates a new instance. */ public DefaultDatagramChannelConfig(DatagramSocket socket) { if (socket == null) { throw new NullPointerException("socket"); } this.socket = socket; } @Override public boolean setOption(String key, Object value) { if (super.setOption(key, value)) { return true; } if (key.equals("broadcast")) { setBroadcast(ConversionUtil.toBoolean(value)); } else if (key.equals("receiveBufferSize")) { setReceiveBufferSize(ConversionUtil.toInt(value)); } else if (key.equals("sendBufferSize")) { setSendBufferSize(ConversionUtil.toInt(value)); } else if (key.equals("reuseAddress")) { setReuseAddress(ConversionUtil.toBoolean(value)); } else if (key.equals("trafficClass")) { setTrafficClass(ConversionUtil.toInt(value)); } else { return false; } return true; } public boolean isBroadcast() { try { return socket.getBroadcast(); } catch (SocketException e) { throw new ChannelException(e); } } public void setBroadcast(boolean broadcast) { try { socket.setBroadcast(broadcast); } catch (SocketException e) { throw new ChannelException(e); } } public InetAddress getInterface() { if (socket instanceof MulticastSocket) { try { return ((MulticastSocket) socket).getInterface(); } catch (SocketException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public void setInterface(InetAddress interfaceAddress) { if (socket instanceof MulticastSocket) { try { ((MulticastSocket) socket).setInterface(interfaceAddress); } catch (SocketException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public boolean isLoopbackModeDisabled() { if (socket instanceof MulticastSocket) { try { return ((MulticastSocket) socket).getLoopbackMode(); } catch (SocketException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public void setLoopbackModeDisabled(boolean loopbackModeDisabled) { if (socket instanceof MulticastSocket) { try { ((MulticastSocket) socket).setLoopbackMode(loopbackModeDisabled); } catch (SocketException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public NetworkInterface getNetworkInterface() { if (socket instanceof MulticastSocket) { try { return ((MulticastSocket) socket).getNetworkInterface(); } catch (SocketException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public void setNetworkInterface(NetworkInterface networkInterface) { if (socket instanceof MulticastSocket) { try { ((MulticastSocket) socket).setNetworkInterface(networkInterface); } catch (SocketException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public boolean isReuseAddress() { try { return socket.getReuseAddress(); } catch (SocketException e) { throw new ChannelException(e); } } public void setReuseAddress(boolean reuseAddress) { try { socket.setReuseAddress(reuseAddress); } catch (SocketException e) { throw new ChannelException(e); } } public int getReceiveBufferSize() { try { return socket.getReceiveBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } } public void setReceiveBufferSize(int receiveBufferSize) { try { socket.setReceiveBufferSize(receiveBufferSize); } catch (SocketException e) { throw new ChannelException(e); } } public int getSendBufferSize() { try { return socket.getSendBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } } public void setSendBufferSize(int sendBufferSize) { try { socket.setSendBufferSize(sendBufferSize); } catch (SocketException e) { throw new ChannelException(e); } } public int getTimeToLive() { if (socket instanceof MulticastSocket) { try { return ((MulticastSocket) socket).getTimeToLive(); } catch (IOException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public void setTimeToLive(int ttl) { if (socket instanceof MulticastSocket) { try { ((MulticastSocket) socket).setTimeToLive(ttl); } catch (IOException e) { throw new ChannelException(e); } } else { throw new UnsupportedOperationException(); } } public int getTrafficClass() { try { return socket.getTrafficClass(); } catch (SocketException e) { throw new ChannelException(e); } } public void setTrafficClass(int trafficClass) { try { socket.setTrafficClass(trafficClass); } catch (SocketException e) { throw new ChannelException(e); } } public ReceiveBufferSizePredictor getReceiveBufferSizePredictor() { return predictor; } public void setReceiveBufferSizePredictor(ReceiveBufferSizePredictor predictor) { if (predictor == null) { throw new NullPointerException("predictor"); } this.predictor = predictor; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DatagramChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DatagramChannelFactory.jav0000644000175000017500000000312711156177151032544 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; /** * A {@link ChannelFactory} which creates a {@link DatagramChannel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1025 $, $Date: 2009-03-12 05:22:01 -0700 (Thu, 12 Mar 2009) $ * * @apiviz.has org.jboss.netty.channel.socket.DatagramChannel oneway - - creates */ public interface DatagramChannelFactory extends ChannelFactory { DatagramChannel newChannel(ChannelPipeline pipeline); } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannelConfig.0000644000175000017500000000635411066426056032546 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.ServerSocket; import org.jboss.netty.channel.ChannelConfig; /** * A {@link ChannelConfig} for a {@link ServerSocketChannel}. * *

Available options

* * In addition to the options provided by {@link ChannelConfig}, * {@link ServerSocketChannelConfig} allows the following options in the * option map: * * * * * * * * * * * *
NameAssociated setter method
{@code "backlog"}{@link #setBacklog(int)}
{@code "reuseAddress"}{@link #setReuseAddress(boolean)}
{@code "receiveBufferSize"}{@link #setReceiveBufferSize(int)}
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 313 $, $Date: 2008-09-24 05:01:50 -0700 (Wed, 24 Sep 2008) $ * * @apiviz.landmark */ public interface ServerSocketChannelConfig extends ChannelConfig { /** * Gets the backlog value to specify when the channel binds to a local * address. */ int getBacklog(); /** * Sets the backlog value to specify when the channel binds to a local * address. */ void setBacklog(int backlog); /** * Gets the {@code SO_REUSEADDR} option. */ boolean isReuseAddress(); /** * Sets the {@code SO_REUSEADDR} option. */ void setReuseAddress(boolean reuseAddress); /** * Gets the {@code SO_RCVBUF} option. */ int getReceiveBufferSize(); /** * Sets the {@code SO_RCVBUF} option. */ void setReceiveBufferSize(int receiveBufferSize); /** * Sets the performance preferences as specified in * {@link ServerSocket#setPerformancePreferences(int, int, int)}. */ void setPerformancePreferences(int connectionTime, int latency, int bandwidth); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannel.java0000644000175000017500000000322011216366721032246 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.InetSocketAddress; import org.jboss.netty.channel.ServerChannel; /** * A TCP/IP {@link ServerChannel} which accepts incoming TCP/IP connections. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1411 $, $Date: 2009-06-18 00:33:37 -0700 (Thu, 18 Jun 2009) $ * * @apiviz.composedOf org.jboss.netty.channel.socket.ServerSocketChannelConfig */ public interface ServerSocketChannel extends ServerChannel { ServerSocketChannelConfig getConfig(); InetSocketAddress getLocalAddress(); InetSocketAddress getRemoteAddress(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/SocketChannel.java0000644000175000017500000000326511057416413031065 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.InetSocketAddress; import org.jboss.netty.channel.Channel; /** * A TCP/IP socket {@link Channel} which was either accepted by * {@link ServerSocketChannel} or created by {@link ClientSocketChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 212 $, $Date: 2008-09-02 22:13:47 -0700 (Tue, 02 Sep 2008) $ * * @apiviz.composedOf org.jboss.netty.channel.socket.SocketChannelConfig */ public interface SocketChannel extends Channel { SocketChannelConfig getConfig(); InetSocketAddress getLocalAddress(); InetSocketAddress getRemoteAddress(); } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DefaultServerSocketChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DefaultServerSocketChannel0000644000175000017500000000741411165336702032643 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.ServerSocket; import java.net.SocketException; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.DefaultServerChannelConfig; import org.jboss.netty.util.internal.ConversionUtil; /** * The default {@link ServerSocketChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public class DefaultServerSocketChannelConfig extends DefaultServerChannelConfig implements ServerSocketChannelConfig { private final ServerSocket socket; private volatile int backlog; /** * Creates a new instance. */ public DefaultServerSocketChannelConfig(ServerSocket socket) { if (socket == null) { throw new NullPointerException("socket"); } this.socket = socket; } @Override public boolean setOption(String key, Object value) { if (super.setOption(key, value)) { return true; } if (key.equals("receiveBufferSize")) { setReceiveBufferSize(ConversionUtil.toInt(value)); } else if (key.equals("reuseAddress")) { setReuseAddress(ConversionUtil.toBoolean(value)); } else if (key.equals("backlog")) { setBacklog(ConversionUtil.toInt(value)); } else { return false; } return true; } public boolean isReuseAddress() { try { return socket.getReuseAddress(); } catch (SocketException e) { throw new ChannelException(e); } } public void setReuseAddress(boolean reuseAddress) { try { socket.setReuseAddress(reuseAddress); } catch (SocketException e) { throw new ChannelException(e); } } public int getReceiveBufferSize() { try { return socket.getReceiveBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } } public void setReceiveBufferSize(int receiveBufferSize) { try { socket.setReceiveBufferSize(receiveBufferSize); } catch (SocketException e) { throw new ChannelException(e); } } public void setPerformancePreferences(int connectionTime, int latency, int bandwidth) { socket.setPerformancePreferences(connectionTime, latency, bandwidth); } public int getBacklog() { return backlog; } public void setBacklog(int backlog) { if (backlog < 1) { throw new IllegalArgumentException("backlog: " + backlog); } this.backlog = backlog; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/ClientSocketChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/ClientSocketChannelFactory0000644000175000017500000000314011057416413032624 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; /** * A {@link ChannelFactory} which creates a client-side {@link SocketChannel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 212 $, $Date: 2008-09-02 22:13:47 -0700 (Tue, 02 Sep 2008) $ * * @apiviz.has org.jboss.netty.channel.socket.SocketChannel oneway - - creates */ public interface ClientSocketChannelFactory extends ChannelFactory { SocketChannel newChannel(ChannelPipeline pipeline); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/0000755000175000017500000000000011316313134026444 5ustar deckerdecker././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingContextListener.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingContextL0000644000175000017500000000621211216747541032670 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import javax.servlet.ServletContextEvent; import javax.servlet.ServletContextListener; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; import org.jboss.netty.channel.local.LocalClientChannelFactory; /** * A {@link ServletContextListener} that creates a {@link ClientBootstrap} * using a {@link LocalClientChannelFactory}. The factory should be registered * before this context is loaded. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpTunnelingContextListener implements ServletContextListener { private static final long DEFAULT_RECONNECT_TIMEOUT = 5000; private static final boolean DEFAULT_IS_STREAMING = true; static final String SERVER_CHANNEL_PROP = "serverChannelName"; static final String RECONNECT_PROP = "reconnectTimeout"; static final String STREAMING_PROP = "streaming"; static final String BOOTSTRAP_PROP = "bootstrap"; private final ChannelFactory factory = new DefaultLocalClientChannelFactory(); public void contextInitialized(ServletContextEvent context) { context.getServletContext().setAttribute(BOOTSTRAP_PROP, new ClientBootstrap(factory)); String timeoutParam = context.getServletContext().getInitParameter(RECONNECT_PROP); context.getServletContext().setAttribute(RECONNECT_PROP, timeoutParam == null?DEFAULT_RECONNECT_TIMEOUT:Long.decode(timeoutParam.trim())); String streaming = context.getServletContext().getInitParameter(STREAMING_PROP); context.getServletContext().setAttribute(STREAMING_PROP, streaming == null?DEFAULT_IS_STREAMING: Boolean.valueOf(streaming.trim())); String serverChannel = context.getServletContext().getInitParameter(SERVER_CHANNEL_PROP); context.getServletContext().setAttribute(SERVER_CHANNEL_PROP, serverChannel); } public void contextDestroyed(ServletContextEvent context) { // Unused } } ././@LongLink0000000000000000000000000000017400000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingClientSocketChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingClientSo0000644000175000017500000000670511216377544032661 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.util.internal.ExecutorUtil; /** * Creates a client-side {@link SocketChannel} which connects to an * {@link HttpTunnelingServlet} to communicate with the server application * behind the {@link HttpTunnelingServlet}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1415 $, $Date: 2009-06-18 01:48:36 -0700 (Thu, 18 Jun 2009) $ */ public class HttpTunnelingClientSocketChannelFactory implements ClientSocketChannelFactory { private final Executor workerExecutor; private final ChannelSink sink; ClientSocketChannelFactory clientSocketChannelFactory; /** * * @param workerExecutor */ public HttpTunnelingClientSocketChannelFactory(ClientSocketChannelFactory clientSocketChannelFactory, Executor workerExecutor) { this(workerExecutor, Runtime.getRuntime().availableProcessors()); this.clientSocketChannelFactory = clientSocketChannelFactory; } /** * Creates a new instance. * * the {@link java.util.concurrent.Executor} which will execute the boss thread * @param workerExecutor * the {@link java.util.concurrent.Executor} which will execute the I/O worker threads * @param workerCount */ public HttpTunnelingClientSocketChannelFactory(Executor workerExecutor, int workerCount) { if (workerExecutor == null) { throw new NullPointerException("workerExecutor"); } if (workerCount <= 0) { throw new IllegalArgumentException( "workerCount (" + workerCount + ") " + "must be a positive integer."); } this.workerExecutor = workerExecutor; sink = new HttpTunnelingClientSocketPipelineSink(workerExecutor); } public SocketChannel newChannel(ChannelPipeline pipeline) { return new HttpTunnelingClientSocketChannel(this, pipeline, sink, clientSocketChannelFactory); } public void releaseExternalResources() { clientSocketChannelFactory.releaseExternalResources(); ExecutorUtil.terminate(workerExecutor); } }././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingChannelHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingChannelH0000644000175000017500000001555011216747541032615 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import java.io.IOException; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpSession; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * A {@link ChannelHandler} that proxies received messages to the * {@link OutputStream} of the {@link HttpTunnelingServlet}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ @ChannelPipelineCoverage("one") class HttpTunnelingChannelHandler extends SimpleChannelUpstreamHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(HttpTunnelingChannelHandler.class); private final List awaitingEvents = new ArrayList(); private final Lock reconnectLock = new ReentrantLock(); private final Condition reconnectCondition = reconnectLock.newCondition(); private final long reconnectTimeoutMillis; private volatile boolean connected = false; private final AtomicBoolean invalidated = new AtomicBoolean(false); private volatile ServletOutputStream outputStream; private final boolean stream; private final HttpSession session; public HttpTunnelingChannelHandler( boolean stream, HttpSession session, long reconnectTimeoutMillis) { this.stream = stream; this.session = session; this.reconnectTimeoutMillis = reconnectTimeoutMillis; } @Override public synchronized void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer buffer = (ChannelBuffer) e.getMessage(); if (stream) { boolean success = false; Exception cause = null; byte[] b = null; reconnectLock.lock(); try { if (outputStream == null) { awaitingEvents.add(e); return; } b = new byte[buffer.readableBytes()]; buffer.readBytes(b); outputStream.write(b); outputStream.flush(); success = true; } catch (Exception ex) { success = false; cause = ex; if (awaitReconnect()) { try { outputStream.write(b); outputStream.flush(); success = true; } catch (Exception ex2) { success = false; cause = ex2; } } else { invalidateHttpSession(); e.getChannel().close(); } } finally { reconnectLock.unlock(); if (!success) { assert cause != null; throw cause; } } } else { awaitingEvents.add(e); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { logger.warn("Unexpected exception", e.getCause()); invalidateHttpSession(); e.getChannel().close(); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { invalidateHttpSession(); } private void invalidateHttpSession() { if (invalidated.compareAndSet(false, true)) { try { session.invalidate(); } catch (Exception e) { // Gulp - https://jira.jboss.org/jira/browse/JBWEB-139 logger.debug( "Unexpected exception raised by the Servlet container; " + "ignoring.", e); } } } synchronized List getAwaitingEvents() { List list = new ArrayList(); list.addAll(awaitingEvents); awaitingEvents.clear(); return list; } void setOutputStream(ServletOutputStream outputStream) throws IOException { reconnectLock.lock(); try { this.outputStream = outputStream; connected = true; for (MessageEvent awaitingEvent : awaitingEvents) { ChannelBuffer buffer = (ChannelBuffer) awaitingEvent.getMessage(); byte[] b = new byte[buffer.readableBytes()]; buffer.readBytes(b); outputStream.write(b); outputStream.flush(); } reconnectCondition.signalAll(); } finally { reconnectLock.unlock(); } } boolean isStreaming() { return stream; } boolean awaitReconnect() { reconnectLock.lock(); try { connected = false; reconnectCondition.await(reconnectTimeoutMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { // return with current state. } finally { reconnectLock.unlock(); } return connected; } } ././@LongLink0000000000000000000000000000017200000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingClientSocketPipelineSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingClientSo0000644000175000017500000001304311216374351032643 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import static org.jboss.netty.channel.Channels.*; import java.net.SocketAddress; import java.util.concurrent.Executor; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.IoWorkerRunnable; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1412 $, $Date: 2009-06-18 01:20:57 -0700 (Thu, 18 Jun 2009) $ */ final class HttpTunnelingClientSocketPipelineSink extends AbstractChannelSink { static final String LINE_TERMINATOR = "\r\n"; private final Executor workerExecutor; HttpTunnelingClientSocketPipelineSink(Executor workerExecutor) { this.workerExecutor = workerExecutor; } public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { HttpTunnelingClientSocketChannel channel = (HttpTunnelingClientSocketChannel) e.getChannel(); ChannelFuture future = e.getFuture(); if (e instanceof ChannelStateEvent) { ChannelStateEvent stateEvent = (ChannelStateEvent) e; ChannelState state = stateEvent.getState(); Object value = stateEvent.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { HttpTunnelWorker.close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (SocketAddress) value); } else { HttpTunnelWorker.close(channel, future); } break; case CONNECTED: if (value != null) { connect(channel, future, (HttpTunnelAddress) value); } else { HttpTunnelWorker.close(channel, future); } break; case INTEREST_OPS: HttpTunnelWorker.setInterestOps(channel, future, ((Integer) value).intValue()); break; } } else if (e instanceof MessageEvent) { HttpTunnelWorker.write( channel, future, ((MessageEvent) e).getMessage()); } } private void bind( HttpTunnelingClientSocketChannel channel, ChannelFuture future, SocketAddress localAddress) { try { channel.bindSocket(localAddress); future.setSuccess(); fireChannelBound(channel, channel.getLocalAddress()); } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } private void connect( HttpTunnelingClientSocketChannel channel, ChannelFuture future, HttpTunnelAddress remoteAddress) { boolean bound = channel.isBound(); boolean connected = false; boolean workerStarted = false; future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); try { channel.connectAndSendHeaders(false, remoteAddress); // Fire events. future.setSuccess(); if (!bound) { fireChannelBound(channel, channel.getLocalAddress()); } fireChannelConnected(channel, channel.getRemoteAddress()); // Start the business. workerExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( new HttpTunnelWorker(channel), "HTTP Tunnel I/O client worker (channelId: " + channel.getId() + ", " + channel.getLocalAddress() + " => " + channel.getRemoteAddress() + ')'))); workerStarted = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (connected && !workerStarted) { HttpTunnelWorker.close(channel, future); } } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelWorker.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelWorker.java0000644000175000017500000001424511216374351032623 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1412 $, $Date: 2009-06-18 01:20:57 -0700 (Thu, 18 Jun 2009) $ */ final class HttpTunnelWorker implements Runnable { private final HttpTunnelingClientSocketChannel channel; HttpTunnelWorker(HttpTunnelingClientSocketChannel channel) { this.channel = channel; } public void run() { channel.workerThread = Thread.currentThread(); while (channel.isOpen()) { synchronized (channel.interestOpsLock) { while (!channel.isReadable()) { try { // notify() is not called at all. // close() and setInterestOps() calls Thread.interrupt() channel.interestOpsLock.wait(); } catch (InterruptedException e) { if (!channel.isOpen()) { break; } } } } byte[] buf; try { buf = channel.receiveChunk(); } catch (Throwable t) { if (!channel.isOpen()) { fireExceptionCaught(channel, t); } break; } if (buf != null) { fireMessageReceived( channel, ChannelBuffers.wrappedBuffer( channel.getConfig().getBufferFactory().getDefaultOrder(), buf)); } } // Setting the workerThread to null will prevent any channel // operations from interrupting this thread from now on. channel.workerThread = null; // Clean up. close(channel, succeededFuture(channel)); } static void write( HttpTunnelingClientSocketChannel channel, ChannelFuture future, Object message) { try { ChannelBuffer buf = (ChannelBuffer) message; int writtenBytes = channel.sendChunk(buf); future.setSuccess(); fireWriteComplete(channel, writtenBytes); } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } static void setInterestOps( HttpTunnelingClientSocketChannel channel, ChannelFuture future, int interestOps) { // Override OP_WRITE flag - a user cannot change this flag. interestOps &= ~Channel.OP_WRITE; interestOps |= channel.getInterestOps() & Channel.OP_WRITE; boolean changed = false; try { if (channel.getInterestOps() != interestOps) { if ((interestOps & Channel.OP_READ) != 0) { channel.setInterestOpsNow(Channel.OP_READ); } else { channel.setInterestOpsNow(Channel.OP_NONE); } changed = true; } future.setSuccess(); if (changed) { synchronized (channel.interestOpsLock) { channel.setInterestOpsNow(interestOps); // Notify the worker so it stops or continues reading. Thread currentThread = Thread.currentThread(); Thread workerThread = channel.workerThread; if (workerThread != null && currentThread != workerThread) { workerThread.interrupt(); } } fireChannelInterestChanged(channel); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } static void close(HttpTunnelingClientSocketChannel channel, ChannelFuture future) { boolean connected = channel.isConnected(); boolean bound = channel.isBound(); try { channel.closeSocket(); if (channel.setClosed()) { future.setSuccess(); if (connected) { // Notify the worker so it stops reading. Thread currentThread = Thread.currentThread(); Thread workerThread = channel.workerThread; if (workerThread != null && currentThread != workerThread) { workerThread.interrupt(); } fireChannelDisconnected(channel); } if (bound) { fireChannelUnbound(channel); } fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } }././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelAddress.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelAddress.jav0000644000175000017500000000472511216747541032605 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import java.net.SocketAddress; import java.net.URI; /** * The URI of {@link HttpTunnelingServlet} where * {@link HttpTunnelingClientSocketChannelFactory} connects to. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpTunnelAddress extends SocketAddress implements Comparable { private static final long serialVersionUID = -7933609652910855887L; private final URI uri; /** * Creates a new instance with the specified URI. */ public HttpTunnelAddress(URI uri) { if (uri == null) { throw new NullPointerException("uri"); } this.uri = uri; } /** * Returns the {@link URI} where {@link HttpTunnelingServlet} is bound. */ public URI getUri() { return uri; } @Override public int hashCode() { return uri.hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof HttpTunnelAddress)) { return false; } return getUri().equals(((HttpTunnelAddress) o).getUri()); } public int compareTo(HttpTunnelAddress o) { return getUri().compareTo(o.getUri()); } @Override public String toString() { return "htun:" + getUri(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/package-info.java0000644000175000017500000000264511216377544031660 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * An HTTP-based client-side {@link org.jboss.netty.channel.socket.SocketChannel} * and its corresponding server-side Servlet implementation that make your * existing server application work in a firewalled network. *

* Please refer to the example in the org.jboss.netty.example.http.tunnel * package to learn how to configure the HTTP tunneling transport. */ package org.jboss.netty.channel.socket.http; ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingServlet.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingServlet.0000644000175000017500000001611311216747541032633 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import java.io.IOException; import java.io.InputStream; import java.io.PushbackInputStream; import java.util.List; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import javax.servlet.http.HttpSession; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.MessageEvent; /** * An {@link HttpServlet} that proxies an incoming data to the actual server * and vice versa. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpTunnelingServlet extends HttpServlet { private static final long serialVersionUID = -872309493835745385L; final static String CHANNEL_PROP = "channel"; final static String HANDLER_PROP = "handler"; protected void doRequest( HttpServletRequest request, HttpServletResponse response) throws IOException { HttpSession session = request.getSession(); Channel channel = (Channel) session.getAttribute(CHANNEL_PROP); HttpTunnelingChannelHandler handler = (HttpTunnelingChannelHandler) session.getAttribute(HANDLER_PROP); if (handler.isStreaming()) { streamResponse(request, response, session, handler, channel); } else { pollResponse(channel, request, response, session, handler); } } private void streamResponse( final HttpServletRequest request, final HttpServletResponse response, HttpSession session, HttpTunnelingChannelHandler handler, Channel channel) throws IOException { try { response.setHeader("JSESSIONID", session.getId()); response.setHeader("Content-Type", "application/octet-stream"); response.setStatus(HttpServletResponse.SC_OK); // Initiate chunked encoding by flushing the headers. response.getOutputStream().flush(); handler.setOutputStream(response.getOutputStream()); PushbackInputStream in = new PushbackInputStream(request.getInputStream()); for (;;) { try { ChannelBuffer buffer = read(in); if (buffer == null) { break; } channel.write(buffer); } catch (IOException e) { // this is ok, the client can reconnect. break; } } } finally { // Mark the channel as closed if the client didn't reconnect in time. if (!handler.awaitReconnect()) { channel.close(); } } } private ChannelBuffer read(PushbackInputStream in) throws IOException { byte[] buf; int readBytes; for (;;) { int bytesToRead = in.available(); if (bytesToRead > 0) { buf = new byte[bytesToRead]; readBytes = in.read(buf); break; } else if (bytesToRead == 0) { int b = in.read(); if (b < 0 || in.available() < 0) { return null; } if (b == 13) { in.read(); } else { in.unread(b); } } else { return null; } } ChannelBuffer buffer; if (readBytes == buf.length) { buffer = ChannelBuffers.wrappedBuffer(buf); } else { // A rare case, but it sometimes happen. buffer = ChannelBuffers.wrappedBuffer(buf, 0, readBytes); } return buffer; } private void pollResponse( Channel channel, HttpServletRequest request, HttpServletResponse response, HttpSession session, HttpTunnelingChannelHandler handler) throws IOException { InputStream in = request.getInputStream(); if (in != null) { ChannelBuffer requestContent = ChannelBuffers.dynamicBuffer(); for (;;) { int writtenBytes = requestContent.writeBytes(in, 4096); if (writtenBytes < 0) { break; } } if (requestContent.readable()) { channel.write(requestContent); } } handler.setOutputStream(response.getOutputStream()); List buffers = handler.getAwaitingEvents(); int length = 0; if (buffers.size() > 0) { for (MessageEvent buffer: buffers) { length += ((ChannelBuffer) buffer.getMessage()).readableBytes(); } } response.setHeader("JSESSIONID", session.getId()); response.setContentLength(length); response.setStatus(HttpServletResponse.SC_OK); for (MessageEvent event: buffers) { ChannelBuffer buffer = (ChannelBuffer) event.getMessage(); byte[] b = new byte[buffer.readableBytes()]; buffer.readBytes(b); try { response.getOutputStream().write(b); event.getFuture().setSuccess(); } catch (IOException e) { event.getFuture().setFailure(e); } } } @Override protected void doGet( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { doRequest(httpServletRequest, httpServletResponse); } @Override protected void doPost( HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { doRequest(httpServletRequest, httpServletResponse); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingSessionListener.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingSessionL0000644000175000017500000000777011216747541032701 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import static org.jboss.netty.channel.Channels.*; import static org.jboss.netty.channel.socket.http.HttpTunnelingContextListener.*; import static org.jboss.netty.channel.socket.http.HttpTunnelingServlet.*; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpSession; import javax.servlet.http.HttpSessionEvent; import javax.servlet.http.HttpSessionListener; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.local.LocalAddress; /** * An {@link HttpSessionListener} that creates an outbound connection to the * actual server behind {@link HttpServlet}. The outbound connection is open * when a new session is created, and closed when the session is destroyed. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpTunnelingSessionListener implements HttpSessionListener, ChannelHandler { public void sessionCreated(HttpSessionEvent event) { HttpSession session = event.getSession(); ClientBootstrap bootstrap = (ClientBootstrap) session.getServletContext().getAttribute(BOOTSTRAP_PROP); Boolean streaming = (Boolean) session.getServletContext().getAttribute(STREAMING_PROP); if (streaming) { session.setMaxInactiveInterval(-1); } final HttpTunnelingChannelHandler handler = new HttpTunnelingChannelHandler(streaming, session, (Long) session.getServletContext().getAttribute(RECONNECT_PROP)); session.setAttribute(HANDLER_PROP, handler); bootstrap.setPipelineFactory(new HttpTunnelingChannelPipelineFactory(handler)); ChannelFuture future = bootstrap.connect(new LocalAddress((String) session.getServletContext().getAttribute(SERVER_CHANNEL_PROP))); future.awaitUninterruptibly(); final Channel ch = future.getChannel(); session.setAttribute(CHANNEL_PROP, ch); } public void sessionDestroyed(HttpSessionEvent event) { Channel channel = (Channel) event.getSession().getAttribute(CHANNEL_PROP); if (channel != null) { channel.close(); } } private static final class HttpTunnelingChannelPipelineFactory implements ChannelPipelineFactory { private final HttpTunnelingChannelHandler handler; HttpTunnelingChannelPipelineFactory(HttpTunnelingChannelHandler handler) { this.handler = handler; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); pipeline.addLast(HttpTunnelingSessionListener.class.getName(), handler); return pipeline; } } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingClientSocketChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingClientSo0000644000175000017500000002525011216374351032646 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import static org.jboss.netty.channel.Channels.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.net.URI; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.DefaultChannelPipeline; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.LinkedTransferQueue; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1412 $, $Date: 2009-06-18 01:20:57 -0700 (Thu, 18 Jun 2009) $ */ class HttpTunnelingClientSocketChannel extends AbstractChannel implements org.jboss.netty.channel.socket.SocketChannel { static final InternalLogger logger = InternalLoggerFactory.getInstance(HttpTunnelingClientSocketChannel.class); private final Lock reconnectLock = new ReentrantLock(); volatile boolean awaitingInitialResponse = true; private final Object writeLock = new Object(); final Object interestOpsLock = new Object(); volatile Thread workerThread; String sessionId; boolean closed = false; LinkedTransferQueue messages = new LinkedTransferQueue(); private final ClientSocketChannelFactory clientSocketChannelFactory; SocketChannel channel; private final DelimiterBasedFrameDecoder handler = new DelimiterBasedFrameDecoder(8092, ChannelBuffers.wrappedBuffer(new byte[] { '\r', '\n' })); private final HttpTunnelingClientSocketChannel.ServletChannelHandler servletHandler = new ServletChannelHandler(); private HttpTunnelAddress remoteAddress; HttpTunnelingClientSocketChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, ClientSocketChannelFactory clientSocketChannelFactory) { super(null, factory, pipeline, sink); this.clientSocketChannelFactory = clientSocketChannelFactory; DefaultChannelPipeline channelPipeline = new DefaultChannelPipeline(); channelPipeline.addLast("DelimiterBasedFrameDecoder", handler); channelPipeline.addLast("servletHandler", servletHandler); channel = clientSocketChannelFactory.newChannel(channelPipeline); fireChannelOpen(this); } public SocketChannelConfig getConfig() { return channel.getConfig(); } public InetSocketAddress getLocalAddress() { return channel.getLocalAddress(); } public InetSocketAddress getRemoteAddress() { return channel.getRemoteAddress(); } public boolean isBound() { return channel.isOpen(); } public boolean isConnected() { return channel.isConnected(); } @Override protected boolean setClosed() { return super.setClosed(); } @Override protected void setInterestOpsNow(int interestOps) { super.setInterestOpsNow(interestOps); } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) { return super.write(message, null); } else { return getUnsupportedOperationFuture(); } } void connectAndSendHeaders(boolean reconnect, HttpTunnelAddress remoteAddress) { this.remoteAddress = remoteAddress; URI url = remoteAddress.getUri(); if (reconnect) { closeSocket(); DefaultChannelPipeline channelPipeline = new DefaultChannelPipeline(); channelPipeline.addLast("DelimiterBasedFrameDecoder", handler); channelPipeline.addLast("servletHandler", servletHandler); channel = clientSocketChannelFactory.newChannel(channelPipeline); } SocketAddress connectAddress = new InetSocketAddress(url.getHost(), url.getPort()); channel.connect(connectAddress).awaitUninterruptibly(); StringBuilder builder = new StringBuilder(); builder.append("POST ").append(url.getRawPath()).append(" HTTP/1.1").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR). append("Host: ").append(url.getHost()).append(":").append(url.getPort()).append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR). append("Content-Type: application/octet-stream").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Transfer-Encoding: chunked"). append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Content-Transfer-Encoding: Binary").append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR).append("Connection: Keep-Alive"). append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR); if (reconnect) { builder.append("Cookie: JSESSIONID=").append(sessionId).append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR); } builder.append(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR); String msg = builder.toString(); channel.write(ChannelBuffers.copiedBuffer(msg, "ASCII")); } int sendChunk(ChannelBuffer a) { int size = a.readableBytes(); String hex = Integer.toHexString(size) + HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR; synchronized (writeLock) { ChannelFuture future = channel.write(ChannelBuffers.wrappedBuffer( ChannelBuffers.copiedBuffer(hex, "ASCII"), a, ChannelBuffers.copiedBuffer(HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR, "ASCII"))); future.awaitUninterruptibly(); } return size + hex.length() + HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR.length(); } byte[] receiveChunk() { byte[] buf = null; try { buf = messages.take(); } catch (InterruptedException e) { // Ignore } return buf; } void reconnect() throws Exception { if (closed) { throw new IllegalStateException("channel closed"); } if (reconnectLock.tryLock()) { try { awaitingInitialResponse = true; connectAndSendHeaders(true, remoteAddress); } finally { reconnectLock.unlock(); } } else { try { reconnectLock.lock(); } finally { reconnectLock.unlock(); } } } void closeSocket() { if (setClosed()) { // Send the end of chunk. synchronized (writeLock) { ChannelFuture future = channel.write(ChannelBuffers.copiedBuffer( "0" + HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR + HttpTunnelingClientSocketPipelineSink.LINE_TERMINATOR, "ASCII")); future.awaitUninterruptibly(); } closed = true; channel.close(); } } void bindSocket(SocketAddress localAddress) { channel.bind(localAddress); } @ChannelPipelineCoverage("one") class ServletChannelHandler extends SimpleChannelUpstreamHandler { int nextChunkSize = -1; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer buf = (ChannelBuffer) e.getMessage(); byte[] bytes = new byte[buf.readableBytes()]; buf.getBytes(0, bytes); if (awaitingInitialResponse) { String line = new String(bytes); if (line.contains("Set-Cookie")) { int start = line.indexOf("JSESSIONID=") + 11; int end = line.indexOf(";", start); sessionId = line.substring(start, end); } else if (line.equals("")) { awaitingInitialResponse = false; } } else { if(nextChunkSize == -1) { String hex = new String(bytes); nextChunkSize = Integer.parseInt(hex, 16); if(nextChunkSize == 0) { if(!closed) { nextChunkSize = -1; awaitingInitialResponse = true; reconnect(); } } } else { messages.put(bytes); nextChunkSize = -1; } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { logger.warn("Unexpected exception", e.getCause()); channel.close(); } } }././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingSocketChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/http/HttpTunnelingSocketCh0000644000175000017500000001731511165336702032635 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.http; import java.net.Socket; import java.net.SocketException; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.DefaultChannelConfig; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.util.internal.ConversionUtil; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ final class HttpTunnelingSocketChannelConfig extends DefaultChannelConfig implements SocketChannelConfig { final Socket socket; private Integer trafficClass; private Boolean tcpNoDelay; private Integer soLinger; private Integer sendBufferSize; private Boolean reuseAddress; private Integer receiveBufferSize; private Integer connectionTime; private Integer latency; private Integer bandwidth; private Boolean keepAlive; /** * Creates a new instance. */ HttpTunnelingSocketChannelConfig(Socket socket) { this.socket = socket; } @Override public boolean setOption(String key, Object value) { if (key.equals("receiveBufferSize")) { setReceiveBufferSize(ConversionUtil.toInt(value)); } else if (key.equals("sendBufferSize")) { setSendBufferSize(ConversionUtil.toInt(value)); } else if (key.equals("tcpNoDelay")) { setTcpNoDelay(ConversionUtil.toBoolean(value)); } else if (key.equals("keepAlive")) { setKeepAlive(ConversionUtil.toBoolean(value)); } else if (key.equals("reuseAddress")) { setReuseAddress(ConversionUtil.toBoolean(value)); } else if (key.equals("soLinger")) { setSoLinger(ConversionUtil.toInt(value)); } else if (key.equals("trafficClass")) { setTrafficClass(ConversionUtil.toInt(value)); } else { return false; } return true; } public int getReceiveBufferSize() { try { return socket.getReceiveBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } } public int getSendBufferSize() { try { return socket.getSendBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } } public int getSoLinger() { try { return socket.getSoLinger(); } catch (SocketException e) { throw new ChannelException(e); } } public int getTrafficClass() { try { return socket.getTrafficClass(); } catch (SocketException e) { throw new ChannelException(e); } } public boolean isKeepAlive() { try { return socket.getKeepAlive(); } catch (SocketException e) { throw new ChannelException(e); } } public boolean isReuseAddress() { try { return socket.getReuseAddress(); } catch (SocketException e) { throw new ChannelException(e); } } public boolean isTcpNoDelay() { try { return socket.getTcpNoDelay(); } catch (SocketException e) { throw new ChannelException(e); } } public void setKeepAlive(boolean keepAlive) { this.keepAlive = keepAlive; try { socket.setKeepAlive(keepAlive); } catch (SocketException e) { throw new ChannelException(e); } } public void setPerformancePreferences( int connectionTime, int latency, int bandwidth) { this.connectionTime = connectionTime; this.latency = latency; this.bandwidth = bandwidth; socket.setPerformancePreferences(connectionTime, latency, bandwidth); } public void setReceiveBufferSize(int receiveBufferSize) { this.receiveBufferSize = receiveBufferSize; try { socket.setReceiveBufferSize(receiveBufferSize); } catch (SocketException e) { throw new ChannelException(e); } } public void setReuseAddress(boolean reuseAddress) { this.reuseAddress = reuseAddress; try { socket.setReuseAddress(reuseAddress); } catch (SocketException e) { throw new ChannelException(e); } } public void setSendBufferSize(int sendBufferSize) { this.sendBufferSize = sendBufferSize; if (socket != null) { try { socket.setSendBufferSize(sendBufferSize); } catch (SocketException e) { throw new ChannelException(e); } } } public void setSoLinger(int soLinger) { this.soLinger = soLinger; try { if (soLinger < 0) { socket.setSoLinger(false, 0); } else { socket.setSoLinger(true, soLinger); } } catch (SocketException e) { throw new ChannelException(e); } } public void setTcpNoDelay(boolean tcpNoDelay) { this.tcpNoDelay = tcpNoDelay; try { socket.setTcpNoDelay(tcpNoDelay); } catch (SocketException e) { throw new ChannelException(e); } } public void setTrafficClass(int trafficClass) { this.trafficClass = trafficClass; try { socket.setTrafficClass(trafficClass); } catch (SocketException e) { throw new ChannelException(e); } } HttpTunnelingSocketChannelConfig copyConfig(Socket socket) { HttpTunnelingSocketChannelConfig config = new HttpTunnelingSocketChannelConfig(socket); config.setConnectTimeoutMillis(getConnectTimeoutMillis()); if (trafficClass != null) { config.setTrafficClass(trafficClass); } if (tcpNoDelay != null) { config.setTcpNoDelay(tcpNoDelay); } if (soLinger != null) { config.setSoLinger(soLinger); } if (sendBufferSize != null) { config.setSendBufferSize(sendBufferSize); } if (reuseAddress != null) { config.setReuseAddress(reuseAddress); } if (receiveBufferSize != null) { config.setReceiveBufferSize(receiveBufferSize); } if (keepAlive != null) { config.setKeepAlive(keepAlive); } if (connectionTime != null) { config.setPerformancePreferences(connectionTime, latency, bandwidth); } return config; } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DatagramChannel.java0000644000175000017500000000434211216642730031352 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import org.jboss.netty.channel.Channel; /** * A UDP/IP {@link Channel} which is created by {@link DatagramChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1447 $, $Date: 2009-06-19 01:01:28 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.composedOf org.jboss.netty.channel.socket.DatagramChannelConfig */ public interface DatagramChannel extends Channel { DatagramChannelConfig getConfig(); InetSocketAddress getLocalAddress(); InetSocketAddress getRemoteAddress(); /** * Joins a multicast group. */ void joinGroup(InetAddress multicastAddress); /** * Joins the specified multicast group at the specified interface. */ void joinGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface); /** * Leaves a multicast group. */ void leaveGroup(InetAddress multicastAddress); /** * Leaves a multicast group on a specified local interface. */ void leaveGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface); } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/ServerSocketChannelFactory0000644000175000017500000000324111150053042032643 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ServerChannelFactory; /** * A {@link ChannelFactory} which creates a {@link ServerSocketChannel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 929 $, $Date: 2009-02-21 11:29:38 -0800 (Sat, 21 Feb 2009) $ * * @apiviz.has org.jboss.netty.channel.socket.ServerSocketChannel oneway - - creates */ public interface ServerSocketChannelFactory extends ServerChannelFactory { ServerSocketChannel newChannel(ChannelPipeline pipeline); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/0000755000175000017500000000000011316313135026253 5ustar deckerdecker././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioSocketChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioSocketChannelConfig0000644000175000017500000001524111216643550032524 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import org.jboss.netty.channel.AdaptiveReceiveBufferSizePredictor; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.SocketChannelConfig; /** * A {@link SocketChannelConfig} for a NIO TCP/IP {@link SocketChannel}. * *

Available options

* * In addition to the options provided by {@link ChannelConfig} and * {@link SocketChannelConfig}, {@link NioSocketChannelConfig} allows the * following options in the option map: * * * * * * * * * * * * * * * *
NameAssociated setter method
{@code "writeBufferHighWaterMark"}{@link #setWriteBufferHighWaterMark(int)}
{@code "writeBufferLowWaterMark"}{@link #setWriteBufferLowWaterMark(int)}
{@code "writeSpinCount"}{@link #setWriteSpinCount(int)}
{@code "receiveBufferSizePredictor"}{@link #setReceiveBufferSizePredictor(ReceiveBufferSizePredictor)}
{@code "readWriteFair"}{@link #setReadWriteFair(boolean)}
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1448 $, $Date: 2009-06-19 01:08:08 -0700 (Fri, 19 Jun 2009) $ */ public interface NioSocketChannelConfig extends SocketChannelConfig { /** * Returns the high water mark of the write buffer. If the number of bytes * queued in the write buffer exceeds this value, {@link Channel#isWritable()} * will start to return {@code true}. */ int getWriteBufferHighWaterMark(); /** * Sets the high water mark of the write buffer. If the number of bytes * queued in the write buffer exceeds this value, {@link Channel#isWritable()} * will start to return {@code true}. */ void setWriteBufferHighWaterMark(int writeBufferHighWaterMark); /** * Returns the low water mark of the write buffer. Once the number of bytes * queued in the write buffer exceeded the * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then * dropped down below this value, {@link Channel#isWritable()} will return * {@code false} again. */ int getWriteBufferLowWaterMark(); /** * Sets the low water mark of the write buffer. Once the number of bytes * queued in the write buffer exceeded the * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then * dropped down below this value, {@link Channel#isWritable()} will return * {@code false} again. */ void setWriteBufferLowWaterMark(int writeBufferLowWaterMark); /** * Returns the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. */ int getWriteSpinCount(); /** * Sets the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. * * @throws IllegalArgumentException * if the specified value is {@code 0} or less than {@code 0} */ void setWriteSpinCount(int writeSpinCount); /** * Returns the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link AdaptiveReceiveBufferSizePredictor}. */ ReceiveBufferSizePredictor getReceiveBufferSizePredictor(); /** * Sets the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link AdaptiveReceiveBufferSizePredictor}. */ void setReceiveBufferSizePredictor(ReceiveBufferSizePredictor predictor); /** * @deprecated This property has been replaced by the * {@code writeBufferHighWaterMark} and {@code writeBufferLowWaterMark}. * * Returns {@code true} if and only if an I/O thread should do its effort * to balance the ratio of read and write operations. Assuring * the read-write fairness is sometimes necessary in a high speed network * because a certain channel can spend too much time on flushing the * large number of write requests not giving enough time for other channels * to perform I/O. The default value is {@code false}. */ @Deprecated boolean isReadWriteFair(); /** * @deprecated This property has been replaced by the * {@code writeBufferHighWaterMark} and {@code writeBufferLowWaterMark}. * * Sets if an I/O thread should balance the ratio of read and write * operations. Assuring the read-write fairness is sometimes necessary * in a high speed network because a certain channel can spend too much * time on flushing the large number of write requests not giving enough * time for other channels to perform I/O. The default value is * {@code false}. */ @Deprecated void setReadWriteFair(boolean fair); } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioServerSocketPipelineSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioServerSocketPipelin0000644000175000017500000002260011213672505032611 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.IoWorkerRunnable; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ class NioServerSocketPipelineSink extends AbstractChannelSink { static final InternalLogger logger = InternalLoggerFactory.getInstance(NioServerSocketPipelineSink.class); private static final AtomicInteger nextId = new AtomicInteger(); private final int id = nextId.incrementAndGet(); private final NioWorker[] workers; private final AtomicInteger workerIndex = new AtomicInteger(); NioServerSocketPipelineSink(Executor workerExecutor, int workerCount) { workers = new NioWorker[workerCount]; for (int i = 0; i < workers.length; i ++) { workers[i] = new NioWorker(id, i + 1, workerExecutor); } } public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { Channel channel = e.getChannel(); if (channel instanceof NioServerSocketChannel) { handleServerSocket(e); } else if (channel instanceof NioSocketChannel) { handleAcceptedSocket(e); } } private void handleServerSocket(ChannelEvent e) { if (!(e instanceof ChannelStateEvent)) { return; } ChannelStateEvent event = (ChannelStateEvent) e; NioServerSocketChannel channel = (NioServerSocketChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (SocketAddress) value); } else { close(channel, future); } break; } } private void handleAcceptedSocket(ChannelEvent e) { if (e instanceof ChannelStateEvent) { ChannelStateEvent event = (ChannelStateEvent) e; NioSocketChannel channel = (NioSocketChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { NioWorker.close(channel, future); } break; case BOUND: case CONNECTED: if (value == null) { NioWorker.close(channel, future); } break; case INTEREST_OPS: NioWorker.setInterestOps(channel, future, ((Integer) value).intValue()); break; } } else if (e instanceof MessageEvent) { MessageEvent event = (MessageEvent) e; NioSocketChannel channel = (NioSocketChannel) event.getChannel(); boolean offered = channel.writeBuffer.offer(event); assert offered; NioWorker.write(channel, true); } } private void bind( NioServerSocketChannel channel, ChannelFuture future, SocketAddress localAddress) { boolean bound = false; boolean bossStarted = false; try { channel.socket.socket().bind(localAddress, channel.getConfig().getBacklog()); bound = true; future.setSuccess(); fireChannelBound(channel, channel.getLocalAddress()); Executor bossExecutor = ((NioServerSocketChannelFactory) channel.getFactory()).bossExecutor; bossExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( new Boss(channel), "New I/O server boss #" + id + " (channelId: " + channel.getId() + ", " + channel.getLocalAddress() + ')'))); bossStarted = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (!bossStarted && bound) { close(channel, future); } } } private void close(NioServerSocketChannel channel, ChannelFuture future) { boolean bound = channel.isBound(); try { channel.socket.close(); if (channel.setClosed()) { future.setSuccess(); if (bound) { fireChannelUnbound(channel); } fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } NioWorker nextWorker() { return workers[Math.abs( workerIndex.getAndIncrement() % workers.length)]; } private final class Boss implements Runnable { private final NioServerSocketChannel channel; Boss(NioServerSocketChannel channel) { this.channel = channel; } public void run() { for (;;) { try { // We do not call ServerSocketChannel.accept() directly // because SocketTimeoutException is not raised on some // JDKs. Socket acceptedSocket = channel.socket.socket().accept(); try { ChannelPipeline pipeline = channel.getConfig().getPipelineFactory().getPipeline(); NioWorker worker = nextWorker(); worker.register(new NioAcceptedSocketChannel( channel.getFactory(), pipeline, channel, NioServerSocketPipelineSink.this, acceptedSocket.getChannel(), worker), null); } catch (Exception e) { logger.warn( "Failed to initialize an accepted socket.", e); try { acceptedSocket.close(); } catch (IOException e2) { logger.warn( "Failed to close a partially accepted socket.", e2); } } } catch (SocketTimeoutException e) { // Thrown every second to get ClosedChannelException // raised. } catch (CancelledKeyException e) { // Raised by accept() when the server socket was closed. } catch (ClosedChannelException e) { // Closed as requested. break; } catch (IOException e) { logger.warn( "Failed to accept a connection.", e); try { Thread.sleep(1000); } catch (InterruptedException e1) { // Ignore } } } } } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioServerSocketChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioServerSocketChannel0000644000175000017500000001462211175574066032600 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.nio.channels.Selector; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.ServerSocketChannel; import org.jboss.netty.channel.socket.ServerSocketChannelFactory; import org.jboss.netty.util.internal.ExecutorUtil; /** * A {@link ServerSocketChannelFactory} which creates a server-side NIO-based * {@link ServerSocketChannel}. It utilizes the non-blocking I/O mode which * was introduced with NIO to serve many number of concurrent connections * efficiently. * *

How threads work

*

* There are two types of threads in a {@link NioServerSocketChannelFactory}; * one is boss thread and the other is worker thread. * *

Boss threads

*

* Each bound {@link ServerSocketChannel} has its own boss thread. * For example, if you opened two server ports such as 80 and 443, you will * have two boss threads. A boss thread accepts incoming connections until * the port is unbound. Once a connection is accepted successfully, the boss * thread passes the accepted {@link Channel} to one of the worker * threads that the {@link NioServerSocketChannelFactory} manages. * *

Worker threads

*

* One {@link NioServerSocketChannelFactory} can have one or more worker * threads. A worker thread performs non-blocking read and write for one or * more {@link Channel}s in a non-blocking mode. * *

Life cycle of threads and graceful shutdown

*

* All threads are acquired from the {@link Executor}s which were specified * when a {@link NioServerSocketChannelFactory} was created. Boss threads are * acquired from the {@code bossExecutor}, and worker threads are acquired from * the {@code workerExecutor}. Therefore, you should make sure the specified * {@link Executor}s are able to lend the sufficient number of threads. * It is the best bet to specify {@linkplain Executors#newCachedThreadPool() a cached thread pool}. *

* Both boss and worker threads are acquired lazily, and then released when * there's nothing left to process. All the related resources such as * {@link Selector} are also released when the boss and worker threads are * released. Therefore, to shut down a service gracefully, you should do the * following: * *

    *
  1. unbind all channels created by the factory, *
  2. close all child channels accepted by the unbound channels, and * (these two steps so far is usually done using {@link ChannelGroup#close()})
  3. *
  4. call {@link #releaseExternalResources()}.
  5. *
* * Please make sure not to shut down the executor until all channels are * closed. Otherwise, you will end up with a {@link RejectedExecutionException} * and the related resources might not be released properly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark */ public class NioServerSocketChannelFactory implements ServerSocketChannelFactory { final Executor bossExecutor; private final Executor workerExecutor; private final ChannelSink sink; /** * Creates a new instance. Calling this constructor is same with calling * {@link #NioServerSocketChannelFactory(Executor, Executor, int)} with * the number of available processors in the machine. The number of * available processors is obtained by {@link Runtime#availableProcessors()}. * * @param bossExecutor * the {@link Executor} which will execute the boss threads * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads */ public NioServerSocketChannelFactory( Executor bossExecutor, Executor workerExecutor) { this(bossExecutor, workerExecutor, Runtime.getRuntime().availableProcessors()); } /** * Creates a new instance. * * @param bossExecutor * the {@link Executor} which will execute the boss threads * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads * @param workerCount * the maximum number of I/O worker threads */ public NioServerSocketChannelFactory( Executor bossExecutor, Executor workerExecutor, int workerCount) { if (bossExecutor == null) { throw new NullPointerException("bossExecutor"); } if (workerExecutor == null) { throw new NullPointerException("workerExecutor"); } if (workerCount <= 0) { throw new IllegalArgumentException( "workerCount (" + workerCount + ") " + "must be a positive integer."); } this.bossExecutor = bossExecutor; this.workerExecutor = workerExecutor; sink = new NioServerSocketPipelineSink(workerExecutor, workerCount); } public ServerSocketChannel newChannel(ChannelPipeline pipeline) { return new NioServerSocketChannel(this, pipeline, sink); } public void releaseExternalResources() { ExecutorUtil.terminate(bossExecutor, workerExecutor); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioAcceptedSocketChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioAcceptedSocketChann0000644000175000017500000000437711203220562032504 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.nio.channels.SocketChannel; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1288 $, $Date: 2009-05-15 01:01:54 -0700 (Fri, 15 May 2009) $ * */ final class NioAcceptedSocketChannel extends NioSocketChannel { NioAcceptedSocketChannel( ChannelFactory factory, ChannelPipeline pipeline, Channel parent, ChannelSink sink, SocketChannel socket, NioWorker worker) { super(parent, factory, pipeline, sink, socket, worker); try { socket.configureBlocking(false); } catch (IOException e) { throw new ChannelException("Failed to enter non-blocking mode.", e); } fireChannelOpen(this); fireChannelBound(this, socket.socket().getLocalSocketAddress()); fireChannelConnected(this, socket.socket().getRemoteSocketAddress()); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel0000644000175000017500000000600111133514357032527 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.nio.channels.SocketChannel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 696 $, $Date: 2009-01-14 18:01:19 -0800 (Wed, 14 Jan 2009) $ * */ final class NioClientSocketChannel extends NioSocketChannel { private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioClientSocketChannel.class); private static SocketChannel newSocket() { SocketChannel socket; try { socket = SocketChannel.open(); } catch (IOException e) { throw new ChannelException("Failed to open a socket.", e); } boolean success = false; try { socket.configureBlocking(false); success = true; } catch (IOException e) { throw new ChannelException("Failed to enter non-blocking mode.", e); } finally { if (!success) { try { socket.close(); } catch (IOException e) { logger.warn( "Failed to close a partially initialized socket.", e); } } } return socket; } volatile ChannelFuture connectFuture; volatile boolean boundManually; NioClientSocketChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, NioWorker worker) { super(null, factory, pipeline, sink, newSocket(), worker); fireChannelOpen(this); } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramChannelConf0000644000175000017500000001264711216643550032503 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import org.jboss.netty.channel.AdaptiveReceiveBufferSizePredictor; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.channel.socket.DatagramChannel; import org.jboss.netty.channel.socket.DatagramChannelConfig; /** * A {@link DatagramChannelConfig} for a NIO TCP/IP {@link DatagramChannel}. * *

Available options

* * In addition to the options provided by {@link ChannelConfig} and * {@link DatagramChannelConfig}, {@link NioDatagramChannelConfig} allows the * following options in the option map: * * * * * * * * * * * * * *
NameAssociated setter method
{@code "writeBufferHighWaterMark"}{@link #setWriteBufferHighWaterMark(int)}
{@code "writeBufferLowWaterMark"}{@link #setWriteBufferLowWaterMark(int)}
{@code "writeSpinCount"}{@link #setWriteSpinCount(int)}
{@code "receiveBufferSizePredictor"}{@link #setReceiveBufferSizePredictor(ReceiveBufferSizePredictor)}
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author Daniel Bevenius (dbevenius@jboss.com) * * @version $Rev: 1448 $, $Date: 2009-06-19 01:08:08 -0700 (Fri, 19 Jun 2009) $ */ public interface NioDatagramChannelConfig extends DatagramChannelConfig { /** * Returns the high water mark of the write buffer. If the number of bytes * queued in the write buffer exceeds this value, {@link Channel#isWritable()} * will start to return {@code true}. */ int getWriteBufferHighWaterMark(); /** * Sets the high water mark of the write buffer. If the number of bytes * queued in the write buffer exceeds this value, {@link Channel#isWritable()} * will start to return {@code true}. */ void setWriteBufferHighWaterMark(int writeBufferHighWaterMark); /** * Returns the low water mark of the write buffer. Once the number of bytes * queued in the write buffer exceeded the * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then * dropped down below this value, {@link Channel#isWritable()} will return * {@code false} again. */ int getWriteBufferLowWaterMark(); /** * Sets the low water mark of the write buffer. Once the number of bytes * queued in the write buffer exceeded the * {@linkplain #setWriteBufferHighWaterMark(int) high water mark} and then * dropped down below this value, {@link Channel#isWritable()} will return * {@code false} again. */ void setWriteBufferLowWaterMark(int writeBufferLowWaterMark); /** * Returns the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. */ int getWriteSpinCount(); /** * Sets the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. * * @throws IllegalArgumentException * if the specified value is {@code 0} or less than {@code 0} */ void setWriteSpinCount(int writeSpinCount); /** * Returns the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link AdaptiveReceiveBufferSizePredictor}. */ ReceiveBufferSizePredictor getReceiveBufferSizePredictor(); /** * Sets the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link AdaptiveReceiveBufferSizePredictor}. */ void setReceiveBufferSizePredictor(ReceiveBufferSizePredictor predictor); } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramPipelineSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramPipelineSin0000644000175000017500000001645711216366721032551 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; /** * Receives downstream events from a {@link ChannelPipeline}. It contains * an array of I/O workers. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author Daniel Bevenius (dbevenius@jboss.com) * * @version $Rev: 1411 $, $Date: 2009-06-18 00:33:37 -0700 (Thu, 18 Jun 2009) $ */ class NioDatagramPipelineSink extends AbstractChannelSink { private static final AtomicInteger nextId = new AtomicInteger(); private final int id = nextId.incrementAndGet(); private final NioDatagramWorker[] workers; private final AtomicInteger workerIndex = new AtomicInteger(); /** * Creates a new {@link NioDatagramPipelineSink} with a the number of {@link NioDatagramWorker}s specified in workerCount. * The {@link NioDatagramWorker}s take care of reading and writing for the {@link NioDatagramChannel}. * * @param workerExecutor * @param workerCount The number of UdpWorkers for this sink. */ NioDatagramPipelineSink(final Executor workerExecutor, final int workerCount) { workers = new NioDatagramWorker[workerCount]; for (int i = 0; i < workers.length; i ++) { workers[i] = new NioDatagramWorker(id, i + 1, workerExecutor); } } /** * Handle downstream event. * * @param pipeline the {@link ChannelPipeline} that passes down the * downstream event. * @param e The downstream event. */ public void eventSunk(final ChannelPipeline pipeline, final ChannelEvent e) throws Exception { final NioDatagramChannel channel = (NioDatagramChannel) e.getChannel(); final ChannelFuture future = e.getFuture(); if (e instanceof ChannelStateEvent) { final ChannelStateEvent stateEvent = (ChannelStateEvent) e; final ChannelState state = stateEvent.getState(); final Object value = stateEvent.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { NioDatagramWorker.close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (InetSocketAddress) value); } else { NioDatagramWorker.close(channel, future); } break; case CONNECTED: if (value != null) { connect(channel, future, (InetSocketAddress) value); } else { NioDatagramWorker.disconnect(channel, future); } break; case INTEREST_OPS: NioDatagramWorker.setInterestOps(channel, future, ((Integer) value) .intValue()); break; } } else if (e instanceof MessageEvent) { final MessageEvent event = (MessageEvent) e; final boolean offered = channel.writeBufferQueue.offer(event); assert offered; NioDatagramWorker.write(channel, true); } } private void close(NioDatagramChannel channel, ChannelFuture future) { try { channel.getDatagramChannel().socket().close(); future.setSuccess(); if (channel.setClosed()) { if (channel.isBound()) { fireChannelUnbound(channel); } fireChannelClosed(channel); } } catch (final Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } /** * Will bind the DatagramSocket to the passed-in address. * Every call bind will spawn a new thread using the that basically in turn */ private void bind(final NioDatagramChannel channel, final ChannelFuture future, final InetSocketAddress address) { boolean bound = false; boolean started = false; try { // First bind the DatagramSocket the specified port. channel.getDatagramChannel().socket().bind(address); bound = true; future.setSuccess(); fireChannelBound(channel, address); channel.worker.register(channel, null); started = true; } catch (final Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (!started && bound) { close(channel, future); } } } private void connect( NioDatagramChannel channel, ChannelFuture future, SocketAddress remoteAddress) { boolean bound = channel.isBound(); boolean connected = false; boolean workerStarted = false; future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); try { channel.getDatagramChannel().connect(remoteAddress); connected = true; // Fire events. future.setSuccess(); if (!bound) { fireChannelBound(channel, channel.getLocalAddress()); } fireChannelConnected(channel, channel.getRemoteAddress()); if (!bound) { channel.worker.register(channel, future); } workerStarted = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (connected && !workerStarted) { NioDatagramWorker.close(channel, future); } } } NioDatagramWorker nextWorker() { return workers[Math.abs(workerIndex.getAndIncrement() % workers.length)]; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioServerSocketChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioServerSocketChannel0000644000175000017500000000711411150044463032560 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.ServerSocketChannel; import org.jboss.netty.channel.AbstractServerChannel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.socket.DefaultServerSocketChannelConfig; import org.jboss.netty.channel.socket.ServerSocketChannelConfig; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 922 $, $Date: 2009-02-21 10:34:27 -0800 (Sat, 21 Feb 2009) $ * */ class NioServerSocketChannel extends AbstractServerChannel implements org.jboss.netty.channel.socket.ServerSocketChannel { private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioServerSocketChannel.class); final ServerSocketChannel socket; private final ServerSocketChannelConfig config; NioServerSocketChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { super(factory, pipeline, sink); try { socket = ServerSocketChannel.open(); } catch (IOException e) { throw new ChannelException( "Failed to open a server socket.", e); } try { socket.socket().setSoTimeout(1000); } catch (IOException e) { try { socket.close(); } catch (IOException e2) { logger.warn( "Failed to close a partially initialized socket.", e2); } throw new ChannelException( "Failed to set the server socket timeout.", e); } config = new DefaultServerSocketChannelConfig(socket.socket()); fireChannelOpen(this); } public ServerSocketChannelConfig getConfig() { return config; } public InetSocketAddress getLocalAddress() { return (InetSocketAddress) socket.socket().getLocalSocketAddress(); } public InetSocketAddress getRemoteAddress() { return null; } public boolean isBound() { return isOpen() && socket.socket().isBound(); } @Override protected boolean setClosed() { return super.setClosed(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelineSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketPipelin0000644000175000017500000003542011214232473032562 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.ClosedChannelException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.IoWorkerRunnable; import org.jboss.netty.util.internal.LinkedTransferQueue; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1351 $, $Date: 2009-06-11 09:47:55 -0700 (Thu, 11 Jun 2009) $ * */ class NioClientSocketPipelineSink extends AbstractChannelSink { static final InternalLogger logger = InternalLoggerFactory.getInstance(NioClientSocketPipelineSink.class); private static final AtomicInteger nextId = new AtomicInteger(); final int id = nextId.incrementAndGet(); final Executor bossExecutor; private final Boss boss = new Boss(); private final NioWorker[] workers; private final AtomicInteger workerIndex = new AtomicInteger(); NioClientSocketPipelineSink( Executor bossExecutor, Executor workerExecutor, int workerCount) { this.bossExecutor = bossExecutor; workers = new NioWorker[workerCount]; for (int i = 0; i < workers.length; i ++) { workers[i] = new NioWorker(id, i + 1, workerExecutor); } } public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { ChannelStateEvent event = (ChannelStateEvent) e; NioClientSocketChannel channel = (NioClientSocketChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { NioWorker.close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (SocketAddress) value); } else { NioWorker.close(channel, future); } break; case CONNECTED: if (value != null) { connect(channel, future, (SocketAddress) value); } else { NioWorker.close(channel, future); } break; case INTEREST_OPS: NioWorker.setInterestOps(channel, future, ((Integer) value).intValue()); break; } } else if (e instanceof MessageEvent) { MessageEvent event = (MessageEvent) e; NioSocketChannel channel = (NioSocketChannel) event.getChannel(); boolean offered = channel.writeBuffer.offer(event); assert offered; NioWorker.write(channel, true); } } private void bind( NioClientSocketChannel channel, ChannelFuture future, SocketAddress localAddress) { try { channel.socket.socket().bind(localAddress); channel.boundManually = true; future.setSuccess(); fireChannelBound(channel, channel.getLocalAddress()); } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } private void connect( final NioClientSocketChannel channel, ChannelFuture future, SocketAddress remoteAddress) { try { if (channel.socket.connect(remoteAddress)) { channel.worker.register(channel, future); } else { future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); channel.connectFuture = future; boss.register(channel); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } NioWorker nextWorker() { return workers[Math.abs( workerIndex.getAndIncrement() % workers.length)]; } private final class Boss implements Runnable { volatile Selector selector; private boolean started; private final AtomicBoolean wakenUp = new AtomicBoolean(); private final Object startStopLock = new Object(); private final Queue registerTaskQueue = new LinkedTransferQueue(); Boss() { super(); } void register(NioSocketChannel channel) { Runnable registerTask = new RegisterTask(this, channel); Selector selector; synchronized (startStopLock) { if (!started) { // Open a selector if this worker didn't start yet. try { this.selector = selector = Selector.open(); } catch (Throwable t) { throw new ChannelException( "Failed to create a selector.", t); } // Start the worker thread with the new Selector. boolean success = false; try { bossExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( this, "New I/O client boss #" + id))); success = true; } finally { if (!success) { // Release the Selector if the execution fails. try { selector.close(); } catch (Throwable t) { logger.warn("Failed to close a selector.", t); } this.selector = selector = null; // The method will return to the caller at this point. } } } else { // Use the existing selector if this worker has been started. selector = this.selector; } assert selector != null && selector.isOpen(); started = true; boolean offered = registerTaskQueue.offer(registerTask); assert offered; } if (wakenUp.compareAndSet(false, true)) { selector.wakeup(); } } public void run() { boolean shutdown = false; Selector selector = this.selector; for (;;) { wakenUp.set(false); try { int selectedKeyCount = selector.select(500); // 'wakenUp.compareAndSet(false, true)' is always evaluated // before calling 'selector.wakeup()' to reduce the wake-up // overhead. (Selector.wakeup() is an expensive operation.) // // However, there is a race condition in this approach. // The race condition is triggered when 'wakenUp' is set to // true too early. // // 'wakenUp' is set to true too early if: // 1) Selector is waken up between 'wakenUp.set(false)' and // 'selector.select(...)'. (BAD) // 2) Selector is waken up between 'selector.select(...)' and // 'if (wakenUp.get()) { ... }'. (OK) // // In the first case, 'wakenUp' is set to true and the // following 'selector.select(...)' will wake up immediately. // Until 'wakenUp' is set to false again in the next round, // 'wakenUp.compareAndSet(false, true)' will fail, and therefore // any attempt to wake up the Selector will fail, too, causing // the following 'selector.select(...)' call to block // unnecessarily. // // To fix this problem, we wake up the selector again if wakenUp // is true immediately after selector.select(...). // It is inefficient in that it wakes up the selector for both // the first case (BAD - wake-up required) and the second case // (OK - no wake-up required). if (wakenUp.get()) { selector.wakeup(); } processRegisterTaskQueue(); if (selectedKeyCount > 0) { processSelectedKeys(selector.selectedKeys()); } // Exit the loop when there's nothing to handle. // The shutdown flag is used to delay the shutdown of this // loop to avoid excessive Selector creation when // connection attempts are made in a one-by-one manner // instead of concurrent manner. if (selector.keys().isEmpty()) { if (shutdown || bossExecutor instanceof ExecutorService && ((ExecutorService) bossExecutor).isShutdown()) { synchronized (startStopLock) { if (registerTaskQueue.isEmpty() && selector.keys().isEmpty()) { started = false; try { selector.close(); } catch (IOException e) { logger.warn( "Failed to close a selector.", e); } finally { this.selector = null; } break; } else { shutdown = false; } } } else { // Give one more second. shutdown = true; } } else { shutdown = false; } } catch (Throwable t) { logger.warn( "Unexpected exception in the selector loop.", t); // Prevent possible consecutive immediate failures. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore. } } } } private void processRegisterTaskQueue() { for (;;) { final Runnable task = registerTaskQueue.poll(); if (task == null) { break; } task.run(); } } private void processSelectedKeys(Set selectedKeys) { for (Iterator i = selectedKeys.iterator(); i.hasNext();) { SelectionKey k = i.next(); i.remove(); if (!k.isValid()) { close(k); continue; } if (k.isConnectable()) { connect(k); } } } private void connect(SelectionKey k) { NioClientSocketChannel ch = (NioClientSocketChannel) k.attachment(); try { if (ch.socket.finishConnect()) { k.cancel(); ch.worker.register(ch, ch.connectFuture); } } catch (Throwable t) { ch.connectFuture.setFailure(t); fireExceptionCaught(ch, t); close(k); } } private void close(SelectionKey k) { k.cancel(); NioSocketChannel ch = (NioSocketChannel) k.attachment(); NioWorker.close(ch, succeededFuture(ch)); } } private static final class RegisterTask implements Runnable { private final Boss boss; private final NioSocketChannel channel; RegisterTask(Boss boss, NioSocketChannel channel) { this.boss = boss; this.channel = channel; } public void run() { try { channel.socket.register( boss.selector, SelectionKey.OP_CONNECT, channel); } catch (ClosedChannelException e) { throw new ChannelException( "Failed to register a socket to the selector.", e); } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/package-info.java0000644000175000017500000000232011066406360031444 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * NIO-based socket channel * API implementation - recommended for a large number of connections (>= 1000). */ package org.jboss.netty.channel.socket.nio; ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramChannelFact0000644000175000017500000001261111216652063032461 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.nio.channels.Selector; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.DatagramChannel; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import org.jboss.netty.util.internal.ExecutorUtil; /** * A {@link DatagramChannelFactory} that creates a NIO-based connectionless * {@link DatagramChannel}. It utilizes the non-blocking I/O mode which * was introduced with NIO to serve many number of concurrent connections * efficiently. * *

How threads work

*

* There is only one thread type in a {@link NioDatagramChannelFactory}; * worker threads. * *

Worker threads

*

* One {@link NioDatagramChannelFactory} can have one or more worker * threads. A worker thread performs non-blocking read and write for one or * more {@link DatagramChannel}s in a non-blocking mode. * *

Life cycle of threads and graceful shutdown

*

* All worker threads are acquired from the {@link Executor} which was specified * when a {@link NioDatagramChannelFactory} was created. Therefore, you should * make sure the specified {@link Executor} is able to lend the sufficient * number of threads. It is the best bet to specify * {@linkplain Executors#newCachedThreadPool() a cached thread pool}. *

* All worker threads are acquired lazily, and then released when there's * nothing left to process. All the related resources such as {@link Selector} * are also released when the worker threads are released. Therefore, to shut * down a service gracefully, you should do the following: * *

    *
  1. close all channels created by the factory usually using * {@link ChannelGroup#close()}, and
  2. *
  3. call {@link #releaseExternalResources()}.
  4. *
* * Please make sure not to shut down the executor until all channels are * closed. Otherwise, you will end up with a {@link RejectedExecutionException} * and the related resources might not be released properly. * *

Limitation

*

* Multicast is not supported. Please use {@link OioDatagramChannelFactory} * instead. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author Daniel Bevenius (dbevenius@jboss.com) * * @version $Rev: 1451 $, $Date: 2009-06-19 02:02:43 -0700 (Fri, 19 Jun 2009) $ */ public class NioDatagramChannelFactory implements DatagramChannelFactory { private final Executor workerExecutor; private final NioDatagramPipelineSink sink; /** * Creates a new instance. Calling this constructor is same with calling * {@link #NioDatagramChannelFactory(Executor, int)} with the number of * available processors in the machine. The number of available processors * is obtained by {@link Runtime#availableProcessors()}. * * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads */ public NioDatagramChannelFactory(final Executor workerExecutor) { this(workerExecutor, Runtime.getRuntime().availableProcessors()); } /** * Creates a new instance. * * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads * @param workerCount * the maximum number of I/O worker threads */ public NioDatagramChannelFactory(final Executor workerExecutor, final int workerCount) { if (workerCount <= 0) { throw new IllegalArgumentException(String .format("workerCount (%s) must be a positive integer.", workerCount)); } if (workerExecutor == null) { throw new NullPointerException( "workerExecutor argument must not be null"); } this.workerExecutor = workerExecutor; sink = new NioDatagramPipelineSink(workerExecutor, workerCount); } public DatagramChannel newChannel(final ChannelPipeline pipeline) { return new NioDatagramChannel(this, pipeline, sink, sink.nextWorker()); } public void releaseExternalResources() { ExecutorUtil.terminate(workerExecutor); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioSocketChannel.java0000644000175000017500000001731211165336702032320 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.SocketChannel; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.internal.LinkedTransferQueue; import org.jboss.netty.util.internal.ThreadLocalBoolean; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ class NioSocketChannel extends AbstractChannel implements org.jboss.netty.channel.socket.SocketChannel { final SocketChannel socket; final NioWorker worker; private final NioSocketChannelConfig config; final Object interestOpsLock = new Object(); final Object writeLock = new Object(); final Runnable writeTask = new WriteTask(); final AtomicBoolean writeTaskInTaskQueue = new AtomicBoolean(); final Queue writeBuffer = new WriteBuffer(); final AtomicInteger writeBufferSize = new AtomicInteger(); final AtomicInteger highWaterMarkCounter = new AtomicInteger(); volatile boolean inWriteNowLoop; MessageEvent currentWriteEvent; int currentWriteIndex; public NioSocketChannel( Channel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, SocketChannel socket, NioWorker worker) { super(parent, factory, pipeline, sink); this.socket = socket; this.worker = worker; config = new DefaultNioSocketChannelConfig(socket.socket()); } public NioSocketChannelConfig getConfig() { return config; } public InetSocketAddress getLocalAddress() { try { return (InetSocketAddress) socket.socket().getLocalSocketAddress(); } catch (Throwable t) { // Sometimes fails on a closed socket in Windows. return null; } } public InetSocketAddress getRemoteAddress() { try { return (InetSocketAddress) socket.socket().getRemoteSocketAddress(); } catch (Throwable t) { // Sometimes fails on a closed socket in Windows. return null; } } public boolean isBound() { return isOpen() && socket.socket().isBound(); } public boolean isConnected() { return isOpen() && socket.socket().isConnected(); } @Override public int getInterestOps() { if (!isOpen()) { return Channel.OP_WRITE; } int interestOps = getRawInterestOps(); int writeBufferSize = this.writeBufferSize.get(); if (writeBufferSize != 0) { if (highWaterMarkCounter.get() > 0) { int lowWaterMark = getConfig().getWriteBufferLowWaterMark(); if (writeBufferSize >= lowWaterMark) { interestOps |= Channel.OP_WRITE; } else { interestOps &= ~Channel.OP_WRITE; } } else { int highWaterMark = getConfig().getWriteBufferHighWaterMark(); if (writeBufferSize >= highWaterMark) { interestOps |= Channel.OP_WRITE; } else { interestOps &= ~Channel.OP_WRITE; } } } else { interestOps &= ~Channel.OP_WRITE; } return interestOps; } int getRawInterestOps() { return super.getInterestOps(); } void setRawInterestOpsNow(int interestOps) { super.setInterestOpsNow(interestOps); } @Override protected boolean setClosed() { return super.setClosed(); } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) { return super.write(message, null); } else { return getUnsupportedOperationFuture(); } } private final class WriteBuffer extends LinkedTransferQueue { private final ThreadLocalBoolean notifying = new ThreadLocalBoolean(); WriteBuffer() { super(); } @Override public boolean offer(MessageEvent e) { boolean success = super.offer(e); assert success; int messageSize = ((ChannelBuffer) e.getMessage()).readableBytes(); int newWriteBufferSize = writeBufferSize.addAndGet(messageSize); int highWaterMark = getConfig().getWriteBufferHighWaterMark(); if (newWriteBufferSize >= highWaterMark) { if (newWriteBufferSize - messageSize < highWaterMark) { highWaterMarkCounter.incrementAndGet(); if (!notifying.get()) { notifying.set(Boolean.TRUE); fireChannelInterestChanged(NioSocketChannel.this); notifying.set(Boolean.FALSE); } } } return true; } @Override public MessageEvent poll() { MessageEvent e = super.poll(); if (e != null) { int messageSize = ((ChannelBuffer) e.getMessage()).readableBytes(); int newWriteBufferSize = writeBufferSize.addAndGet(-messageSize); int lowWaterMark = getConfig().getWriteBufferLowWaterMark(); if (newWriteBufferSize == 0 || newWriteBufferSize < lowWaterMark) { if (newWriteBufferSize + messageSize >= lowWaterMark) { highWaterMarkCounter.decrementAndGet(); if (!notifying.get()) { notifying.set(Boolean.TRUE); fireChannelInterestChanged(NioSocketChannel.this); notifying.set(Boolean.FALSE); } } } } return e; } } private final class WriteTask implements Runnable { WriteTask() { super(); } public void run() { writeTaskInTaskQueue.set(false); NioWorker.write(NioSocketChannel.this, false); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioProviderMetadata.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioProviderMetadata.ja0000644000175000017500000004136511213672505032506 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.io.IOException; import java.net.InetSocketAddress; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.spi.SelectorProvider; import java.util.Set; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.SystemPropertyUtil; /** * Provides information which is specific to a NIO service provider * implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ class NioProviderMetadata { static final InternalLogger logger = InternalLoggerFactory.getInstance(NioProviderMetadata.class); private static final String CONSTRAINT_LEVEL_PROPERTY = "java.nio.channels.spi.constraintLevel"; private static final long AUTODETECTION_TIMEOUT = 7000L; /** * 0 - no need to wake up to get / set interestOps (most cases) * 1 - no need to wake up to get interestOps, but need to wake up to set. * 2 - need to wake up to get / set interestOps (old providers) */ static final int CONSTRAINT_LEVEL; static { int constraintLevel = -1; // Use the system property if possible. try { String value = SystemPropertyUtil.get(CONSTRAINT_LEVEL_PROPERTY, "-1"); constraintLevel = Integer.parseInt(value); if (constraintLevel < 0 || constraintLevel > 2) { constraintLevel = -1; } else { logger.debug( "Using the specified NIO constraint level: " + constraintLevel); } } catch (Exception e) { // format error } if (constraintLevel < 0) { constraintLevel = detectConstraintLevelFromSystemProperties(); if (constraintLevel < 0) { logger.debug( "Couldn't get the NIO constraint level from the system properties."); ConstraintLevelAutodetector autodetector = new ConstraintLevelAutodetector(); try { constraintLevel = autodetector.autodetectWithTimeout(); } catch (Exception e) { // Probably because of security manager - try again without // creating a new thread directly. constraintLevel = autodetector.autodetectWithoutTimeout(); } } if (constraintLevel < 0) { constraintLevel = 2; logger.warn( "Failed to autodetect the NIO constraint level; " + "using the safest level (2)"); } else if (constraintLevel != 0) { logger.info( "Using the autodetected NIO constraint level: " + constraintLevel + " (Use better NIO provider for better performance)"); } else { logger.debug( "Using the autodetected NIO constraint level: " + constraintLevel); } } CONSTRAINT_LEVEL = constraintLevel; if (CONSTRAINT_LEVEL < 0 || CONSTRAINT_LEVEL > 2) { throw new Error( "Unexpected NIO constraint level: " + CONSTRAINT_LEVEL + ", please report this error."); } } private static int detectConstraintLevelFromSystemProperties() { String version = SystemPropertyUtil.get("java.specification.version"); String os = SystemPropertyUtil.get("os.name"); String vendor = SystemPropertyUtil.get("java.vm.vendor"); String provider; try { provider = SelectorProvider.provider().getClass().getName(); } catch (Exception e) { // Perhaps security exception. provider = null; } if (version == null || os == null || vendor == null || provider == null) { return -1; } os = os.toLowerCase(); vendor = vendor.toLowerCase(); // Sun JVM if (vendor.indexOf("sun") >= 0) { // Linux if (os.indexOf("linux") >= 0) { if (provider.equals("sun.nio.ch.EPollSelectorProvider") || provider.equals("sun.nio.ch.PollSelectorProvider")) { return 0; } // Windows } else if (os.indexOf("windows") >= 0) { if (provider.equals("sun.nio.ch.WindowsSelectorProvider")) { return 0; } // Solaris } else if (os.indexOf("sun") >= 0 || os.indexOf("solaris") >= 0) { if (provider.equals("sun.nio.ch.DevPollSelectorProvider")) { return 0; } } // Apple JVM } else if (vendor.indexOf("apple") >= 0) { // Mac OS if (os.indexOf("mac") >= 0 && os.indexOf("os") >= 0) { if (provider.equals("sun.nio.ch.KQueueSelectorProvider")) { return 0; } } // IBM } else if (vendor.indexOf("ibm") >= 0) { // Linux if (os.indexOf("linux") >= 0) { if (version.equals("1.5") || version.matches("^1\\.5\\D.*$")) { if (provider.equals("sun.nio.ch.PollSelectorProvider")) { return 1; } } // Commented out - the constraint level of IBM JDK 1.6 is // different between versions. // //else if (version.equals("1.6") || version.matches("^1\\.6\\D.*$")) { // if (provider.equals("sun.nio.ch.EPollSelectorProvider") || // provider.equals("sun.nio.ch.PollSelectorProvider")) { // return 2; // } //} // AIX } if (os.indexOf("aix") >= 0) { if (version.equals("1.5") || version.matches("^1\\.5\\D.*$")) { if (provider.equals("sun.nio.ch.PollSelectorProvider")) { return 1; } } // Commented out - the constraint level of IBM JDK 1.6 is // different between versions. // //else if (version.equals("1.6") || version.matches("^1\\.6\\D.*$")) { // if (provider.equals("sun.nio.ch.EPollSelectorProvider") || // provider.equals("sun.nio.ch.PollSelectorProvider")) { // return 2; // } //} } // BEA } else if (vendor.indexOf("bea") >= 0 || vendor.indexOf("oracle") >= 0) { // Linux if (os.indexOf("linux") >= 0) { if (provider.equals("sun.nio.ch.EPollSelectorProvider") || provider.equals("sun.nio.ch.PollSelectorProvider")) { return 0; } // Windows } else if (os.indexOf("windows") >= 0) { if (provider.equals("sun.nio.ch.WindowsSelectorProvider")) { return 0; } } } // Others (untested) return -1; } private static final class ConstraintLevelAutodetector { ConstraintLevelAutodetector() { super(); } int autodetectWithTimeout() { final BlockingQueue resultQueue = new LinkedBlockingQueue(); Runnable detector = new ThreadRenamingRunnable(new Runnable() { public void run() { int level = -1; try { level = autodetectWithoutTimeout(); } finally { boolean finished = resultQueue.offer(Integer.valueOf(level)); assert finished; } } }, "NIO constraint level detector"); Thread detectorThread = new Thread(detector); detectorThread.start(); for (;;) { try { Integer result = resultQueue.poll(AUTODETECTION_TIMEOUT, TimeUnit.MILLISECONDS); if (result == null) { logger.warn("NIO constraint level autodetection timed out."); return -1; } else { return result.intValue(); } } catch (InterruptedException e) { // Ignored } } } int autodetectWithoutTimeout() { final int constraintLevel; ExecutorService executor = Executors.newCachedThreadPool(); boolean success; long startTime; int interestOps; ServerSocketChannel ch = null; SelectorLoop loop = null; try { // Open a channel. ch = ServerSocketChannel.open(); // Configure the channel try { ch.socket().bind(new InetSocketAddress(0)); ch.configureBlocking(false); } catch (Throwable e) { logger.warn("Failed to configure a temporary socket.", e); return -1; } // Prepare the selector loop. try { loop = new SelectorLoop(); } catch (Throwable e) { logger.warn("Failed to open a temporary selector.", e); return -1; } // Register the channel try { ch.register(loop.selector, 0); } catch (Throwable e) { logger.warn("Failed to register a temporary selector.", e); return -1; } SelectionKey key = ch.keyFor(loop.selector); // Start the selector loop. executor.execute(loop); // Level 0 success = true; for (int i = 0; i < 10; i ++) { // Increase the probability of calling interestOps // while select() is running. do { while (!loop.selecting) { Thread.yield(); } // Wait a little bit more. try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore } } while (!loop.selecting); startTime = System.nanoTime(); key.interestOps(key.interestOps() | SelectionKey.OP_ACCEPT); key.interestOps(key.interestOps() & ~SelectionKey.OP_ACCEPT); if (System.nanoTime() - startTime >= 500000000L) { success = false; break; } } if (success) { constraintLevel = 0; } else { // Level 1 success = true; for (int i = 0; i < 10; i ++) { // Increase the probability of calling interestOps // while select() is running. do { while (!loop.selecting) { Thread.yield(); } // Wait a little bit more. try { Thread.sleep(50); } catch (InterruptedException e) { // Ignore } } while (!loop.selecting); startTime = System.nanoTime(); interestOps = key.interestOps(); synchronized (loop) { loop.selector.wakeup(); key.interestOps(interestOps | SelectionKey.OP_ACCEPT); key.interestOps(interestOps & ~SelectionKey.OP_ACCEPT); } if (System.nanoTime() - startTime >= 500000000L) { success = false; break; } } if (success) { constraintLevel = 1; } else { constraintLevel = 2; } } } catch (Throwable e) { return -1; } finally { if (ch != null) { try { ch.close(); } catch (Throwable e) { logger.warn("Failed to close a temporary socket.", e); } } if (loop != null) { loop.done = true; try { executor.shutdownNow(); } catch (NullPointerException ex) { // Some JDK throws NPE here, but shouldn't. } try { for (;;) { loop.selector.wakeup(); try { if (executor.awaitTermination(1, TimeUnit.SECONDS)) { break; } } catch (InterruptedException e) { // Ignore } } } catch (Throwable e) { // Perhaps security exception. } try { loop.selector.close(); } catch (Throwable e) { logger.warn("Failed to close a temporary selector.", e); } } } return constraintLevel; } } private static final class SelectorLoop implements Runnable { final Selector selector; volatile boolean done; volatile boolean selecting; // Just an approximation SelectorLoop() throws IOException { selector = Selector.open(); } public void run() { while (!done) { synchronized (this) { // Guard } try { selecting = true; try { selector.select(1000); } finally { selecting = false; } Set keys = selector.selectedKeys(); for (SelectionKey k: keys) { k.interestOps(0); } keys.clear(); } catch (IOException e) { logger.warn("Failed to wait for a temporary selector.", e); } } } } } ././@LongLink0000000000000000000000000000016300000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/DefaultNioDatagramChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/DefaultNioDatagramChan0000644000175000017500000001332011214110567032463 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.net.DatagramSocket; import java.util.Map; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.channel.socket.DefaultDatagramChannelConfig; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.ConversionUtil; /** * The default {@link NioSocketChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author Daniel Bevenius (dbevenius@jboss.com) * * @version $Rev: 1345 $, $Date: 2009-06-10 22:09:11 -0700 (Wed, 10 Jun 2009) $ * */ class DefaultNioDatagramChannelConfig extends DefaultDatagramChannelConfig implements NioDatagramChannelConfig { private static final InternalLogger logger = InternalLoggerFactory .getInstance(DefaultNioDatagramChannelConfig.class); private volatile int writeBufferHighWaterMark = 64 * 1024; private volatile int writeBufferLowWaterMark = 32 * 1024; private volatile int writeSpinCount = 16; DefaultNioDatagramChannelConfig(DatagramSocket socket) { super(socket); } @Override public void setOptions(Map options) { super.setOptions(options); if (getWriteBufferHighWaterMark() < getWriteBufferLowWaterMark()) { // Recover the integrity of the configuration with a sensible value. setWriteBufferLowWaterMark0(getWriteBufferHighWaterMark() >>> 1); // Notify the user about misconfiguration. logger.warn("writeBufferLowWaterMark cannot be greater than " + "writeBufferHighWaterMark; setting to the half of the " + "writeBufferHighWaterMark."); } } @Override public boolean setOption(String key, Object value) { if (super.setOption(key, value)) { return true; } if (key.equals("writeBufferHighWaterMark")) { setWriteBufferHighWaterMark0(ConversionUtil.toInt(value)); } else if (key.equals("writeBufferLowWaterMark")) { setWriteBufferLowWaterMark0(ConversionUtil.toInt(value)); } else if (key.equals("writeSpinCount")) { setWriteSpinCount(ConversionUtil.toInt(value)); } else if (key.equals("receiveBufferSizePredictor")) { setReceiveBufferSizePredictor((ReceiveBufferSizePredictor) value); } else { return false; } return true; } public int getWriteBufferHighWaterMark() { return writeBufferHighWaterMark; } public void setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { if (writeBufferHighWaterMark < getWriteBufferLowWaterMark()) { throw new IllegalArgumentException( "writeBufferHighWaterMark cannot be less than " + "writeBufferLowWaterMark (" + getWriteBufferLowWaterMark() + "): " + writeBufferHighWaterMark); } setWriteBufferHighWaterMark0(writeBufferHighWaterMark); } private void setWriteBufferHighWaterMark0(int writeBufferHighWaterMark) { if (writeBufferHighWaterMark < 0) { throw new IllegalArgumentException("writeBufferHighWaterMark: " + writeBufferHighWaterMark); } this.writeBufferHighWaterMark = writeBufferHighWaterMark; } public int getWriteBufferLowWaterMark() { return writeBufferLowWaterMark; } public void setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { if (writeBufferLowWaterMark > getWriteBufferHighWaterMark()) { throw new IllegalArgumentException( "writeBufferLowWaterMark cannot be greater than " + "writeBufferHighWaterMark (" + getWriteBufferHighWaterMark() + "): " + writeBufferLowWaterMark); } setWriteBufferLowWaterMark0(writeBufferLowWaterMark); } private void setWriteBufferLowWaterMark0(int writeBufferLowWaterMark) { if (writeBufferLowWaterMark < 0) { throw new IllegalArgumentException("writeBufferLowWaterMark: " + writeBufferLowWaterMark); } this.writeBufferLowWaterMark = writeBufferLowWaterMark; } public int getWriteSpinCount() { return writeSpinCount; } public void setWriteSpinCount(int writeSpinCount) { if (writeSpinCount <= 0) { throw new IllegalArgumentException( "writeSpinCount must be a positive integer."); } this.writeSpinCount = writeSpinCount; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/DefaultNioSocketChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/DefaultNioSocketChanne0000644000175000017500000001470111165336702032530 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.net.Socket; import java.util.Map; import org.jboss.netty.channel.AdaptiveReceiveBufferSizePredictor; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.channel.socket.DefaultSocketChannelConfig; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.ConversionUtil; /** * The default {@link NioSocketChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ class DefaultNioSocketChannelConfig extends DefaultSocketChannelConfig implements NioSocketChannelConfig { private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultNioSocketChannelConfig.class); private volatile int writeBufferHighWaterMark = 64 * 1024; private volatile int writeBufferLowWaterMark = 32 * 1024; private volatile ReceiveBufferSizePredictor predictor = new AdaptiveReceiveBufferSizePredictor(); private volatile int writeSpinCount = 16; DefaultNioSocketChannelConfig(Socket socket) { super(socket); } @Override public void setOptions(Map options) { super.setOptions(options); if (getWriteBufferHighWaterMark() < getWriteBufferLowWaterMark()) { // Recover the integrity of the configuration with a sensible value. setWriteBufferLowWaterMark0(getWriteBufferHighWaterMark() >>> 1); // Notify the user about misconfiguration. logger.warn( "writeBufferLowWaterMark cannot be greater than " + "writeBufferHighWaterMark; setting to the half of the " + "writeBufferHighWaterMark."); } } @Override public boolean setOption(String key, Object value) { if (super.setOption(key, value)) { return true; } if (key.equals("readWriteFair")) { setReadWriteFair(true); // Deprecated } else if (key.equals("writeBufferHighWaterMark")) { setWriteBufferHighWaterMark0(ConversionUtil.toInt(value)); } else if (key.equals("writeBufferLowWaterMark")) { setWriteBufferLowWaterMark0(ConversionUtil.toInt(value)); } else if (key.equals("writeSpinCount")) { setWriteSpinCount(ConversionUtil.toInt(value)); } else if (key.equals("receiveBufferSizePredictor")) { setReceiveBufferSizePredictor((ReceiveBufferSizePredictor) value); } else { return false; } return true; } public int getWriteBufferHighWaterMark() { return writeBufferHighWaterMark; } public void setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { if (writeBufferHighWaterMark < getWriteBufferLowWaterMark()) { throw new IllegalArgumentException( "writeBufferHighWaterMark cannot be less than " + "writeBufferLowWaterMark (" + getWriteBufferLowWaterMark() + "): " + writeBufferHighWaterMark); } setWriteBufferHighWaterMark0(writeBufferHighWaterMark); } private void setWriteBufferHighWaterMark0(int writeBufferHighWaterMark) { if (writeBufferHighWaterMark < 0) { throw new IllegalArgumentException( "writeBufferHighWaterMark: " + writeBufferHighWaterMark); } this.writeBufferHighWaterMark = writeBufferHighWaterMark; } public int getWriteBufferLowWaterMark() { return writeBufferLowWaterMark; } public void setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { if (writeBufferLowWaterMark > getWriteBufferHighWaterMark()) { throw new IllegalArgumentException( "writeBufferLowWaterMark cannot be greater than " + "writeBufferHighWaterMark (" + getWriteBufferHighWaterMark() + "): " + writeBufferLowWaterMark); } setWriteBufferLowWaterMark0(writeBufferLowWaterMark); } private void setWriteBufferLowWaterMark0(int writeBufferLowWaterMark) { if (writeBufferLowWaterMark < 0) { throw new IllegalArgumentException( "writeBufferLowWaterMark: " + writeBufferLowWaterMark); } this.writeBufferLowWaterMark = writeBufferLowWaterMark; } public int getWriteSpinCount() { return writeSpinCount; } public void setWriteSpinCount(int writeSpinCount) { if (writeSpinCount <= 0) { throw new IllegalArgumentException( "writeSpinCount must be a positive integer."); } this.writeSpinCount = writeSpinCount; } public ReceiveBufferSizePredictor getReceiveBufferSizePredictor() { return predictor; } public void setReceiveBufferSizePredictor( ReceiveBufferSizePredictor predictor) { if (predictor == null) { throw new NullPointerException("predictor"); } this.predictor = predictor; } public boolean isReadWriteFair() { logger.warn( "Detected an access to a deprecated configuration parameter: " + "readWriteFair"); return true; } public void setReadWriteFair(boolean readWriteFair) { isReadWriteFair(); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioClientSocketChannel0000644000175000017500000001423511175574066032550 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import java.nio.channels.Selector; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.util.internal.ExecutorUtil; /** * A {@link ClientSocketChannelFactory} which creates a client-side NIO-based * {@link SocketChannel}. It utilizes the non-blocking I/O mode which was * introduced with NIO to serve many number of concurrent connections * efficiently. * *

How threads work

*

* There are two types of threads in a {@link NioClientSocketChannelFactory}; * one is boss thread and the other is worker thread. * *

Boss thread

*

* One {@link NioClientSocketChannelFactory} has one boss thread. It makes * a connection attempt on request. Once a connection attempt succeeds, * the boss thread passes the connected {@link Channel} to one of the worker * threads that the {@link NioClientSocketChannelFactory} manages. * *

Worker threads

*

* One {@link NioClientSocketChannelFactory} can have one or more worker * threads. A worker thread performs non-blocking read and write for one or * more {@link Channel}s in a non-blocking mode. * *

Life cycle of threads and graceful shutdown

*

* All threads are acquired from the {@link Executor}s which were specified * when a {@link NioClientSocketChannelFactory} was created. A boss thread is * acquired from the {@code bossExecutor}, and worker threads are acquired from * the {@code workerExecutor}. Therefore, you should make sure the specified * {@link Executor}s are able to lend the sufficient number of threads. * It is the best bet to specify {@linkplain Executors#newCachedThreadPool() a cached thread pool}. *

* Both boss and worker threads are acquired lazily, and then released when * there's nothing left to process. All the related resources such as * {@link Selector} are also released when the boss and worker threads are * released. Therefore, to shut down a service gracefully, you should do the * following: * *

    *
  1. close all channels created by the factory usually using * {@link ChannelGroup#close()}, and
  2. *
  3. call {@link #releaseExternalResources()}.
  4. *
* * Please make sure not to shut down the executor until all channels are * closed. Otherwise, you will end up with a {@link RejectedExecutionException} * and the related resources might not be released properly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark */ public class NioClientSocketChannelFactory implements ClientSocketChannelFactory { private final Executor bossExecutor; private final Executor workerExecutor; private final NioClientSocketPipelineSink sink; /** * Creates a new instance. Calling this constructor is same with calling * {@link #NioClientSocketChannelFactory(Executor, Executor, int)} with * the number of available processors in the machine. The number of * available processors is obtained by {@link Runtime#availableProcessors()}. * * @param bossExecutor * the {@link Executor} which will execute the boss thread * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads */ public NioClientSocketChannelFactory( Executor bossExecutor, Executor workerExecutor) { this(bossExecutor, workerExecutor, Runtime.getRuntime().availableProcessors()); } /** * Creates a new instance. * * @param bossExecutor * the {@link Executor} which will execute the boss thread * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads * @param workerCount * the maximum number of I/O worker threads */ public NioClientSocketChannelFactory( Executor bossExecutor, Executor workerExecutor, int workerCount) { if (bossExecutor == null) { throw new NullPointerException("bossExecutor"); } if (workerExecutor == null) { throw new NullPointerException("workerExecutor"); } if (workerCount <= 0) { throw new IllegalArgumentException( "workerCount (" + workerCount + ") " + "must be a positive integer."); } this.bossExecutor = bossExecutor; this.workerExecutor = workerExecutor; sink = new NioClientSocketPipelineSink(bossExecutor, workerExecutor, workerCount); } public SocketChannel newChannel(ChannelPipeline pipeline) { return new NioClientSocketChannel(this, pipeline, sink, sink.nextWorker()); } public void releaseExternalResources() { ExecutorUtil.terminate(bossExecutor, workerExecutor); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioWorker.java0000644000175000017500000006527311215374443031061 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.SocketAddress; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.NotYetConnectedException; import java.nio.channels.ScatteringByteChannel; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.CompositeChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.DownstreamMessageEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.IoWorkerRunnable; import org.jboss.netty.util.internal.LinkedTransferQueue; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1369 $, $Date: 2009-06-15 00:32:51 -0700 (Mon, 15 Jun 2009) $ * */ class NioWorker implements Runnable { private static final InternalLogger logger = InternalLoggerFactory.getInstance(NioWorker.class); private static final int CONSTRAINT_LEVEL = NioProviderMetadata.CONSTRAINT_LEVEL; private final int bossId; private final int id; private final Executor executor; private boolean started; private volatile Thread thread; volatile Selector selector; private final AtomicBoolean wakenUp = new AtomicBoolean(); private final ReadWriteLock selectorGuard = new ReentrantReadWriteLock(); private final Object startStopLock = new Object(); private final Queue registerTaskQueue = new LinkedTransferQueue(); private final Queue writeTaskQueue = new LinkedTransferQueue(); NioWorker(int bossId, int id, Executor executor) { this.bossId = bossId; this.id = id; this.executor = executor; } void register(NioSocketChannel channel, ChannelFuture future) { boolean server = !(channel instanceof NioClientSocketChannel); Runnable registerTask = new RegisterTask(channel, future, server); Selector selector; synchronized (startStopLock) { if (!started) { // Open a selector if this worker didn't start yet. try { this.selector = selector = Selector.open(); } catch (Throwable t) { throw new ChannelException( "Failed to create a selector.", t); } // Start the worker thread with the new Selector. String threadName = (server ? "New I/O server worker #" : "New I/O client worker #") + bossId + '-' + id; boolean success = false; try { executor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable(this, threadName))); success = true; } finally { if (!success) { // Release the Selector if the execution fails. try { selector.close(); } catch (Throwable t) { logger.warn("Failed to close a selector.", t); } this.selector = selector = null; // The method will return to the caller at this point. } } } else { // Use the existing selector if this worker has been started. selector = this.selector; } assert selector != null && selector.isOpen(); started = true; boolean offered = registerTaskQueue.offer(registerTask); assert offered; } if (wakenUp.compareAndSet(false, true)) { selector.wakeup(); } } public void run() { thread = Thread.currentThread(); boolean shutdown = false; Selector selector = this.selector; for (;;) { wakenUp.set(false); if (CONSTRAINT_LEVEL != 0) { selectorGuard.writeLock().lock(); // This empty synchronization block prevents the selector // from acquiring its lock. selectorGuard.writeLock().unlock(); } try { int selectedKeyCount = selector.select(500); // 'wakenUp.compareAndSet(false, true)' is always evaluated // before calling 'selector.wakeup()' to reduce the wake-up // overhead. (Selector.wakeup() is an expensive operation.) // // However, there is a race condition in this approach. // The race condition is triggered when 'wakenUp' is set to // true too early. // // 'wakenUp' is set to true too early if: // 1) Selector is waken up between 'wakenUp.set(false)' and // 'selector.select(...)'. (BAD) // 2) Selector is waken up between 'selector.select(...)' and // 'if (wakenUp.get()) { ... }'. (OK) // // In the first case, 'wakenUp' is set to true and the // following 'selector.select(...)' will wake up immediately. // Until 'wakenUp' is set to false again in the next round, // 'wakenUp.compareAndSet(false, true)' will fail, and therefore // any attempt to wake up the Selector will fail, too, causing // the following 'selector.select(...)' call to block // unnecessarily. // // To fix this problem, we wake up the selector again if wakenUp // is true immediately after selector.select(...). // It is inefficient in that it wakes up the selector for both // the first case (BAD - wake-up required) and the second case // (OK - no wake-up required). if (wakenUp.get()) { selector.wakeup(); } processRegisterTaskQueue(); processWriteTaskQueue(); if (selectedKeyCount > 0) { processSelectedKeys(selector.selectedKeys()); } // Exit the loop when there's nothing to handle. // The shutdown flag is used to delay the shutdown of this // loop to avoid excessive Selector creation when // connections are registered in a one-by-one manner instead of // concurrent manner. if (selector.keys().isEmpty()) { if (shutdown || executor instanceof ExecutorService && ((ExecutorService) executor).isShutdown()) { synchronized (startStopLock) { if (registerTaskQueue.isEmpty() && selector.keys().isEmpty()) { started = false; try { selector.close(); } catch (IOException e) { logger.warn( "Failed to close a selector.", e); } finally { this.selector = null; } break; } else { shutdown = false; } } } else { // Give one more second. shutdown = true; } } else { shutdown = false; } } catch (Throwable t) { logger.warn( "Unexpected exception in the selector loop.", t); // Prevent possible consecutive immediate failures that lead to // excessive CPU consumption. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore. } } } } private void processRegisterTaskQueue() { for (;;) { final Runnable task = registerTaskQueue.poll(); if (task == null) { break; } task.run(); } } private void processWriteTaskQueue() { for (;;) { final Runnable task = writeTaskQueue.poll(); if (task == null) { break; } task.run(); } } private static void processSelectedKeys(Set selectedKeys) { for (Iterator i = selectedKeys.iterator(); i.hasNext();) { SelectionKey k = i.next(); i.remove(); try { int readyOps = k.readyOps(); if ((readyOps & SelectionKey.OP_READ) != 0) { if (!read(k)) { // Connection already closed - no need to handle write. continue; } } if ((readyOps & SelectionKey.OP_WRITE) != 0) { write(k); } } catch (CancelledKeyException e) { close(k); } } } private static boolean read(SelectionKey k) { ScatteringByteChannel ch = (ScatteringByteChannel) k.channel(); NioSocketChannel channel = (NioSocketChannel) k.attachment(); ReceiveBufferSizePredictor predictor = channel.getConfig().getReceiveBufferSizePredictor(); ChannelBufferFactory bufferFactory = channel.getConfig().getBufferFactory(); ChannelBuffer buffer = bufferFactory.getBuffer(predictor.nextReceiveBufferSize()); int ret = 0; int readBytes = 0; boolean failure = true; try { while ((ret = buffer.writeBytes(ch, buffer.writableBytes())) > 0) { readBytes += ret; if (!buffer.writable()) { break; } } failure = false; } catch (AsynchronousCloseException e) { // Can happen, and does not need a user attention. } catch (Throwable t) { fireExceptionCaught(channel, t); } if (readBytes > 0) { // Update the predictor. predictor.previousReceiveBufferSize(readBytes); // Fire the event. fireMessageReceived(channel, buffer); } if (ret < 0 || failure) { close(k); return false; } return true; } private static void write(SelectionKey k) { NioSocketChannel ch = (NioSocketChannel) k.attachment(); write(ch, false); } private static void close(SelectionKey k) { NioSocketChannel ch = (NioSocketChannel) k.attachment(); close(ch, succeededFuture(ch)); } static void write(final NioSocketChannel channel, boolean mightNeedWakeup) { if (!channel.isConnected()) { cleanUpWriteBuffer(channel); return; } if (mightNeedWakeup && scheduleWriteIfNecessary(channel)) { return; } if (channel.inWriteNowLoop) { scheduleWriteIfNecessary(channel); } else { writeNow(channel, channel.getConfig().getWriteSpinCount()); } } private static boolean scheduleWriteIfNecessary(NioSocketChannel channel) { NioWorker worker = channel.worker; Thread workerThread = worker.thread; if (workerThread == null || Thread.currentThread() != workerThread) { if (channel.writeTaskInTaskQueue.compareAndSet(false, true)) { boolean offered = worker.writeTaskQueue.offer(channel.writeTask); assert offered; } Selector workerSelector = worker.selector; if (workerSelector != null) { if (worker.wakenUp.compareAndSet(false, true)) { workerSelector.wakeup(); } } return true; } return false; } private static void writeNow(NioSocketChannel channel, int writeSpinCount) { boolean open = true; boolean addOpWrite = false; boolean removeOpWrite = false; MessageEvent evt; ChannelBuffer buf; int bufIdx; int writtenBytes = 0; Queue writeBuffer = channel.writeBuffer; synchronized (channel.writeLock) { channel.inWriteNowLoop = true; evt = channel.currentWriteEvent; for (;;) { if (evt == null) { evt = writeBuffer.poll(); if (evt == null) { channel.currentWriteEvent = null; removeOpWrite = true; break; } evt = consolidateComposite(evt); buf = (ChannelBuffer) evt.getMessage(); bufIdx = buf.readerIndex(); } else { buf = (ChannelBuffer) evt.getMessage(); bufIdx = channel.currentWriteIndex; } try { for (int i = writeSpinCount; i > 0; i --) { int localWrittenBytes = buf.getBytes( bufIdx, channel.socket, buf.writerIndex() - bufIdx); if (localWrittenBytes != 0) { bufIdx += localWrittenBytes; writtenBytes += localWrittenBytes; break; } } if (bufIdx == buf.writerIndex()) { // Successful write - proceed to the next message. channel.currentWriteEvent = null; evt.getFuture().setSuccess(); evt = null; } else { // Not written fully - perhaps the kernel buffer is full. channel.currentWriteEvent = evt; channel.currentWriteIndex = bufIdx; addOpWrite = true; break; } } catch (AsynchronousCloseException e) { // Doesn't need a user attention - ignore. } catch (Throwable t) { evt.getFuture().setFailure(t); evt = null; fireExceptionCaught(channel, t); if (t instanceof IOException) { open = false; close(channel, succeededFuture(channel)); } } } channel.inWriteNowLoop = false; } fireWriteComplete(channel, writtenBytes); if (open) { if (addOpWrite) { setOpWrite(channel); } else if (removeOpWrite) { clearOpWrite(channel); } } } static MessageEvent consolidateComposite(MessageEvent e) { // Convert a composite buffer into a simple buffer to save memory // bandwidth on full write buffer. // This method should be eliminated once gathering write works. Object m = e.getMessage(); if (m instanceof CompositeChannelBuffer) { e = new DownstreamMessageEvent( e.getChannel(), e.getFuture(), ((CompositeChannelBuffer) m).copy(), e.getRemoteAddress()); } return e; } private static void setOpWrite(NioSocketChannel channel) { NioWorker worker = channel.worker; Selector selector = worker.selector; SelectionKey key = channel.socket.keyFor(selector); if (key == null) { return; } if (!key.isValid()) { close(key); return; } int interestOps; boolean changed = false; // interestOps can change at any time and at any thread. // Acquire a lock to avoid possible race condition. synchronized (channel.interestOpsLock) { interestOps = channel.getRawInterestOps(); if ((interestOps & SelectionKey.OP_WRITE) == 0) { interestOps |= SelectionKey.OP_WRITE; key.interestOps(interestOps); changed = true; } } if (changed) { channel.setRawInterestOpsNow(interestOps); } } private static void clearOpWrite(NioSocketChannel channel) { NioWorker worker = channel.worker; Selector selector = worker.selector; SelectionKey key = channel.socket.keyFor(selector); if (key == null) { return; } if (!key.isValid()) { close(key); return; } int interestOps; boolean changed = false; // interestOps can change at any time and at any thread. // Acquire a lock to avoid possible race condition. synchronized (channel.interestOpsLock) { interestOps = channel.getRawInterestOps(); if ((interestOps & SelectionKey.OP_WRITE) != 0) { interestOps &= ~SelectionKey.OP_WRITE; key.interestOps(interestOps); changed = true; } } if (changed) { channel.setRawInterestOpsNow(interestOps); } } static void close(NioSocketChannel channel, ChannelFuture future) { NioWorker worker = channel.worker; Selector selector = worker.selector; SelectionKey key = channel.socket.keyFor(selector); if (key != null) { key.cancel(); } boolean connected = channel.isConnected(); boolean bound = channel.isBound(); try { channel.socket.close(); if (channel.setClosed()) { future.setSuccess(); if (connected) { fireChannelDisconnected(channel); } if (bound) { fireChannelUnbound(channel); } cleanUpWriteBuffer(channel); fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } private static void cleanUpWriteBuffer(NioSocketChannel channel) { Exception cause = null; // Clean up the stale messages in the write buffer. synchronized (channel.writeLock) { MessageEvent evt = channel.currentWriteEvent; if (evt != null) { channel.currentWriteEvent = null; channel.currentWriteIndex = 0; // Create the exception only once to avoid the excessive overhead // caused by fillStackTrace. if (channel.isOpen()) { cause = new NotYetConnectedException(); } else { cause = new ClosedChannelException(); } evt.getFuture().setFailure(cause); fireExceptionCaught(channel, cause); } Queue writeBuffer = channel.writeBuffer; if (!writeBuffer.isEmpty()) { // Create the exception only once to avoid the excessive overhead // caused by fillStackTrace. if (cause == null) { if (channel.isOpen()) { cause = new NotYetConnectedException(); } else { cause = new ClosedChannelException(); } } for (;;) { evt = writeBuffer.poll(); if (evt == null) { break; } evt.getFuture().setFailure(cause); fireExceptionCaught(channel, cause); } } } } static void setInterestOps( NioSocketChannel channel, ChannelFuture future, int interestOps) { boolean changed = false; try { // interestOps can change at any time and at any thread. // Acquire a lock to avoid possible race condition. synchronized (channel.interestOpsLock) { NioWorker worker = channel.worker; Selector selector = worker.selector; SelectionKey key = channel.socket.keyFor(selector); if (key == null || selector == null) { // Not registered to the worker yet. // Set the rawInterestOps immediately; RegisterTask will pick it up. channel.setRawInterestOpsNow(interestOps); return; } // Override OP_WRITE flag - a user cannot change this flag. interestOps &= ~Channel.OP_WRITE; interestOps |= channel.getRawInterestOps() & Channel.OP_WRITE; switch (CONSTRAINT_LEVEL) { case 0: if (channel.getRawInterestOps() != interestOps) { key.interestOps(interestOps); if (Thread.currentThread() != worker.thread && worker.wakenUp.compareAndSet(false, true)) { selector.wakeup(); } changed = true; } break; case 1: case 2: if (channel.getRawInterestOps() != interestOps) { if (Thread.currentThread() == worker.thread) { key.interestOps(interestOps); changed = true; } else { worker.selectorGuard.readLock().lock(); try { if (worker.wakenUp.compareAndSet(false, true)) { selector.wakeup(); } key.interestOps(interestOps); changed = true; } finally { worker.selectorGuard.readLock().unlock(); } } } break; default: throw new Error(); } } future.setSuccess(); if (changed) { channel.setRawInterestOpsNow(interestOps); fireChannelInterestChanged(channel); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } private final class RegisterTask implements Runnable { private final NioSocketChannel channel; private final ChannelFuture future; private final boolean server; RegisterTask( NioSocketChannel channel, ChannelFuture future, boolean server) { this.channel = channel; this.future = future; this.server = server; } public void run() { SocketAddress localAddress = channel.getLocalAddress(); SocketAddress remoteAddress = channel.getRemoteAddress(); if (localAddress == null || remoteAddress == null) { if (future != null) { future.setFailure(new ClosedChannelException()); } close(channel, succeededFuture(channel)); return; } try { synchronized (channel.interestOpsLock) { channel.socket.register( selector, channel.getRawInterestOps(), channel); } if (future != null) { future.setSuccess(); } } catch (ClosedChannelException e) { if (future != null) { future.setFailure(e); } close(channel, succeededFuture(channel)); throw new ChannelException( "Failed to register a socket to the selector.", e); } if (!server) { if (!((NioClientSocketChannel) channel).boundManually) { fireChannelBound(channel, localAddress); } fireChannelConnected(channel, remoteAddress); } } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramWorker.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramWorker.java0000644000175000017500000007554011216366721032521 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.CancelledKeyException; import java.nio.channels.ClosedChannelException; import java.nio.channels.DatagramChannel; import java.nio.channels.NotYetConnectedException; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.util.Iterator; import java.util.Queue; import java.util.Set; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.LinkedTransferQueue; /** * A class responsible for registering channels with {@link Selector}. * It also implements the {@link Selector} loop. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author Daniel Bevenius (dbevenius@jboss.com) * * @version $Rev: 1411 $, $Date: 2009-06-18 00:33:37 -0700 (Thu, 18 Jun 2009) $ */ class NioDatagramWorker implements Runnable { /** * Internal Netty logger. */ private static final InternalLogger logger = InternalLoggerFactory .getInstance(NioDatagramWorker.class); /** * This id of this worker. */ private final int id; /** * This id of the NioDatagramPipelineSink. */ private final int bossId; /** * Executor used to execute {@link Runnable}s such as * {@link ChannelRegistionTask}. */ private final Executor executor; /** * Boolean to indicate if this worker has been started. */ private boolean started; /** * If this worker has been started thread will be a reference to the thread * used when starting. i.e. the current thread when the run method is executed. */ private volatile Thread thread; /** * The NIO {@link Selector}. */ volatile Selector selector; /** * Boolean that controls determines if a blocked Selector.select should * break out of its selection process. In our case we use a timeone for * the select method and the select method will block for that time unless * waken up. */ private final AtomicBoolean wakenUp = new AtomicBoolean(); /** * Lock for this workers Selector. */ private final ReadWriteLock selectorGuard = new ReentrantReadWriteLock(); /** * Monitor object used to synchronize selector open/close. */ private final Object startStopLock = new Object(); /** * Queue of {@link ChannelRegistionTask}s */ private final Queue registerTaskQueue = new LinkedTransferQueue(); /** * Queue of WriteTasks */ private final Queue writeTaskQueue = new LinkedTransferQueue(); /** * Sole constructor. * * @param bossId This id of the NioDatagramPipelineSink * @param id The id of this worker * @param executor the {@link Executor} used to execute {@link Runnable}s * such as {@link ChannelRegistionTask} */ NioDatagramWorker(final int bossId, final int id, final Executor executor) { this.bossId = bossId; this.id = id; this.executor = executor; } /** * Registers the passed-in channel with a selector. * * @param channel The channel to register. * @param future */ void register(final NioDatagramChannel channel, final ChannelFuture future) { final Runnable channelRegTask = new ChannelRegistionTask(channel, future); Selector selector; synchronized (startStopLock) { if (!started) { // Open a selector if this worker didn't start yet. try { this.selector = selector = Selector.open(); } catch (final Throwable t) { throw new ChannelException("Failed to create a selector.", t); } boolean success = false; try { // Start the main selector loop. See run() for details. executor.execute(new ThreadRenamingRunnable(this, "New I/O server worker #" + bossId + "'-'" + id)); success = true; } finally { if (!success) { try { // Release the Selector if the execution fails. selector.close(); } catch (final Throwable t) { logger.warn("Failed to close a selector.", t); } this.selector = selector = null; // The method will return to the caller at this point. } } } else { // Use the existing selector if this worker has been started. selector = this.selector; } assert selector != null && selector.isOpen(); started = true; // "Add" the registration task to the register task queue. boolean offered = registerTaskQueue.offer(channelRegTask); assert offered; } if (wakenUp.compareAndSet(false, true)) { selector.wakeup(); } } /** * Selector loop. */ public void run() { // Store a ref to the current thread. thread = Thread.currentThread(); final Selector selector = this.selector; boolean shutdown = false; for (;;) { wakenUp.set(false); if (NioProviderMetadata.CONSTRAINT_LEVEL != 0) { selectorGuard.writeLock().lock(); // This empty synchronization block prevents the selector from acquiring its lock. selectorGuard.writeLock().unlock(); } try { int selectedKeyCount = selector.select(500); // 'wakenUp.compareAndSet(false, true)' is always evaluated // before calling 'selector.wakeup()' to reduce the wake-up // overhead. (Selector.wakeup() is an expensive operation.) // // However, there is a race condition in this approach. // The race condition is triggered when 'wakenUp' is set to // true too early. // // 'wakenUp' is set to true too early if: // 1) Selector is waken up between 'wakenUp.set(false)' and // 'selector.select(...)'. (BAD) // 2) Selector is waken up between 'selector.select(...)' and // 'if (wakenUp.get()) { ... }'. (OK) // // In the first case, 'wakenUp' is set to true and the // following 'selector.select(...)' will wake up immediately. // Until 'wakenUp' is set to false again in the next round, // 'wakenUp.compareAndSet(false, true)' will fail, and therefore // any attempt to wake up the Selector will fail, too, causing // the following 'selector.select(...)' call to block // unnecessarily. // // To fix this problem, we wake up the selector again if wakenUp // is true immediately after selector.select(...). // It is inefficient in that it wakes up the selector for both // the first case (BAD - wake-up required) and the second case // (OK - no wake-up required). if (wakenUp.get()) { selector.wakeup(); } processRegisterTaskQueue(); processWriteTaskQueue(); if (selectedKeyCount > 0) { processSelectedKeys(selector.selectedKeys()); } // Exit the loop when there's nothing to handle (the registered // key set is empty. // The shutdown flag is used to delay the shutdown of this // loop to avoid excessive Selector creation when // connections are registered in a one-by-one manner instead of // concurrent manner. if (selector.keys().isEmpty()) { if (shutdown || executor instanceof ExecutorService && ((ExecutorService) executor).isShutdown()) { synchronized (startStopLock) { if (registerTaskQueue.isEmpty() && selector.keys().isEmpty()) { started = false; try { selector.close(); } catch (IOException e) { logger.warn("Failed to close a selector.", e); } finally { this.selector = null; } break; } else { shutdown = false; } } } else { // Give one more second. shutdown = true; } } else { shutdown = false; } } catch (Throwable t) { logger.warn("Unexpected exception in the selector loop.", t); // Prevent possible consecutive immediate failures that lead to // excessive CPU consumption. try { Thread.sleep(1000); } catch (InterruptedException e) { // Ignore. } } } } /** * Will go through all the {@link ChannelRegistionTask}s in the * task queue and run them (registering them). */ private void processRegisterTaskQueue() { for (;;) { final Runnable task = registerTaskQueue.poll(); if (task == null) { break; } task.run(); } } /** * Will go through all the WriteTasks and run them. */ private void processWriteTaskQueue() { for (;;) { final Runnable task = writeTaskQueue.poll(); if (task == null) { break; } task.run(); } } private static void processSelectedKeys(final Set selectedKeys) { for (Iterator i = selectedKeys.iterator(); i.hasNext();) { SelectionKey k = i.next(); i.remove(); try { int readyOps = k.readyOps(); if ((readyOps & SelectionKey.OP_READ) != 0) { if (!read(k)) { // Connection already closed - no need to handle write. continue; } } if ((readyOps & SelectionKey.OP_WRITE) != 0) { write(k); } } catch (CancelledKeyException e) { close(k); } } } private static void write(SelectionKey k) { write((NioDatagramChannel) k.attachment(), false); } /** * Read is called when a Selector has been notified that the underlying channel * was something to be read. The channel would previously have registered its interest * in read operations. * * @param key The selection key which contains the Selector registration information. */ private static boolean read(final SelectionKey key) { final NioDatagramChannel channel = (NioDatagramChannel) key.attachment(); ReceiveBufferSizePredictor predictor = channel.getConfig().getReceiveBufferSizePredictor(); final ChannelBufferFactory bufferFactory = channel.getConfig().getBufferFactory(); final DatagramChannel nioChannel = (DatagramChannel) key.channel(); // Allocating a non-direct buffer with a max udp packge size. // Would using a direct buffer be more efficient or would this negatively // effect performance, as direct buffer allocation has a higher upfront cost // where as a ByteBuffer is heap allocated. final ByteBuffer byteBuffer = ByteBuffer.allocate( predictor.nextReceiveBufferSize()).order(bufferFactory.getDefaultOrder()); boolean failure = true; SocketAddress remoteAddress = null; try { // Receive from the channel in a non blocking mode. We have already been notified that // the channel is ready to receive. remoteAddress = nioChannel.receive(byteBuffer); failure = false; } catch (AsynchronousCloseException e) { // Can happen, and does not need a user attention. } catch (Throwable t) { fireExceptionCaught(channel, t); } if (remoteAddress != null) { // Flip the buffer so that we can wrap it. byteBuffer.flip(); int readBytes = byteBuffer.remaining(); if (readBytes > 0) { // Update the predictor. predictor.previousReceiveBufferSize(readBytes); // Create a Netty ChannelByffer by wrapping the ByteBuffer. final ChannelBuffer channelBuffer = ChannelBuffers .wrappedBuffer(byteBuffer); // Notify the interested parties about the newly arrived message (channelBuffer). fireMessageReceived(channel, channelBuffer, remoteAddress); } } if (failure) { close(key); return false; } return true; } private static void close(SelectionKey k) { final NioDatagramChannel ch = (NioDatagramChannel) k.attachment(); close(ch, succeededFuture(ch)); } static void write(final NioDatagramChannel channel, final boolean mightNeedWakeup) { /* * Note that we are not checking if the channel is connected. Connected has a different * meaning in UDP and means that the channels socket is configured to only send and * receive from a given remote peer. */ if (!channel.isOpen()) { cleanUpWriteBuffer(channel); return; } if (mightNeedWakeup && scheduleWriteIfNecessary(channel)) { return; } if (channel.inWriteNowLoop) { scheduleWriteIfNecessary(channel); } else { writeNow(channel, channel.getConfig().getWriteSpinCount()); } } private static boolean scheduleWriteIfNecessary( final NioDatagramChannel channel) { final NioDatagramWorker worker = channel.worker; final Thread workerThread = worker.thread; if (workerThread == null || Thread.currentThread() != workerThread) { if (channel.writeTaskInTaskQueue.compareAndSet(false, true)) { // "add" the channels writeTask to the writeTaskQueue. boolean offered = worker.writeTaskQueue .offer(channel.writeTask); assert offered; } final Selector workerSelector = worker.selector; if (workerSelector != null) { if (worker.wakenUp.compareAndSet(false, true)) { workerSelector.wakeup(); } } return true; } return false; } private static void writeNow(final NioDatagramChannel channel, final int writeSpinCount) { boolean open = true; boolean addOpWrite = false; boolean removeOpWrite = false; MessageEvent evt; ChannelBuffer buf; int writtenBytes = 0; Queue writeBuffer = channel.writeBufferQueue; synchronized (channel.writeLock) { // inform the channel that write is in-progress channel.inWriteNowLoop = true; // get the write event. evt = channel.currentWriteEvent; // loop forever... for (;;) { if (evt == null) { evt = writeBuffer.poll(); if (evt == null) { channel.currentWriteEvent = null; removeOpWrite = true; break; } evt = NioWorker.consolidateComposite(evt); buf = (ChannelBuffer) evt.getMessage(); } else { buf = (ChannelBuffer) evt.getMessage(); } try { int localWrittenBytes = 0; for (int i = writeSpinCount; i > 0; i --) { if (evt.getRemoteAddress() == null) { localWrittenBytes = buf.getBytes( buf.readerIndex(), channel.getDatagramChannel(), buf.readableBytes()); } else { localWrittenBytes = channel.getDatagramChannel().send( buf.toByteBuffer(), evt.getRemoteAddress()); } if (localWrittenBytes != 0) { writtenBytes += localWrittenBytes; break; } } if (localWrittenBytes > 0) { // Successful write - proceed to the next message. evt.getFuture().setSuccess(); evt = null; } else { // Not written at all - perhaps the kernel buffer is full. channel.currentWriteEvent = evt; addOpWrite = true; break; } } catch (final AsynchronousCloseException e) { // Doesn't need a user attention - ignore. } catch (final Throwable t) { evt.getFuture().setFailure(t); evt = null; fireExceptionCaught(channel, t); if (t instanceof IOException) { open = false; close(channel, succeededFuture(channel)); } } } channel.inWriteNowLoop = false; } fireWriteComplete(channel, writtenBytes); if (open) { if (addOpWrite) { setOpWrite(channel); } else if (removeOpWrite) { clearOpWrite(channel); } } } private static void setOpWrite(final NioDatagramChannel channel) { NioDatagramWorker worker = channel.worker; Selector selector = worker.selector; SelectionKey key = channel.getDatagramChannel().keyFor(selector); if (key == null) { return; } if (!key.isValid()) { close(key); return; } int interestOps; boolean changed = false; // interestOps can change at any time and at any thread. // Acquire a lock to avoid possible race condition. synchronized (channel.interestOpsLock) { interestOps = channel.getRawInterestOps(); if ((interestOps & SelectionKey.OP_WRITE) == 0) { interestOps |= SelectionKey.OP_WRITE; key.interestOps(interestOps); changed = true; } } if (changed) { channel.setRawInterestOpsNow(interestOps); } } private static void clearOpWrite(NioDatagramChannel channel) { NioDatagramWorker worker = channel.worker; Selector selector = worker.selector; SelectionKey key = channel.getDatagramChannel().keyFor(selector); if (key == null) { return; } if (!key.isValid()) { close(key); return; } int interestOps; boolean changed = false; // interestOps can change at any time and at any thread. // Acquire a lock to avoid possible race condition. synchronized (channel.interestOpsLock) { interestOps = channel.getRawInterestOps(); if ((interestOps & SelectionKey.OP_WRITE) != 0) { interestOps &= ~SelectionKey.OP_WRITE; key.interestOps(interestOps); changed = true; } } if (changed) { channel.setRawInterestOpsNow(interestOps); } } static void disconnect(NioDatagramChannel channel, ChannelFuture future) { boolean connected = channel.isConnected(); try { channel.getDatagramChannel().disconnect(); future.setSuccess(); if (connected) { fireChannelDisconnected(channel); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } static void close(final NioDatagramChannel channel, final ChannelFuture future) { NioDatagramWorker worker = channel.worker; Selector selector = worker.selector; SelectionKey key = channel.getDatagramChannel().keyFor(selector); if (key != null) { key.cancel(); } boolean connected = channel.isConnected(); boolean bound = channel.isBound(); try { channel.getDatagramChannel().close(); if (channel.setClosed()) { future.setSuccess(); if (connected) { fireChannelDisconnected(channel); } if (bound) { fireChannelUnbound(channel); } cleanUpWriteBuffer(channel); fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } private static void cleanUpWriteBuffer(final NioDatagramChannel channel) { Exception cause = null; // Clean up the stale messages in the write buffer. synchronized (channel.writeLock) { MessageEvent evt = channel.currentWriteEvent; if (evt != null) { channel.currentWriteEvent = null; // Create the exception only once to avoid the excessive overhead // caused by fillStackTrace. if (channel.isOpen()) { cause = new NotYetConnectedException(); } else { cause = new ClosedChannelException(); } evt.getFuture().setFailure(cause); fireExceptionCaught(channel, cause); } Queue writeBuffer = channel.writeBufferQueue; if (!writeBuffer.isEmpty()) { // Create the exception only once to avoid the excessive overhead // caused by fillStackTrace. if (cause == null) { if (channel.isOpen()) { cause = new NotYetConnectedException(); } else { cause = new ClosedChannelException(); } } for (;;) { evt = writeBuffer.poll(); if (evt == null) { break; } evt.getFuture().setFailure(cause); fireExceptionCaught(channel, cause); } } } } static void setInterestOps(final NioDatagramChannel channel, ChannelFuture future, int interestOps) { boolean changed = false; try { // interestOps can change at any time and by any thread. // Acquire a lock to avoid possible race condition. synchronized (channel.interestOpsLock) { final NioDatagramWorker worker = channel.worker; final Selector selector = worker.selector; final SelectionKey key = channel.getDatagramChannel().keyFor(selector); if (key == null || selector == null) { // Not registered to the worker yet. // Set the rawInterestOps immediately; RegisterTask will pick it up. channel.setRawInterestOpsNow(interestOps); return; } // Override OP_WRITE flag - a user cannot change this flag. interestOps &= ~Channel.OP_WRITE; interestOps |= channel.getRawInterestOps() & Channel.OP_WRITE; switch (NioProviderMetadata.CONSTRAINT_LEVEL) { case 0: if (channel.getRawInterestOps() != interestOps) { // Set the interesteOps on the SelectionKey key.interestOps(interestOps); // If the worker thread (the one that that might possibly be blocked // in a select() call) is not the thread executing this method wakeup // the select() operation. if (Thread.currentThread() != worker.thread && worker.wakenUp.compareAndSet(false, true)) { selector.wakeup(); } changed = true; } break; case 1: case 2: if (channel.getRawInterestOps() != interestOps) { if (Thread.currentThread() == worker.thread) { // Going to set the interestOps from the same thread. // Set the interesteOps on the SelectionKey key.interestOps(interestOps); changed = true; } else { // Going to set the interestOps from a different thread // and some old provides will need synchronization. worker.selectorGuard.readLock().lock(); try { if (worker.wakenUp.compareAndSet(false, true)) { selector.wakeup(); } key.interestOps(interestOps); changed = true; } finally { worker.selectorGuard.readLock().unlock(); } } } break; default: throw new Error(); } } future.setSuccess(); if (changed) { channel.setRawInterestOpsNow(interestOps); fireChannelInterestChanged(channel); } } catch (final Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } /** * RegisterTask is a task responsible for registering a channel with a * selector. */ private final class ChannelRegistionTask implements Runnable { private final NioDatagramChannel channel; private final ChannelFuture future; ChannelRegistionTask(final NioDatagramChannel channel, final ChannelFuture future) { this.channel = channel; this.future = future; } /** * This runnable's task. Does the actual registering by calling the * underlying DatagramChannels peer DatagramSocket register method. * */ public void run() { final SocketAddress localAddress = channel.getLocalAddress(); if (localAddress == null) { if (future != null) { future.setFailure(new ClosedChannelException()); } close(channel, succeededFuture(channel)); return; } try { synchronized (channel.interestOpsLock) { channel.getDatagramChannel().register( selector, channel.getRawInterestOps(), channel); } if (future != null) { future.setSuccess(); } } catch (final ClosedChannelException e) { if (future != null) { future.setFailure(e); } close(channel, succeededFuture(channel)); throw new ChannelException( "Failed to register a socket to the selector.", e); } } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/nio/NioDatagramChannel.jav0000644000175000017500000002530211216366721032446 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.nio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.NetworkInterface; import java.net.SocketAddress; import java.nio.channels.DatagramChannel; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.socket.DatagramChannelConfig; import org.jboss.netty.util.internal.LinkedTransferQueue; import org.jboss.netty.util.internal.ThreadLocalBoolean; /** * Provides an NIO based {@link org.jboss.netty.channel.socket.DatagramChannel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author Daniel Bevenius (dbevenius@jboss.com) * * @version $Rev: 1411 $, $Date: 2009-06-18 00:33:37 -0700 (Thu, 18 Jun 2009) $ */ class NioDatagramChannel extends AbstractChannel implements org.jboss.netty.channel.socket.DatagramChannel { /** * The {@link DatagramChannelConfig}. */ private final NioDatagramChannelConfig config; /** * The {@link NioDatagramWorker} for this NioDatagramChannnel. */ final NioDatagramWorker worker; /** * The {@link DatagramChannel} that this channel uses. */ private final java.nio.channels.DatagramChannel datagramChannel; /** * Monitor object to synchronize access to InterestedOps. */ final Object interestOpsLock = new Object(); /** * Monitor object for synchronizing access to the {@link WriteBufferQueue}. */ final Object writeLock = new Object(); /** * WriteTask that performs write operations. */ final Runnable writeTask = new WriteTask(); /** * Indicates if there is a {@link WriteTask} in the task queue. */ final AtomicBoolean writeTaskInTaskQueue = new AtomicBoolean(); /** * Queue of write {@link MessageEvent}s. */ final Queue writeBufferQueue = new WriteBufferQueue(); /** * Keeps track of the number of bytes that the {@link WriteBufferQueue} currently * contains. */ final AtomicInteger writeBufferSize = new AtomicInteger(); /** * Keeps track of the highWaterMark. */ final AtomicInteger highWaterMarkCounter = new AtomicInteger(); /** * The current write {@link MessageEvent} */ MessageEvent currentWriteEvent; /** * Boolean that indicates that write operation is in progress. */ volatile boolean inWriteNowLoop; NioDatagramChannel(final ChannelFactory factory, final ChannelPipeline pipeline, final ChannelSink sink, final NioDatagramWorker worker) { super(null, factory, pipeline, sink); this.worker = worker; datagramChannel = openNonBlockingChannel(); config = new DefaultNioDatagramChannelConfig(datagramChannel.socket()); fireChannelOpen(this); } private DatagramChannel openNonBlockingChannel() { try { final DatagramChannel channel = DatagramChannel.open(); channel.configureBlocking(false); return channel; } catch (final IOException e) { throw new ChannelException("Failed to open a DatagramChannel.", e); } } public InetSocketAddress getLocalAddress() { try { return (InetSocketAddress) datagramChannel.socket().getLocalSocketAddress(); } catch (Throwable t) { // Sometimes fails on a closed socket in Windows. return null; } } public InetSocketAddress getRemoteAddress() { try { return (InetSocketAddress) datagramChannel.socket().getRemoteSocketAddress(); } catch (Throwable t) { // Sometimes fails on a closed socket in Windows. return null; } } public boolean isBound() { return isOpen() && datagramChannel.socket().isBound(); } public boolean isConnected() { return datagramChannel.socket().isConnected(); } @Override protected boolean setClosed() { return super.setClosed(); } public NioDatagramChannelConfig getConfig() { return config; } DatagramChannel getDatagramChannel() { return datagramChannel; } @Override public int getInterestOps() { if (!isOpen()) { return Channel.OP_WRITE; } int interestOps = getRawInterestOps(); int writeBufferSize = this.writeBufferSize.get(); if (writeBufferSize != 0) { if (highWaterMarkCounter.get() > 0) { int lowWaterMark = getConfig().getWriteBufferLowWaterMark(); if (writeBufferSize >= lowWaterMark) { interestOps |= Channel.OP_WRITE; } else { interestOps &= ~Channel.OP_WRITE; } } else { int highWaterMark = getConfig().getWriteBufferHighWaterMark(); if (writeBufferSize >= highWaterMark) { interestOps |= Channel.OP_WRITE; } else { interestOps &= ~Channel.OP_WRITE; } } } else { interestOps &= ~Channel.OP_WRITE; } return interestOps; } int getRawInterestOps() { return super.getInterestOps(); } void setRawInterestOpsNow(int interestOps) { super.setInterestOpsNow(interestOps); } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) { return super.write(message, null); } else { return super.write(message, remoteAddress); } } /** * WriteBuffer is an extension of {@link LinkedTransferQueue} that adds * support for highWaterMark checking of the write buffer size. */ private final class WriteBufferQueue extends LinkedTransferQueue { private final ThreadLocalBoolean notifying = new ThreadLocalBoolean(); WriteBufferQueue() { super(); } /** * This method first delegates to {@link LinkedTransferQueue#offer(Object)} and * adds support for keeping track of the size of the this write buffer. */ @Override public boolean offer(MessageEvent e) { boolean success = super.offer(e); assert success; int messageSize = ((ChannelBuffer) e.getMessage()).readableBytes(); int newWriteBufferSize = writeBufferSize.addAndGet(messageSize); int highWaterMark = getConfig().getWriteBufferHighWaterMark(); if (newWriteBufferSize >= highWaterMark) { if (newWriteBufferSize - messageSize < highWaterMark) { highWaterMarkCounter.incrementAndGet(); if (!notifying.get()) { notifying.set(Boolean.TRUE); fireChannelInterestChanged(NioDatagramChannel.this); notifying.set(Boolean.FALSE); } } } return true; } /** * This method first delegates to {@link LinkedTransferQueue#poll()} and * adds support for keeping track of the size of the this writebuffers queue. */ @Override public MessageEvent poll() { MessageEvent e = super.poll(); if (e != null) { int messageSize = ((ChannelBuffer) e.getMessage()).readableBytes(); int newWriteBufferSize = writeBufferSize.addAndGet(-messageSize); int lowWaterMark = getConfig().getWriteBufferLowWaterMark(); if (newWriteBufferSize == 0 || newWriteBufferSize < lowWaterMark) { if (newWriteBufferSize + messageSize >= lowWaterMark) { highWaterMarkCounter.decrementAndGet(); if (!notifying.get()) { notifying.set(Boolean.TRUE); fireChannelInterestChanged(NioDatagramChannel.this); notifying.set(Boolean.FALSE); } } } } return e; } } /** * WriteTask is a simple runnable performs writes by delegating the {@link NioDatagramWorker}. * */ private final class WriteTask implements Runnable { WriteTask() { super(); } public void run() { writeTaskInTaskQueue.set(false); NioDatagramWorker.write(NioDatagramChannel.this, false); } } public void joinGroup(InetAddress multicastAddress) { throw new UnsupportedOperationException(); } public void joinGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface) { throw new UnsupportedOperationException(); } public void leaveGroup(InetAddress multicastAddress) { throw new UnsupportedOperationException(); } public void leaveGroup(InetSocketAddress multicastAddress, NetworkInterface networkInterface) { throw new UnsupportedOperationException(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/0000755000175000017500000000000011316313136026255 5ustar deckerdecker././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioAcceptedSocketChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioAcceptedSocketChann0000644000175000017500000000526111057417007032510 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.io.OutputStream; import java.io.PushbackInputStream; import java.net.Socket; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 213 $, $Date: 2008-09-02 22:17:59 -0700 (Tue, 02 Sep 2008) $ * */ class OioAcceptedSocketChannel extends OioSocketChannel { private final PushbackInputStream in; private final OutputStream out; OioAcceptedSocketChannel( Channel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, Socket socket) { super(parent, factory, pipeline, sink, socket); try { in = new PushbackInputStream(socket.getInputStream(), 1); } catch (IOException e) { throw new ChannelException("Failed to obtain an InputStream.", e); } try { out = socket.getOutputStream(); } catch (IOException e) { throw new ChannelException("Failed to obtain an OutputStream.", e); } fireChannelOpen(this); fireChannelBound(this, getLocalAddress()); fireChannelConnected(this, getRemoteAddress()); } @Override PushbackInputStream getInputStream() { return in; } @Override OutputStream getOutputStream() { return out; } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramPipelineSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramPipelineSin0000644000175000017500000001503611213672505032540 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.net.SocketAddress; import java.util.concurrent.Executor; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.IoWorkerRunnable; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ class OioDatagramPipelineSink extends AbstractChannelSink { private final Executor workerExecutor; OioDatagramPipelineSink(Executor workerExecutor) { this.workerExecutor = workerExecutor; } public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { OioDatagramChannel channel = (OioDatagramChannel) e.getChannel(); ChannelFuture future = e.getFuture(); if (e instanceof ChannelStateEvent) { ChannelStateEvent stateEvent = (ChannelStateEvent) e; ChannelState state = stateEvent.getState(); Object value = stateEvent.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { OioDatagramWorker.close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (SocketAddress) value); } else { OioDatagramWorker.close(channel, future); } break; case CONNECTED: if (value != null) { connect(channel, future, (SocketAddress) value); } else { OioDatagramWorker.disconnect(channel, future); } break; case INTEREST_OPS: OioDatagramWorker.setInterestOps(channel, future, ((Integer) value).intValue()); break; } } else if (e instanceof MessageEvent) { MessageEvent evt = (MessageEvent) e; OioDatagramWorker.write( channel, future, evt.getMessage(), evt.getRemoteAddress()); } } private void bind( OioDatagramChannel channel, ChannelFuture future, SocketAddress localAddress) { boolean bound = false; boolean workerStarted = false; try { channel.socket.bind(localAddress); bound = true; // Fire events future.setSuccess(); fireChannelBound(channel, channel.getLocalAddress()); // Start the business. workerExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( new OioDatagramWorker(channel), "Old I/O datagram worker (channelId: " + channel.getId() + ", " + channel.getLocalAddress() + ')'))); workerStarted = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (bound && !workerStarted) { OioDatagramWorker.close(channel, future); } } } private void connect( OioDatagramChannel channel, ChannelFuture future, SocketAddress remoteAddress) { boolean bound = channel.isBound(); boolean connected = false; boolean workerStarted = false; future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); try { channel.socket.connect(remoteAddress); connected = true; // Fire events. future.setSuccess(); if (!bound) { fireChannelBound(channel, channel.getLocalAddress()); } fireChannelConnected(channel, channel.getRemoteAddress()); String threadName = "Old I/O datagram worker (channelId: " + channel.getId() + ", " + channel.getLocalAddress() + " => " + channel.getRemoteAddress() + ')'; if (!bound) { // Start the business. workerExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( new OioDatagramWorker(channel), threadName))); } else { // Worker started by bind() - just rename. Thread workerThread = channel.workerThread; if (workerThread != null) { try { workerThread.setName(threadName); } catch (SecurityException e) { // Ignore. } } } workerStarted = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (connected && !workerStarted) { OioDatagramWorker.close(channel, future); } } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioClientSocketChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioClientSocketChannel0000644000175000017500000000401211057417007032530 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.OutputStream; import java.io.PushbackInputStream; import java.net.Socket; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 213 $, $Date: 2008-09-02 22:17:59 -0700 (Tue, 02 Sep 2008) $ * */ class OioClientSocketChannel extends OioSocketChannel { volatile PushbackInputStream in; volatile OutputStream out; OioClientSocketChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { super(null, factory, pipeline, sink, new Socket()); fireChannelOpen(this); } @Override PushbackInputStream getInputStream() { return in; } @Override OutputStream getOutputStream() { return out; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramWorker.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramWorker.java0000644000175000017500000002070011214334272032501 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.InterruptedIOException; import java.net.DatagramPacket; import java.net.MulticastSocket; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.ByteOrder; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ReceiveBufferSizePredictor; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1355 $, $Date: 2009-06-11 19:08:58 -0700 (Thu, 11 Jun 2009) $ * */ class OioDatagramWorker implements Runnable { private final OioDatagramChannel channel; OioDatagramWorker(OioDatagramChannel channel) { this.channel = channel; } public void run() { channel.workerThread = Thread.currentThread(); final MulticastSocket socket = channel.socket; while (channel.isOpen()) { synchronized (channel.interestOpsLock) { while (!channel.isReadable()) { try { // notify() is not called at all. // close() and setInterestOps() calls Thread.interrupt() channel.interestOpsLock.wait(); } catch (InterruptedException e) { if (!channel.isOpen()) { break; } } } } ReceiveBufferSizePredictor predictor = channel.getConfig().getReceiveBufferSizePredictor(); byte[] buf = new byte[predictor.nextReceiveBufferSize()]; DatagramPacket packet = new DatagramPacket(buf, buf.length); try { socket.receive(packet); } catch (InterruptedIOException e) { // Can happen on interruption. // Keep receiving unless the channel is closed. continue; } catch (Throwable t) { if (!channel.socket.isClosed()) { fireExceptionCaught(channel, t); } break; } ChannelBuffer buffer; ByteOrder endianness = channel.getConfig().getBufferFactory().getDefaultOrder(); int readBytes = packet.getLength(); if (readBytes == buf.length) { buffer = ChannelBuffers.wrappedBuffer(endianness, buf); } else { buffer = ChannelBuffers.wrappedBuffer(endianness, buf, 0, readBytes); } fireMessageReceived(channel, buffer, packet.getSocketAddress()); } // Setting the workerThread to null will prevent any channel // operations from interrupting this thread from now on. channel.workerThread = null; // Clean up. close(channel, succeededFuture(channel)); } static void write( OioDatagramChannel channel, ChannelFuture future, Object message, SocketAddress remoteAddress) { try { ChannelBuffer buf = (ChannelBuffer) message; int length = buf.readableBytes(); ByteBuffer nioBuf = buf.toByteBuffer(); DatagramPacket packet; if (nioBuf.hasArray()) { // Avoid copy if the buffer is backed by an array. packet = new DatagramPacket( nioBuf.array(), nioBuf.arrayOffset(), length); } else { // Otherwise it will be expensive. byte[] arrayBuf = new byte[length]; buf.getBytes(0, arrayBuf); packet = new DatagramPacket(arrayBuf, length); } if (remoteAddress != null) { packet.setSocketAddress(remoteAddress); } channel.socket.send(packet); fireWriteComplete(channel, length); future.setSuccess(); } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } static void setInterestOps( OioDatagramChannel channel, ChannelFuture future, int interestOps) { // Override OP_WRITE flag - a user cannot change this flag. interestOps &= ~Channel.OP_WRITE; interestOps |= channel.getInterestOps() & Channel.OP_WRITE; boolean changed = false; try { if (channel.getInterestOps() != interestOps) { if ((interestOps & Channel.OP_READ) != 0) { channel.setInterestOpsNow(Channel.OP_READ); } else { channel.setInterestOpsNow(Channel.OP_NONE); } changed = true; } future.setSuccess(); if (changed) { synchronized (channel.interestOpsLock) { channel.setInterestOpsNow(interestOps); // Notify the worker so it stops or continues reading. Thread currentThread = Thread.currentThread(); Thread workerThread = channel.workerThread; if (workerThread != null && currentThread != workerThread) { workerThread.interrupt(); } } fireChannelInterestChanged(channel); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } static void disconnect(OioDatagramChannel channel, ChannelFuture future) { boolean connected = channel.isConnected(); try { channel.socket.disconnect(); future.setSuccess(); if (connected) { fireChannelDisconnected(channel); } Thread workerThread = channel.workerThread; if (workerThread != null) { try { workerThread.setName( "Old I/O datagram worker (channelId: " + channel.getId() + ", " + channel.getLocalAddress() + ')'); } catch (SecurityException e) { // Ignore. } } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } static void close(OioDatagramChannel channel, ChannelFuture future) { boolean connected = channel.isConnected(); boolean bound = channel.isBound(); try { channel.socket.close(); if (channel.setClosed()) { future.setSuccess(); if (connected) { // Notify the worker so it stops reading. Thread currentThread = Thread.currentThread(); Thread workerThread = channel.workerThread; if (workerThread != null && currentThread != workerThread) { workerThread.interrupt(); } fireChannelDisconnected(channel); } if (bound) { fireChannelUnbound(channel); } fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } }././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramChannel.jav0000644000175000017500000001222011212144657032441 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.MulticastSocket; import java.net.NetworkInterface; import java.net.SocketAddress; import java.net.SocketException; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.socket.DatagramChannel; import org.jboss.netty.channel.socket.DatagramChannelConfig; import org.jboss.netty.channel.socket.DefaultDatagramChannelConfig; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1331 $, $Date: 2009-06-05 00:30:55 -0700 (Fri, 05 Jun 2009) $ * */ final class OioDatagramChannel extends AbstractChannel implements DatagramChannel { final MulticastSocket socket; final Object interestOpsLock = new Object(); private final DatagramChannelConfig config; volatile Thread workerThread; OioDatagramChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { super(null, factory, pipeline, sink); try { socket = new MulticastSocket(null); } catch (IOException e) { throw new ChannelException("Failed to open a datagram socket.", e); } try { socket.setSoTimeout(10); } catch (SocketException e) { throw new ChannelException( "Failed to configure the datagram socket timeout.", e); } config = new DefaultDatagramChannelConfig(socket); fireChannelOpen(this); } public DatagramChannelConfig getConfig() { return config; } public InetSocketAddress getLocalAddress() { return (InetSocketAddress) socket.getLocalSocketAddress(); } public InetSocketAddress getRemoteAddress() { return (InetSocketAddress) socket.getRemoteSocketAddress(); } public boolean isBound() { return isOpen() && socket.isBound(); } public boolean isConnected() { return isOpen() && socket.isConnected(); } @Override protected boolean setClosed() { return super.setClosed(); } @Override protected void setInterestOpsNow(int interestOps) { super.setInterestOpsNow(interestOps); } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) { return super.write(message, null); } else { return super.write(message, remoteAddress); } } public void joinGroup(InetAddress multicastAddress) { ensureBound(); try { socket.joinGroup(multicastAddress); } catch (IOException e) { throw new ChannelException(e); } } public void joinGroup( InetSocketAddress multicastAddress, NetworkInterface networkInterface) { ensureBound(); try { socket.joinGroup(multicastAddress, networkInterface); } catch (IOException e) { throw new ChannelException(e); } } private void ensureBound() { if (!isBound()) { throw new IllegalStateException( DatagramChannel.class.getName() + " must be bound to join a group."); } } public void leaveGroup(InetAddress multicastAddress) { try { socket.leaveGroup(multicastAddress); } catch (IOException e) { throw new ChannelException(e); } } public void leaveGroup( InetSocketAddress multicastAddress, NetworkInterface networkInterface) { try { socket.leaveGroup(multicastAddress, networkInterface); } catch (IOException e) { throw new ChannelException(e); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioSocketChannel.java0000644000175000017500000000677111212144657032330 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import java.io.OutputStream; import java.io.PushbackInputStream; import java.net.InetSocketAddress; import java.net.Socket; import java.net.SocketAddress; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.socket.DefaultSocketChannelConfig; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.channel.socket.SocketChannelConfig; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1331 $, $Date: 2009-06-05 00:30:55 -0700 (Fri, 05 Jun 2009) $ * */ abstract class OioSocketChannel extends AbstractChannel implements SocketChannel { final Socket socket; final Object interestOpsLock = new Object(); private final SocketChannelConfig config; volatile Thread workerThread; OioSocketChannel( Channel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, Socket socket) { super(parent, factory, pipeline, sink); this.socket = socket; config = new DefaultSocketChannelConfig(socket); } public SocketChannelConfig getConfig() { return config; } public InetSocketAddress getLocalAddress() { return (InetSocketAddress) socket.getLocalSocketAddress(); } public InetSocketAddress getRemoteAddress() { return (InetSocketAddress) socket.getRemoteSocketAddress(); } public boolean isBound() { return isOpen() && socket.isBound(); } public boolean isConnected() { return isOpen() && socket.isConnected(); } @Override protected boolean setClosed() { return super.setClosed(); } @Override protected void setInterestOpsNow(int interestOps) { super.setInterestOpsNow(interestOps); } abstract PushbackInputStream getInputStream(); abstract OutputStream getOutputStream(); @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { if (remoteAddress == null || remoteAddress.equals(getRemoteAddress())) { return super.write(message, null); } else { return getUnsupportedOperationFuture(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioWorker.java0000644000175000017500000001637711212144657031063 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.OutputStream; import java.io.PushbackInputStream; import java.net.SocketException; import java.nio.channels.ClosedChannelException; import java.util.regex.Pattern; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1331 $, $Date: 2009-06-05 00:30:55 -0700 (Fri, 05 Jun 2009) $ * */ class OioWorker implements Runnable { private static final Pattern SOCKET_CLOSED_MESSAGE = Pattern.compile( "^.*(?:Socket.*closed).*$", Pattern.CASE_INSENSITIVE); private final OioSocketChannel channel; OioWorker(OioSocketChannel channel) { this.channel = channel; } public void run() { channel.workerThread = Thread.currentThread(); final PushbackInputStream in = channel.getInputStream(); while (channel.isOpen()) { synchronized (channel.interestOpsLock) { while (!channel.isReadable()) { try { // notify() is not called at all. // close() and setInterestOps() calls Thread.interrupt() channel.interestOpsLock.wait(); } catch (InterruptedException e) { if (!channel.isOpen()) { break; } } } } byte[] buf; int readBytes; try { int bytesToRead = in.available(); if (bytesToRead > 0) { buf = new byte[bytesToRead]; readBytes = in.read(buf); } else { int b = in.read(); if (b < 0) { break; } in.unread(b); continue; } } catch (Throwable t) { if (!channel.socket.isClosed()) { fireExceptionCaught(channel, t); } break; } ChannelBuffer buffer; if (readBytes == buf.length) { buffer = ChannelBuffers.wrappedBuffer(buf); } else { // A rare case, but it sometimes happen. buffer = ChannelBuffers.wrappedBuffer(buf, 0, readBytes); } fireMessageReceived(channel, buffer); } // Setting the workerThread to null will prevent any channel // operations from interrupting this thread from now on. channel.workerThread = null; // Clean up. close(channel, succeededFuture(channel)); } static void write( OioSocketChannel channel, ChannelFuture future, Object message) { OutputStream out = channel.getOutputStream(); try { ChannelBuffer a = (ChannelBuffer) message; int bytes = a.readableBytes(); synchronized (out) { a.getBytes(a.readerIndex(), out, bytes); } fireWriteComplete(channel, bytes); future.setSuccess(); } catch (Throwable t) { // Convert 'SocketException: Socket closed' to // ClosedChannelException. if (t instanceof SocketException && SOCKET_CLOSED_MESSAGE.matcher( String.valueOf(t.getMessage())).matches()) { t = new ClosedChannelException(); } future.setFailure(t); fireExceptionCaught(channel, t); } } static void setInterestOps( OioSocketChannel channel, ChannelFuture future, int interestOps) { // Override OP_WRITE flag - a user cannot change this flag. interestOps &= ~Channel.OP_WRITE; interestOps |= channel.getInterestOps() & Channel.OP_WRITE; boolean changed = false; try { if (channel.getInterestOps() != interestOps) { if ((interestOps & Channel.OP_READ) != 0) { channel.setInterestOpsNow(Channel.OP_READ); } else { channel.setInterestOpsNow(Channel.OP_NONE); } changed = true; } future.setSuccess(); if (changed) { synchronized (channel.interestOpsLock) { channel.setInterestOpsNow(interestOps); // Notify the worker so it stops or continues reading. Thread currentThread = Thread.currentThread(); Thread workerThread = channel.workerThread; if (workerThread != null && currentThread != workerThread) { workerThread.interrupt(); } } fireChannelInterestChanged(channel); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } static void close(OioSocketChannel channel, ChannelFuture future) { boolean connected = channel.isConnected(); boolean bound = channel.isBound(); try { channel.socket.close(); if (channel.setClosed()) { future.setSuccess(); if (connected) { // Notify the worker so it stops reading. Thread currentThread = Thread.currentThread(); Thread workerThread = channel.workerThread; if (workerThread != null && currentThread != workerThread) { workerThread.interrupt(); } fireChannelDisconnected(channel); } if (bound) { fireChannelUnbound(channel); } fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } }././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioServerSocketPipelineSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioServerSocketPipelin0000644000175000017500000002244111213672505032616 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.Socket; import java.net.SocketAddress; import java.net.SocketTimeoutException; import java.util.concurrent.Executor; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.IoWorkerRunnable; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ class OioServerSocketPipelineSink extends AbstractChannelSink { static final InternalLogger logger = InternalLoggerFactory.getInstance(OioServerSocketPipelineSink.class); final Executor workerExecutor; OioServerSocketPipelineSink(Executor workerExecutor) { this.workerExecutor = workerExecutor; } public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { Channel channel = e.getChannel(); if (channel instanceof OioServerSocketChannel) { handleServerSocket(e); } else if (channel instanceof OioAcceptedSocketChannel) { handleAcceptedSocket(e); } } private void handleServerSocket(ChannelEvent e) { if (!(e instanceof ChannelStateEvent)) { return; } ChannelStateEvent event = (ChannelStateEvent) e; OioServerSocketChannel channel = (OioServerSocketChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (SocketAddress) value); } else { close(channel, future); } break; } } private void handleAcceptedSocket(ChannelEvent e) { if (e instanceof ChannelStateEvent) { ChannelStateEvent event = (ChannelStateEvent) e; OioAcceptedSocketChannel channel = (OioAcceptedSocketChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { OioWorker.close(channel, future); } break; case BOUND: case CONNECTED: if (value == null) { OioWorker.close(channel, future); } break; case INTEREST_OPS: OioWorker.setInterestOps(channel, future, ((Integer) value).intValue()); break; } } else if (e instanceof MessageEvent) { MessageEvent event = (MessageEvent) e; OioSocketChannel channel = (OioSocketChannel) event.getChannel(); ChannelFuture future = event.getFuture(); Object message = event.getMessage(); OioWorker.write(channel, future, message); } } private void bind( OioServerSocketChannel channel, ChannelFuture future, SocketAddress localAddress) { boolean bound = false; boolean bossStarted = false; try { channel.socket.bind(localAddress, channel.getConfig().getBacklog()); bound = true; future.setSuccess(); localAddress = channel.getLocalAddress(); fireChannelBound(channel, localAddress); Executor bossExecutor = ((OioServerSocketChannelFactory) channel.getFactory()).bossExecutor; bossExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( new Boss(channel), "Old I/O server boss (channelId: " + channel.getId() + ", " + localAddress + ')'))); bossStarted = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (!bossStarted && bound) { close(channel, future); } } } private void close(OioServerSocketChannel channel, ChannelFuture future) { boolean bound = channel.isBound(); try { channel.socket.close(); if (channel.setClosed()) { future.setSuccess(); if (bound) { fireChannelUnbound(channel); } fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } private final class Boss implements Runnable { private final OioServerSocketChannel channel; Boss(OioServerSocketChannel channel) { this.channel = channel; } public void run() { while (channel.isBound()) { try { Socket acceptedSocket = channel.socket.accept(); try { ChannelPipeline pipeline = channel.getConfig().getPipelineFactory().getPipeline(); final OioAcceptedSocketChannel acceptedChannel = new OioAcceptedSocketChannel( channel, channel.getFactory(), pipeline, OioServerSocketPipelineSink.this, acceptedSocket); workerExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( new OioWorker(acceptedChannel), "Old I/O server worker (parentId: " + channel.getId() + ", channelId: " + acceptedChannel.getId() + ", " + channel.getRemoteAddress() + " => " + channel.getLocalAddress() + ')'))); } catch (Exception e) { logger.warn( "Failed to initialize an accepted socket.", e); try { acceptedSocket.close(); } catch (IOException e2) { logger.warn( "Failed to close a partially accepted socket.", e2); } } } catch (SocketTimeoutException e) { // Thrown every second to stop when requested. } catch (IOException e) { // Do not log the exception if the server socket was closed // by a user. if (!channel.socket.isBound() || channel.socket.isClosed()) { break; } logger.warn( "Failed to accept a connection.", e); try { Thread.sleep(1000); } catch (InterruptedException e1) { // Ignore } } } } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioDatagramChannelFact0000644000175000017500000001016611175574066032500 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.DatagramChannel; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.util.internal.ExecutorUtil; /** * A {@link DatagramChannelFactory} which creates a blocking I/O based * {@link DatagramChannel}. It utilizes the good old blocking I/O API which * has support for multicast. * *

How threads work

*

* There is only one type of threads in {@link OioDatagramChannelFactory}; * worker threads. * *

Worker threads

*

* Each {@link Channel} has a dedicated worker thread, just like a * traditional blocking I/O thread model. * *

Life cycle of threads and graceful shutdown

*

* Worker threads are acquired from the {@link Executor} which was specified * when a {@link OioDatagramChannelFactory} was created (i.e. {@code workerExecutor}.) * Therefore, you should make sure the specified {@link Executor} is able to * lend the sufficient number of threads. *

* Worker threads are acquired lazily, and then released when there's nothing * left to process. All the related resources are also released when the * worker threads are released. Therefore, to shut down a service gracefully, * you should do the following: * *

    *
  1. close all channels created by the factory usually using * {@link ChannelGroup#close()}, and
  2. *
  3. call {@link #releaseExternalResources()}.
  4. *
* * Please make sure not to shut down the executor until all channels are * closed. Otherwise, you will end up with a {@link RejectedExecutionException} * and the related resources might not be released properly. * *

Limitation

*

* A {@link DatagramChannel} created by this factory does not support asynchronous * operations. Any I/O requests such as {@code "write"} will be performed in a * blocking manner. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark */ public class OioDatagramChannelFactory implements DatagramChannelFactory { private final Executor workerExecutor; final OioDatagramPipelineSink sink; /** * Creates a new instance. * * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads */ public OioDatagramChannelFactory(Executor workerExecutor) { if (workerExecutor == null) { throw new NullPointerException("workerExecutor"); } this.workerExecutor = workerExecutor; sink = new OioDatagramPipelineSink(workerExecutor); } public DatagramChannel newChannel(ChannelPipeline pipeline) { return new OioDatagramChannel(this, pipeline, sink); } public void releaseExternalResources() { ExecutorUtil.terminate(workerExecutor); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioClientSocketPipelineSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioClientSocketPipelin0000644000175000017500000001316511213672505032571 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.PushbackInputStream; import java.net.SocketAddress; import java.util.concurrent.Executor; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.ThreadRenamingRunnable; import org.jboss.netty.util.internal.IoWorkerRunnable; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ class OioClientSocketPipelineSink extends AbstractChannelSink { private final Executor workerExecutor; OioClientSocketPipelineSink(Executor workerExecutor) { this.workerExecutor = workerExecutor; } public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { OioClientSocketChannel channel = (OioClientSocketChannel) e.getChannel(); ChannelFuture future = e.getFuture(); if (e instanceof ChannelStateEvent) { ChannelStateEvent stateEvent = (ChannelStateEvent) e; ChannelState state = stateEvent.getState(); Object value = stateEvent.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { OioWorker.close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (SocketAddress) value); } else { OioWorker.close(channel, future); } break; case CONNECTED: if (value != null) { connect(channel, future, (SocketAddress) value); } else { OioWorker.close(channel, future); } break; case INTEREST_OPS: OioWorker.setInterestOps(channel, future, ((Integer) value).intValue()); break; } } else if (e instanceof MessageEvent) { OioWorker.write( channel, future, ((MessageEvent) e).getMessage()); } } private void bind( OioClientSocketChannel channel, ChannelFuture future, SocketAddress localAddress) { try { channel.socket.bind(localAddress); future.setSuccess(); fireChannelBound(channel, channel.getLocalAddress()); } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } private void connect( OioClientSocketChannel channel, ChannelFuture future, SocketAddress remoteAddress) { boolean bound = channel.isBound(); boolean connected = false; boolean workerStarted = false; future.addListener(ChannelFutureListener.CLOSE_ON_FAILURE); try { channel.socket.connect( remoteAddress, channel.getConfig().getConnectTimeoutMillis()); connected = true; // Obtain I/O stream. channel.in = new PushbackInputStream(channel.socket.getInputStream(), 1); channel.out = channel.socket.getOutputStream(); // Fire events. future.setSuccess(); if (!bound) { fireChannelBound(channel, channel.getLocalAddress()); } fireChannelConnected(channel, channel.getRemoteAddress()); // Start the business. workerExecutor.execute( new IoWorkerRunnable( new ThreadRenamingRunnable( new OioWorker(channel), "Old I/O client worker (channelId: " + channel.getId() + ", " + channel.getLocalAddress() + " => " + channel.getRemoteAddress() + ')'))); workerStarted = true; } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } finally { if (connected && !workerStarted) { OioWorker.close(channel, future); } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/package-info.java0000644000175000017500000000225111066406360031450 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Old blocking I/O based socket channel API implementation - recommended for * a small number of connections (< 1000). */ package org.jboss.netty.channel.socket.oio; ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioServerSocketChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioServerSocketChannel0000644000175000017500000001255311175574066032603 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.ServerSocketChannel; import org.jboss.netty.channel.socket.ServerSocketChannelFactory; import org.jboss.netty.util.internal.ExecutorUtil; /** * A {@link ServerSocketChannelFactory} which creates a server-side blocking * I/O based {@link ServerSocketChannel}. It utilizes the good old blocking * I/O API which is known to yield better throughput and latency when there * are relatively small number of connections to serve. * *

How threads work

*

* There are two types of threads in a {@link OioServerSocketChannelFactory}; * one is boss thread and the other is worker thread. * *

Boss threads

*

* Each bound {@link ServerSocketChannel} has its own boss thread. * For example, if you opened two server ports such as 80 and 443, you will * have two boss threads. A boss thread accepts incoming connections until * the port is unbound. Once a connection is accepted successfully, the boss * thread passes the accepted {@link Channel} to one of the worker * threads that the {@link OioServerSocketChannelFactory} manages. * *

Worker threads

*

* Each connected {@link Channel} has a dedicated worker thread, just like a * traditional blocking I/O thread model. * *

Life cycle of threads and graceful shutdown

*

* All threads are acquired from the {@link Executor}s which were specified * when a {@link OioServerSocketChannelFactory} was created. Boss threads are * acquired from the {@code bossExecutor}, and worker threads are acquired from * the {@code workerExecutor}. Therefore, you should make sure the specified * {@link Executor}s are able to lend the sufficient number of threads. *

* Both boss and worker threads are acquired lazily, and then released when * there's nothing left to process. All the related resources are also * released when the boss and worker threads are released. Therefore, to shut * down a service gracefully, you should do the following: * *

    *
  1. unbind all channels created by the factory, *
  2. close all child channels accepted by the unbound channels, * (these two steps so far is usually done using {@link ChannelGroup#close()})
  3. *
  4. call {@link #releaseExternalResources()}.
  5. *
* * Please make sure not to shut down the executor until all channels are * closed. Otherwise, you will end up with a {@link RejectedExecutionException} * and the related resources might not be released properly. * *

Limitation

*

* A {@link ServerSocketChannel} created by this factory and its child channels * do not support asynchronous operations. Any I/O requests such as * {@code "write"} will be performed in a blocking manner. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark */ public class OioServerSocketChannelFactory implements ServerSocketChannelFactory { final Executor bossExecutor; private final Executor workerExecutor; private final ChannelSink sink; /** * Creates a new instance. * * @param bossExecutor * the {@link Executor} which will execute the boss threads * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads */ public OioServerSocketChannelFactory( Executor bossExecutor, Executor workerExecutor) { if (bossExecutor == null) { throw new NullPointerException("bossExecutor"); } if (workerExecutor == null) { throw new NullPointerException("workerExecutor"); } this.bossExecutor = bossExecutor; this.workerExecutor = workerExecutor; sink = new OioServerSocketPipelineSink(workerExecutor); } public ServerSocketChannel newChannel(ChannelPipeline pipeline) { return new OioServerSocketChannel(this, pipeline, sink); } public void releaseExternalResources() { ExecutorUtil.terminate(bossExecutor, workerExecutor); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioClientSocketChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioClientSocketChannel0000644000175000017500000001043211175574066032545 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import java.util.concurrent.Executor; import java.util.concurrent.RejectedExecutionException; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.SocketChannel; import org.jboss.netty.util.internal.ExecutorUtil; /** * A {@link ClientSocketChannelFactory} which creates a client-side blocking * I/O based {@link SocketChannel}. It utilizes the good old blocking I/O API * which is known to yield better throughput and latency when there are * relatively small number of connections to serve. * *

How threads work

*

* There is only one type of threads in {@link OioClientSocketChannelFactory}; * worker threads. * *

Worker threads

*

* Each connected {@link Channel} has a dedicated worker thread, just like a * traditional blocking I/O thread model. * *

Life cycle of threads and graceful shutdown

*

* Worker threads are acquired from the {@link Executor} which was specified * when a {@link OioClientSocketChannelFactory} was created (i.e. {@code workerExecutor}.) * Therefore, you should make sure the specified {@link Executor} is able to * lend the sufficient number of threads. *

* Worker threads are acquired lazily, and then released when there's nothing * left to process. All the related resources are also released when the * worker threads are released. Therefore, to shut down a service gracefully, * you should do the following: * *

    *
  1. close all channels created by the factory usually using * {@link ChannelGroup#close()}, and
  2. *
  3. call {@link #releaseExternalResources()}.
  4. *
* * Please make sure not to shut down the executor until all channels are * closed. Otherwise, you will end up with a {@link RejectedExecutionException} * and the related resources might not be released properly. * *

Limitation

*

* A {@link SocketChannel} created by this factory does not support asynchronous * operations. Any I/O requests such as {@code "connect"} and {@code "write"} * will be performed in a blocking manner. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark */ public class OioClientSocketChannelFactory implements ClientSocketChannelFactory { private final Executor workerExecutor; final OioClientSocketPipelineSink sink; /** * Creates a new instance. * * @param workerExecutor * the {@link Executor} which will execute the I/O worker threads */ public OioClientSocketChannelFactory(Executor workerExecutor) { if (workerExecutor == null) { throw new NullPointerException("workerExecutor"); } this.workerExecutor = workerExecutor; sink = new OioClientSocketPipelineSink(workerExecutor); } public SocketChannel newChannel(ChannelPipeline pipeline) { return new OioClientSocketChannel(this, pipeline, sink); } public void releaseExternalResources() { ExecutorUtil.terminate(workerExecutor); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioServerSocketChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/oio/OioServerSocketChannel0000644000175000017500000000704511150044463032565 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket.oio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.InetSocketAddress; import java.net.ServerSocket; import org.jboss.netty.channel.AbstractServerChannel; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.socket.DefaultServerSocketChannelConfig; import org.jboss.netty.channel.socket.ServerSocketChannel; import org.jboss.netty.channel.socket.ServerSocketChannelConfig; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 922 $, $Date: 2009-02-21 10:34:27 -0800 (Sat, 21 Feb 2009) $ * */ class OioServerSocketChannel extends AbstractServerChannel implements ServerSocketChannel { private static final InternalLogger logger = InternalLoggerFactory.getInstance(OioServerSocketChannel.class); final ServerSocket socket; private final ServerSocketChannelConfig config; OioServerSocketChannel( ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { super(factory, pipeline, sink); try { socket = new ServerSocket(); } catch (IOException e) { throw new ChannelException( "Failed to open a server socket.", e); } try { socket.setSoTimeout(1000); } catch (IOException e) { try { socket.close(); } catch (IOException e2) { logger.warn( "Failed to close a partially initialized socket.", e2); } throw new ChannelException( "Failed to set the server socket timeout.", e); } config = new DefaultServerSocketChannelConfig(socket); fireChannelOpen(this); } public ServerSocketChannelConfig getConfig() { return config; } public InetSocketAddress getLocalAddress() { return (InetSocketAddress) socket.getLocalSocketAddress(); } public InetSocketAddress getRemoteAddress() { return null; } public boolean isBound() { return isOpen() && socket.isBound(); } @Override protected boolean setClosed() { return super.setClosed(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/package-info.java0000644000175000017500000000224411060210335030651 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Abstract TCP and UDP socket interfaces which extend the core channel API. * * @apiviz.exclude \.(Abstract|Default).*$ */ package org.jboss.netty.channel.socket; libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/SocketChannelConfig.java0000644000175000017500000001163211066426056032214 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.Socket; import org.jboss.netty.channel.ChannelConfig; /** * A {@link ChannelConfig} for a {@link SocketChannel}. * *

Available options

* * In addition to the options provided by {@link ChannelConfig}, * {@link SocketChannelConfig} allows the following options in the option map: * * * * * * * * * * * * * * * * * * * *
NameAssociated setter method
{@code "keepAlive"}{@link #setKeepAlive(boolean)}
{@code "reuseAddress"}{@link #setReuseAddress(boolean)}
{@code "soLinger"}{@link #setSoLinger(int)}
{@code "tcpNoDelay"}{@link #setTcpNoDelay(boolean)}
{@code "receiveBufferSize"}{@link #setReceiveBufferSize(int)}
{@code "sendBufferSize"}{@link #setSendBufferSize(int)}
{@code "trafficClass"}{@link #setTrafficClass(int)}
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 313 $, $Date: 2008-09-24 05:01:50 -0700 (Wed, 24 Sep 2008) $ * * @apiviz.landmark */ public interface SocketChannelConfig extends ChannelConfig { /** * Gets the {@code SO_TCPNODELAY} option. */ boolean isTcpNoDelay(); /** * Sets the {@code SO_TCPNODELAY} option. */ void setTcpNoDelay(boolean tcpNoDelay); /** * Gets the {@code SO_LINGER} option. */ int getSoLinger(); /** * Sets the {@code SO_LINGER} option. */ void setSoLinger(int soLinger); /** * Gets the {@code SO_SNDBUF} option. */ int getSendBufferSize(); /** * Sets the {@code SO_SNDBUF} option. */ void setSendBufferSize(int sendBufferSize); /** * Gets the {@code SO_RCVBUF} option. */ int getReceiveBufferSize(); /** * Gets the {@code SO_RCVBUF} option. */ void setReceiveBufferSize(int receiveBufferSize); /** * Gets the {@code SO_KEEPALIVE} option. */ boolean isKeepAlive(); /** * Sets the {@code SO_KEEPALIVE} option. */ void setKeepAlive(boolean keepAlive); /** * Gets the traffic class. */ int getTrafficClass(); /** * Sets the traffic class as specified in {@link Socket#setTrafficClass(int)}. */ void setTrafficClass(int trafficClass); /** * Gets the {@code SO_REUSEADDR} option. */ boolean isReuseAddress(); /** * Sets the {@code SO_REUSEADDR} option. */ void setReuseAddress(boolean reuseAddress); /** * Sets the performance preferences as specified in * {@link Socket#setPerformancePreferences(int, int, int)}. */ void setPerformancePreferences( int connectionTime, int latency, int bandwidth); } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DefaultSocketChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DefaultSocketChannelConfig0000644000175000017500000001370111165336702032576 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.Socket; import java.net.SocketException; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.DefaultChannelConfig; import org.jboss.netty.util.internal.ConversionUtil; /** * The default {@link SocketChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class DefaultSocketChannelConfig extends DefaultChannelConfig implements SocketChannelConfig { private final Socket socket; /** * Creates a new instance. */ public DefaultSocketChannelConfig(Socket socket) { if (socket == null) { throw new NullPointerException("socket"); } this.socket = socket; } @Override public boolean setOption(String key, Object value) { if (super.setOption(key, value)) { return true; } if (key.equals("receiveBufferSize")) { setReceiveBufferSize(ConversionUtil.toInt(value)); } else if (key.equals("sendBufferSize")) { setSendBufferSize(ConversionUtil.toInt(value)); } else if (key.equals("tcpNoDelay")) { setTcpNoDelay(ConversionUtil.toBoolean(value)); } else if (key.equals("keepAlive")) { setKeepAlive(ConversionUtil.toBoolean(value)); } else if (key.equals("reuseAddress")) { setReuseAddress(ConversionUtil.toBoolean(value)); } else if (key.equals("soLinger")) { setSoLinger(ConversionUtil.toInt(value)); } else if (key.equals("trafficClass")) { setTrafficClass(ConversionUtil.toInt(value)); } else { return false; } return true; } public int getReceiveBufferSize() { try { return socket.getReceiveBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } } public int getSendBufferSize() { try { return socket.getSendBufferSize(); } catch (SocketException e) { throw new ChannelException(e); } } public int getSoLinger() { try { return socket.getSoLinger(); } catch (SocketException e) { throw new ChannelException(e); } } public int getTrafficClass() { try { return socket.getTrafficClass(); } catch (SocketException e) { throw new ChannelException(e); } } public boolean isKeepAlive() { try { return socket.getKeepAlive(); } catch (SocketException e) { throw new ChannelException(e); } } public boolean isReuseAddress() { try { return socket.getReuseAddress(); } catch (SocketException e) { throw new ChannelException(e); } } public boolean isTcpNoDelay() { try { return socket.getTcpNoDelay(); } catch (SocketException e) { throw new ChannelException(e); } } public void setKeepAlive(boolean keepAlive) { try { socket.setKeepAlive(keepAlive); } catch (SocketException e) { throw new ChannelException(e); } } public void setPerformancePreferences( int connectionTime, int latency, int bandwidth) { socket.setPerformancePreferences(connectionTime, latency, bandwidth); } public void setReceiveBufferSize(int receiveBufferSize) { try { socket.setReceiveBufferSize(receiveBufferSize); } catch (SocketException e) { throw new ChannelException(e); } } public void setReuseAddress(boolean reuseAddress) { try { socket.setReuseAddress(reuseAddress); } catch (SocketException e) { throw new ChannelException(e); } } public void setSendBufferSize(int sendBufferSize) { try { socket.setSendBufferSize(sendBufferSize); } catch (SocketException e) { throw new ChannelException(e); } } public void setSoLinger(int soLinger) { try { if (soLinger < 0) { socket.setSoLinger(false, 0); } else { socket.setSoLinger(true, soLinger); } } catch (SocketException e) { throw new ChannelException(e); } } public void setTcpNoDelay(boolean tcpNoDelay) { try { socket.setTcpNoDelay(tcpNoDelay); } catch (SocketException e) { throw new ChannelException(e); } } public void setTrafficClass(int trafficClass) { try { socket.setTrafficClass(trafficClass); } catch (SocketException e) { throw new ChannelException(e); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DatagramChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/socket/DatagramChannelConfig.java0000644000175000017500000001506411216642477032513 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.socket; import java.net.DatagramSocket; import java.net.InetAddress; import java.net.NetworkInterface; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.FixedReceiveBufferSizePredictor; import org.jboss.netty.channel.ReceiveBufferSizePredictor; /** * A {@link ChannelConfig} for a {@link DatagramChannel}. * *

Available options

* * In addition to the options provided by {@link ChannelConfig}, * {@link DatagramChannelConfig} allows the following options in the option map: * * * * * * * * * * * * * * * * * * * * * * * * * *
NameAssociated setter method
{@code "broadcast"}{@link #setBroadcast(boolean)}
{@code "interface"}{@link #setInterface(InetAddress)}
{@code "loopbackModeDisabled"}{@link #setLoopbackModeDisabled(boolean)}
{@code "networkInterface"}{@link #setNetworkInterface(NetworkInterface)}
{@code "reuseAddress"}{@link #setReuseAddress(boolean)}
{@code "receiveBufferSize"}{@link #setReceiveBufferSize(int)}
{@code "receiveBufferSizePredictor"}{@link #setReceiveBufferSizePredictor(ReceiveBufferSizePredictor)}
{@code "sendBufferSize"}{@link #setSendBufferSize(int)}
{@code "timeToLive"}{@link #setTimeToLive(int)}
{@code "trafficClass"}{@link #setTrafficClass(int)}
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1446 $, $Date: 2009-06-19 00:58:55 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.landmark */ public interface DatagramChannelConfig extends ChannelConfig { /** * Gets the {@code SO_SNDBUF} option. */ int getSendBufferSize(); /** * Sets the {@code SO_SNDBUF} option. */ void setSendBufferSize(int sendBufferSize); /** * Gets the {@code SO_RCVBUF} option. */ int getReceiveBufferSize(); /** * Gets the {@code SO_RCVBUF} option. */ void setReceiveBufferSize(int receiveBufferSize); /** * Gets the traffic class. */ int getTrafficClass(); /** * Sets the traffic class as specified in {@link DatagramSocket#setTrafficClass(int)}. */ void setTrafficClass(int trafficClass); /** * Gets the {@code SO_REUSEADDR} option. */ boolean isReuseAddress(); /** * Sets the {@code SO_REUSEADDR} option. */ void setReuseAddress(boolean reuseAddress); /** * Gets the {@code SO_BROADCAST} option. */ boolean isBroadcast(); /** * Sets the {@code SO_BROADCAST} option. */ void setBroadcast(boolean broadcast); /** * Gets the setting for local loopback of multicast datagrams. * * @return {@code true} if and only if the loopback mode has been disabled */ boolean isLoopbackModeDisabled(); /** * Sets the setting for local loopback of multicast datagrams. * * @param loopbackModeDisabled * {@code true} if and only if the loopback mode has been disabled */ void setLoopbackModeDisabled(boolean loopbackModeDisabled); /** * Gets the default time-to-live for multicast packets sent out on the * socket. */ int getTimeToLive(); /** * Sets the default time-to-live for multicast packets sent out on the * {@link DatagramChannel} in order to control the scope of the multicasts. */ void setTimeToLive(int ttl); /** * Gets the address of the network interface used for multicast packets. */ InetAddress getInterface(); /** * Sets the address of the network interface used for multicast packets. */ void setInterface(InetAddress interfaceAddress); /** * Gets the network interface for outgoing multicast datagrams sent on * the {@link DatagramChannel}. */ NetworkInterface getNetworkInterface(); /** * Sets the network interface for outgoing multicast datagrams sent on * the {@link DatagramChannel}. */ void setNetworkInterface(NetworkInterface networkInterface); /** * Returns the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link FixedReceiveBufferSizePredictor}(768). */ ReceiveBufferSizePredictor getReceiveBufferSizePredictor(); /** * Sets the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link FixedReceiveBufferSizePredictor}(768). */ void setReceiveBufferSizePredictor(ReceiveBufferSizePredictor predictor); } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/SimpleChannelUpstreamHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/SimpleChannelUpstreamHandler.java0000644000175000017500000002052611142473445032617 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * A {@link ChannelUpstreamHandler} which provides an individual handler method * for each event type. This handler down-casts the received upstream event * into more meaningful sub-type event and calls an appropriate handler method * with the down-cast event. The names of the methods are identical to the * upstream event names, as introduced in the {@link ChannelUpstreamHandler} * documentation. *

* Please use {@link SimpleChannelHandler} if you need to implement both * {@link ChannelUpstreamHandler} and {@link ChannelDownstreamHandler}. * *

Overriding the {@link #handleUpstream(ChannelHandlerContext, ChannelEvent) handleUpstream} method

*

* You can override the {@link #handleUpstream(ChannelHandlerContext, ChannelEvent) handleUpstream} * method just like overriding an ordinary Java method. Please make sure to * call {@code super.handleUpstream()} so that other handler methods are invoked * properly: *

*
public class MyChannelHandler extends SimpleChannelUpstreamHandler {
 *
 *     public void handleUpstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *
 *         // Log all channel state changes.
 *         if (e instanceof ChannelStateEvent) {
 *             logger.info("Channel state changed: " + e);
 *         }
 *
 *         super.handleUpstream(ctx, e);
 *     }
 * }
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 760 $, $Date: 2009-02-04 21:20:37 -0800 (Wed, 04 Feb 2009) $ */ public class SimpleChannelUpstreamHandler implements ChannelUpstreamHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SimpleChannelUpstreamHandler.class.getName()); /** * Creates a new instance. */ public SimpleChannelUpstreamHandler() { super(); } /** * {@inheritDoc} Down-casts the received upstream event into more * meaningful sub-type event and calls an appropriate handler method with * the down-casted event. */ public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof MessageEvent) { messageReceived(ctx, (MessageEvent) e); } else if (e instanceof WriteCompletionEvent) { WriteCompletionEvent evt = (WriteCompletionEvent) e; writeComplete(ctx, evt); } else if (e instanceof ChildChannelStateEvent) { ChildChannelStateEvent evt = (ChildChannelStateEvent) e; if (evt.getChildChannel().isOpen()) { childChannelOpen(ctx, evt); } else { childChannelClosed(ctx, evt); } } else if (e instanceof ChannelStateEvent) { ChannelStateEvent evt = (ChannelStateEvent) e; switch (evt.getState()) { case OPEN: if (Boolean.TRUE.equals(evt.getValue())) { channelOpen(ctx, evt); } else { channelClosed(ctx, evt); } break; case BOUND: if (evt.getValue() != null) { channelBound(ctx, evt); } else { channelUnbound(ctx, evt); } break; case CONNECTED: if (evt.getValue() != null) { channelConnected(ctx, evt); } else { channelDisconnected(ctx, evt); } break; case INTEREST_OPS: channelInterestChanged(ctx, evt); break; default: ctx.sendDownstream(e); } } else if (e instanceof ExceptionEvent) { exceptionCaught(ctx, (ExceptionEvent) e); } else { ctx.sendUpstream(e); } } /** * Invoked when a message object (e.g: {@link ChannelBuffer}) was received * from a remote peer. */ public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when an exception was raised by an I/O thread or a * {@link ChannelHandler}. */ public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (this == ctx.getPipeline().getLast()) { logger.warn( "EXCEPTION, please implement " + getClass().getName() + ".exceptionCaught() for proper handling.", e.getCause()); } ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} is open, but not bound nor connected. */ public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} is open and bound to a local address, * but not connected. */ public void channelBound( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} is open, bound to a local address, and * connected to a remote address. */ public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel}'s {@link Channel#getInterestOps() interestOps} * was changed. */ public void channelInterestChanged( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} was disconnected from its remote peer. */ public void channelDisconnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} was unbound from the current local address. */ public void channelUnbound( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} was closed and all its related resources * were released. */ public void channelClosed( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when something was written into a {@link Channel}. */ public void writeComplete( ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a child {@link Channel} was open. * (e.g. a server channel accepted a connection) */ public void childChannelOpen( ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a child {@link Channel} was closed. * (e.g. the accepted connection was closed) */ public void childChannelClosed( ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelState.java0000644000175000017500000001022011216723540027411 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; /** * The current or future state of a {@link Channel}. *

* The state of a {@link Channel} is interpreted differently depending on the * {@linkplain ChannelStateEvent#getValue() value} of a {@link ChannelStateEvent} * and the direction of the event in a {@link ChannelPipeline}: * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
DirectionStateValueMeaning
Upstream{@link #OPEN}{@code true}The channel is open.
Upstream{@link #OPEN}{@code false}The channel is closed.
Upstream{@link #BOUND}{@link SocketAddress}The channel is bound to a local address.
Upstream{@link #BOUND}{@code null}The channel is unbound to a local address.
Upstream{@link #CONNECTED}{@link SocketAddress}The channel is connected to a remote address.
Upstream{@link #CONNECTED}{@code null}The channel is disconnected from a remote address.
Upstream{@link #INTEREST_OPS}an integerThe channel interestOps has been changed.
Downstream{@link #OPEN}{@code true}N/A
Downstream{@link #OPEN}{@code false}Close the channel.
Downstream{@link #BOUND}{@link SocketAddress}Bind the channel to the specified local address.
Downstream{@link #BOUND}{@code null}Unbind the channel from the current local address.
Downstream{@link #CONNECTED}{@link SocketAddress}Connect the channel to the specified remote address.
Downstream{@link #CONNECTED}{@code null}Disconnect the channel from the current remote address.
Downstream{@link #INTEREST_OPS}an integerChange the interestOps of the channel.
*

* To see how a {@link ChannelEvent} is interpreted further, please refer to * {@link ChannelUpstreamHandler} and {@link ChannelDownstreamHandler}. * * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1471 $, $Date: 2009-06-19 07:57:36 -0700 (Fri, 19 Jun 2009) $ */ public enum ChannelState { /** * Represents a {@link Channel}'s {@link Channel#isOpen() open} property */ OPEN, /** * Represents a {@link Channel}'s {@link Channel#isBound() bound} property */ BOUND, /** * Represents a {@link Channel}'s {@link Channel#isConnected() connected} * property */ CONNECTED, /** * Represents a {@link Channel}'s {@link Channel#getInterestOps() interestOps} * property */ INTEREST_OPS; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelUpstreamHandler.java0000644000175000017500000002200211175574066031443 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; import java.util.concurrent.Executor; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.socket.ServerSocketChannel; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; /** * Handles or intercepts an upstream {@link ChannelEvent}, and sends a * {@link ChannelEvent} to the next or previous handler in a * {@link ChannelPipeline}. * *

Upstream events

*

* An upstream event is an event which is supposed to be processed from the * first handler to the last handler in the {@link ChannelPipeline}. * For example, all events initiated by an I/O thread are upstream events, and * they have the following meaning: *

* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * *
Event nameEvent type and conditionMeaning
{@code "messageReceived"}{@link MessageEvent}a message object (e.g. {@link ChannelBuffer}) was received from a remote peer
{@code "exceptionCaught"}{@link ExceptionEvent}an exception was raised by an I/O thread or a {@link ChannelHandler}
{@code "channelOpen"}{@link ChannelStateEvent}
(state = {@link ChannelState#OPEN OPEN}, value = {@code true})
a {@link Channel} is open, but not bound nor connected
{@code "channelClosed"}{@link ChannelStateEvent}
(state = {@link ChannelState#OPEN OPEN}, value = {@code false})
a {@link Channel} was closed and all its related resources were released
{@code "channelBound"}{@link ChannelStateEvent}
(state = {@link ChannelState#BOUND BOUND}, value = {@link SocketAddress})
a {@link Channel} is open and bound to a local address, but not connected
{@code "channelUnbound"}{@link ChannelStateEvent}
(state = {@link ChannelState#BOUND BOUND}, value = {@code null})
a {@link Channel} was unbound from the current local address
{@code "channelConnected"}{@link ChannelStateEvent}
(state = {@link ChannelState#CONNECTED CONNECTED}, value = {@link SocketAddress})
a {@link Channel} is open, bound to a local address, and connected to a remote address
{@code "writeComplete"}{@link WriteCompletionEvent}something has been written to a remote peer
{@code "channelDisconnected"}{@link ChannelStateEvent}
(state = {@link ChannelState#CONNECTED CONNECTED}, value = {@code null})
a {@link Channel} was disconnected from its remote peer
{@code "channelInterestChanged"}{@link ChannelStateEvent}
(state = {@link ChannelState#INTEREST_OPS INTEREST_OPS}, no value)
a {@link Channel}'s {@link Channel#getInterestOps() interestOps} was changed
*

* These two additional event types are used only for a parent channel which * can have a child channel (e.g. {@link ServerSocketChannel}). *

* * * * * * * * * * * * * * *
Event nameEvent type and conditionMeaning
{@code "childChannelOpen"}{@link ChildChannelStateEvent}
({@code childChannel.isOpen() = true})
a child {@link Channel} was open (e.g. a server channel accepted a connection.)
{@code "childChannelClosed"}{@link ChildChannelStateEvent}
({@code childChannel.isOpen() = false})
a child {@link Channel} was closed (e.g. the accepted connection was closed.)
* *

Additional resources worth reading

*

* You might want to refer to {@link ChannelDownstreamHandler} to see how a * {@link ChannelEvent} is interpreted when going downstream. Also, please * refer to the {@link ChannelEvent} and {@link ChannelPipeline} documentation * to find out what an upstream event and a downstream event are, what * fundamental differences they have, and how they flow in a pipeline. * *

{@link SimpleChannelHandler}

*

* In most cases, you will get to use a {@link SimpleChannelHandler} to * implement an upstream handler because it provides an individual handler * method for each event type. You might want to implement this interface * directly though if you want to handle various types of events in more * generic way. * *

Firing an event to the next or previous handler

*

* You can forward the received event upstream or downstream. In most cases, * {@link ChannelUpstreamHandler} will sent the event to the next handler * (upstream) although it is legal to sent the event to the previous handler * (downstream): * *

 * // Sending the event forward (upstream)
 * void handleUpstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *     ...
 *     ctx.sendUpstream(e);
 *     ...
 * }
 *
 * // Sending the event backward (downstream)
 * void handleDownstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *     ...
 *     ctx.sendDownstream(new MessageEvent(...));
 *     ...
 * }
 * 
* *

Using the helper class to send an event

*

* You will also find various helper methods in {@link Channels} to be useful * to generate and send an artificial or manipulated event. * *

Thread safety

*

* If there's no {@link ExecutionHandler} in the {@link ChannelPipeline}, * {@link #handleUpstream(ChannelHandlerContext, ChannelEvent) handleUpstream} * will be invoked sequentially by the same thread (i.e. an I/O thread). * Please note that this does not necessarily mean that there's a dedicated * thread per {@link Channel}; the I/O thread of some transport can serve more * than one {@link Channel} (e.g. NIO transport), while the I/O thread of * other transports can serve only one (e.g. OIO transport). *

* If an {@link ExecutionHandler} is added in the {@link ChannelPipeline}, * {@link #handleUpstream(ChannelHandlerContext, ChannelEvent) handleUpstream} * may be invoked by different threads at the same time, depending on what * {@link Executor} implementation is used with the {@link ExecutionHandler}. *

* {@link OrderedMemoryAwareThreadPoolExecutor} is provided to guarantee the * order of {@link ChannelEvent}s. It does not guarantee that the invocation * will be made by the same thread for the same channel, but it does guarantee * that the invocation will be made sequentially for the events of the same * channel. For example, the events can be processed as depicted below: * *

 *           -----------------------------------> Timeline ----------------------------------->
 *
 * Thread X: --- Channel A (Event 1) --.   .-- Channel B (Event 2) --- Channel B (Event 3) --->
 *                                      \ /
 *                                       X
 *                                      / \
 * Thread Y: --- Channel B (Event 1) --'   '-- Channel A (Event 2) --- Channel A (Event 3) --->
 * 
*

* Also, please refer to the {@link ChannelPipelineCoverage} annotation to * understand the relationship between a handler and its stateful properties. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.exclude ^org\.jboss\.netty\.handler\..*$ */ public interface ChannelUpstreamHandler extends ChannelHandler { /** * Handles the specified upstream event. * * @param ctx the context object for this handler * @param e the upstream event to process or intercept */ void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception; } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/LifeCycleAwareChannelHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/LifeCycleAwareChannelHandler.java0000644000175000017500000000644111167057036032465 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link ChannelHandler} that is notified when it is added to or removed * from a {@link ChannelPipeline}. *

* Please note that the methods of this handler is called only when the * {@link ChannelPipeline} it belongs to has been * {@linkplain ChannelPipeline#attach(Channel, ChannelSink) attached}. * That is, if you add a {@link LifeCycleAwareChannelHandler} to the unattached * {@link ChannelPipeline}, the life cycle handler methods in this handler will * not be invoked because there's no associated {@link ChannelHandlerContext}: *

 * // Create a new pipeline which is unattached initially.
 * ChannelPipeline pipeline = Channels.pipeline();
 * // beforeAdd() and afterAdd() will not be called.
 * pipeline.addLast("handler", new MyLifeCycleAwareChannelHandler());
 * // beforeRemove() and afterRemove() will not be called.
 * pipeline.remove("handler");
 * 
* However, once the {@link ChannelPipeline} is attached and the * {@code channelOpen} event is fired, the life cycle handler methods will * be invoked on addition or removal: *
 * public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent evt) {
 *     // channelOpen event has been triggered, which means the pipeline has
 *     // been attached to the channel.
 *     ChannelPipeline pipeline = ctx.getChannel().getPipeline();
 *     // beforeAdd() and afterAdd() will be called.
 *     pipeline.addLast("handler", new MyLifeCycleAwareChannelHandler());
 * }
 *
 * public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent evt) {
 *     // Once attached, the pipeline is never detached.
 *     ChannelPipeline pipeline = ctx.getChannel().getPipeline();
 *     // beforeRemove() and afterRemove() will be called.
 *     pipeline.remove("handler");
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1150 $, $Date: 2009-04-08 01:19:42 -0700 (Wed, 08 Apr 2009) $ */ public interface LifeCycleAwareChannelHandler extends ChannelHandler { void beforeAdd(ChannelHandlerContext ctx) throws Exception; void afterAdd(ChannelHandlerContext ctx) throws Exception; void beforeRemove(ChannelHandlerContext ctx) throws Exception; void afterRemove(ChannelHandlerContext ctx) throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelFutureListener.java0000644000175000017500000000600611216131646031320 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.EventListener; /** * Listens to the result of a {@link ChannelFuture}. The result of the * asynchronous {@link Channel} I/O operation is notified once this listener * is added by calling {@link ChannelFuture#addListener(ChannelFutureListener)}. * *

Return the control to the caller quickly

* * {@link #operationComplete(ChannelFuture)} is directly called by an I/O * thread. Therefore, performing a time consuming task or a blocking operation * in the handler method can cause an unexpected pause during I/O. If you need * to perform a blocking operation on I/O completion, try to execute the * operation in a different thread using a thread pool. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1405 $, $Date: 2009-06-17 02:13:10 -0700 (Wed, 17 Jun 2009) $ */ public interface ChannelFutureListener extends EventListener { /** * A {@link ChannelFutureListener} that closes the {@link Channel} which is * associated with the specified {@link ChannelFuture}. */ static ChannelFutureListener CLOSE = new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { future.getChannel().close(); } }; /** * A {@link ChannelFutureListener} that closes the {@link Channel} when the * operation ended up with a failure or cancellation rather than a success. */ static ChannelFutureListener CLOSE_ON_FAILURE = new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { if (!future.isSuccess()) { future.getChannel().close(); } } }; /** * Invoked when the I/O operation associated with the {@link ChannelFuture} * has been completed. * * @param future The source {@link ChannelFuture} which called this * callback. */ void operationComplete(ChannelFuture future) throws Exception; }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/UpstreamChannelStateEvent.java0000644000175000017500000000656211216134140032142 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.jboss.netty.channel.Channels.*; /** * The default upstream {@link ChannelStateEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ * */ public class UpstreamChannelStateEvent implements ChannelStateEvent { private final Channel channel; private final ChannelState state; private final Object value; /** * Creates a new instance. */ public UpstreamChannelStateEvent( Channel channel, ChannelState state, Object value) { if (channel == null) { throw new NullPointerException("channel"); } if (state == null) { throw new NullPointerException("state"); } this.channel = channel; this.state = state; this.value = value; } public Channel getChannel() { return channel; } public ChannelFuture getFuture() { return succeededFuture(getChannel()); } public ChannelState getState() { return state; } public Object getValue() { return value; } @Override public String toString() { String channelString = getChannel().toString(); StringBuilder buf = new StringBuilder(channelString.length() + 64); buf.append(channelString); switch (getState()) { case OPEN: if (Boolean.TRUE.equals(getValue())) { buf.append(" OPEN"); } else { buf.append(" CLOSED"); } break; case BOUND: if (getValue() != null) { buf.append(" BOUND: "); buf.append(getValue()); } else { buf.append(" UNBOUND"); } break; case CONNECTED: if (getValue() != null) { buf.append(" CONNECTED: "); buf.append(getValue()); } else { buf.append(" DISCONNECTED"); } break; case INTEREST_OPS: buf.append(" INTEREST_CHANGED"); break; default: buf.append(getState().name()); buf.append(": "); buf.append(getValue()); } return buf.toString(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/Channels.java0000644000175000017500000012312211216134140026571 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; import java.util.Map; /** * A helper class which provides various convenience methods related with * {@link Channel}, {@link ChannelHandler}, and {@link ChannelPipeline}. * *

Factory methods

*

* It is always recommended to use the factory methods provided by * {@link Channels} rather than calling the constructor of the implementation * types. *

    *
  • {@link #pipeline()}
  • *
  • {@link #pipeline(ChannelPipeline)}
  • *
  • {@link #pipelineFactory(ChannelPipeline)}
  • *
  • {@link #succeededFuture(Channel)}
  • *
  • {@link #failedFuture(Channel, Throwable)}
  • *
* *

Upstream and downstream event generation

*

* Various event generation methods are provided to simplify the generation of * upstream events and downstream events. It is always recommended to use the * event generation methods provided by {@link Channels} rather than calling * {@link ChannelHandlerContext#sendUpstream(ChannelEvent)} or * {@link ChannelHandlerContext#sendDownstream(ChannelEvent)} by yourself. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @apiviz.landmark * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ */ public class Channels { // pipeline factory methods /** * Creates a new {@link ChannelPipeline}. */ public static ChannelPipeline pipeline() { return new DefaultChannelPipeline(); } /** * Creates a new {@link ChannelPipeline} which contains the same entries * with the specified {@code pipeline}. Please note that only the names * and the references of the {@link ChannelHandler}s will be copied; a new * {@link ChannelHandler} instance will never be created. */ public static ChannelPipeline pipeline(ChannelPipeline pipeline) { ChannelPipeline newPipeline = pipeline(); for (Map.Entry e: pipeline.toMap().entrySet()) { newPipeline.addLast(e.getKey(), e.getValue()); } return newPipeline; } /** * Creates a new {@link ChannelPipelineFactory} which creates a new * {@link ChannelPipeline} which contains the same entries with the * specified {@code pipeline}. Please note that only the names and the * references of the {@link ChannelHandler}s will be copied; a new * {@link ChannelHandler} instance will never be created. */ public static ChannelPipelineFactory pipelineFactory( final ChannelPipeline pipeline) { return new ChannelPipelineFactory() { public ChannelPipeline getPipeline() { return pipeline(pipeline); } }; } // future factory methods /** * Creates a new non-cancellable {@link ChannelFuture} for the specified * {@link Channel}. */ public static ChannelFuture future(Channel channel) { return future(channel, false); } /** * Creates a new {@link ChannelFuture} for the specified {@link Channel}. * * @param cancellable {@code true} if and only if the returned future * can be canceled by {@link ChannelFuture#cancel()} */ public static ChannelFuture future(Channel channel, boolean cancellable) { return new DefaultChannelFuture(channel, cancellable); } /** * Creates a new {@link ChannelFuture} which is already succeeded for the * specified {@link Channel}. */ public static ChannelFuture succeededFuture(Channel channel) { if (channel instanceof AbstractChannel) { return ((AbstractChannel) channel).getSucceededFuture(); } else { return new SucceededChannelFuture(channel); } } /** * Creates a new {@link ChannelFuture} which has failed already for the * specified {@link Channel}. * * @param cause the cause of the failure */ public static ChannelFuture failedFuture(Channel channel, Throwable cause) { return new FailedChannelFuture(channel, cause); } // event factory methods /** * @deprecated Instantiate {@link UpstreamMessageEvent} or {@link DownstreamMessageEvent} directly instead. * * Creates a new {@link MessageEvent} * * @param channel the channel which is associated with the event * @param future the future which will be notified when a message is sent * (only meaningful when the event is sent downstream) * @param message the received or sent message object * ('received' when the event is sent upstream, and * 'sent' when the event is sent downstream) */ @Deprecated public static MessageEvent messageEvent(Channel channel, ChannelFuture future, Object message) { return messageEvent(channel, future, message, null); } /** * @deprecated Instantiate {@link UpstreamMessageEvent} or {@link DownstreamMessageEvent} directly instead. * * Creates a new {@link MessageEvent} * * @param channel the channel which is associated with the event * @param future the future which will be notified when a message is sent * (only meaningful when the event is sent downstream) * @param message the received or sent message object * ('received' when the event is sent upstream, and * 'sent' when the event is sent downstream) * @param remoteAddress the source or destination address of the message * ('source' when the event is sent upstream, and * 'destination' when the event is sent downstream) */ @Deprecated public static MessageEvent messageEvent(Channel channel, ChannelFuture future, Object message, SocketAddress remoteAddress) { return new DownstreamMessageEvent(channel, future, message, remoteAddress); } // event emission methods /** * Sends a {@code "channelOpen"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. If the specified channel has a parent, * a {@code "childChannelOpen"} event will be sent, too. */ public static void fireChannelOpen(Channel channel) { // Notify the parent handler. if (channel.getParent() != null) { fireChildChannelStateChanged(channel.getParent(), channel); } channel.getPipeline().sendUpstream( new UpstreamChannelStateEvent( channel, ChannelState.OPEN, Boolean.TRUE)); } /** * Sends a {@code "channelOpen"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. Please note that * this method does not send a {@code "childChannelOpen"} event unlike * {@link #fireChannelOpen(Channel)} method. */ public static void fireChannelOpen(ChannelHandlerContext ctx) { ctx.sendUpstream(new UpstreamChannelStateEvent( ctx.getChannel(), ChannelState.OPEN, Boolean.TRUE)); } /** * @deprecated Use {@link #fireChannelOpen(ChannelHandlerContext)} instead. * * Sends a {@code "channelOpen"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. Please note that * this method does not send a {@code "childChannelOpen"} event unlike * {@link #fireChannelOpen(Channel)} method. */ @Deprecated public static void fireChannelOpen( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel) { fireChannelOpen(ctx); } /** * Sends a {@code "channelBound"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param localAddress * the local address where the specified channel is bound */ public static void fireChannelBound(Channel channel, SocketAddress localAddress) { channel.getPipeline().sendUpstream( new UpstreamChannelStateEvent( channel, ChannelState.BOUND, localAddress)); } /** * Sends a {@code "channelBound"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param localAddress * the local address where the specified channel is bound */ public static void fireChannelBound(ChannelHandlerContext ctx, SocketAddress localAddress) { ctx.sendUpstream(new UpstreamChannelStateEvent( ctx.getChannel(), ChannelState.BOUND, localAddress)); } /** * @deprecated Use {@link #fireChannelBound(ChannelHandlerContext, SocketAddress)} instead. * * Sends a {@code "channelBound"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param localAddress * the local address where the specified channel is bound */ @Deprecated public static void fireChannelBound( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, SocketAddress localAddress) { fireChannelBound(ctx, localAddress); } /** * Sends a {@code "channelConnected"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param remoteAddress * the remote address where the specified channel is connected */ public static void fireChannelConnected(Channel channel, SocketAddress remoteAddress) { channel.getPipeline().sendUpstream( new UpstreamChannelStateEvent( channel, ChannelState.CONNECTED, remoteAddress)); } /** * Sends a {@code "channelConnected"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param remoteAddress * the remote address where the specified channel is connected */ public static void fireChannelConnected(ChannelHandlerContext ctx, SocketAddress remoteAddress) { ctx.sendUpstream(new UpstreamChannelStateEvent( ctx.getChannel(), ChannelState.CONNECTED, remoteAddress)); } /** * @deprecated Use {@link #fireChannelConnected(ChannelHandlerContext, SocketAddress)} instead. * * Sends a {@code "channelConnected"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param remoteAddress * the remote address where the specified channel is connected */ @Deprecated public static void fireChannelConnected( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, SocketAddress remoteAddress) { fireChannelConnected(ctx, remoteAddress); } /** * Sends a {@code "messageReceived"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param message the received message */ public static void fireMessageReceived(Channel channel, Object message) { fireMessageReceived(channel, message, null); } /** * Sends a {@code "messageReceived"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel} belongs. * * @param message the received message * @param remoteAddress the remote address where the received message * came from */ public static void fireMessageReceived(Channel channel, Object message, SocketAddress remoteAddress) { channel.getPipeline().sendUpstream( new UpstreamMessageEvent(channel, message, remoteAddress)); } /** * Sends a {@code "messageReceived"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param message the received message */ public static void fireMessageReceived(ChannelHandlerContext ctx, Object message) { ctx.sendUpstream(new UpstreamMessageEvent(ctx.getChannel(), message, null)); } /** * @deprecated Use {@link #fireMessageReceived(ChannelHandlerContext, Object)} instead. * * Sends a {@code "messageReceived"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param message the received message */ @Deprecated public static void fireMessageReceived( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, Object message) { fireMessageReceived(ctx, message); } /** * Sends a {@code "messageReceived"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param message the received message * @param remoteAddress the remote address where the received message * came from */ public static void fireMessageReceived( ChannelHandlerContext ctx, Object message, SocketAddress remoteAddress) { ctx.sendUpstream(new UpstreamMessageEvent( ctx.getChannel(), message, remoteAddress)); } /** * @deprecated Use {@link #fireMessageReceived(ChannelHandlerContext, Object, SocketAddress)} instead. * * Sends a {@code "messageReceived"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param message the received message * @param remoteAddress the remote address where the received message * came from */ @Deprecated public static void fireMessageReceived( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, Object message, SocketAddress remoteAddress) { fireMessageReceived(ctx, message, remoteAddress); } /** * Sends a {@code "writeComplete"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. */ public static void fireWriteComplete(Channel channel, int amount) { if (amount == 0) { return; } channel.getPipeline().sendUpstream( new DefaultWriteCompletionEvent(channel, amount)); } /** * Sends a {@code "writeComplete"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ public static void fireWriteComplete(ChannelHandlerContext ctx, int amount) { ctx.sendUpstream(new DefaultWriteCompletionEvent(ctx.getChannel(), amount)); } /** * Sends a {@code "channelInterestChanged"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. */ public static void fireChannelInterestChanged(Channel channel) { channel.getPipeline().sendUpstream( new UpstreamChannelStateEvent( channel, ChannelState.INTEREST_OPS, Channel.OP_READ)); } /** * @deprecated Use {@link #fireChannelInterestChanged(Channel)} instead. * * Sends a {@code "channelInterestChanged"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param interestOps the new interestOps */ @Deprecated public static void fireChannelInterestChanged( Channel channel, @SuppressWarnings("unused") int interestOps) { fireChannelInterestChanged(channel); } /** * Sends a {@code "channelInterestChanged"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ public static void fireChannelInterestChanged( ChannelHandlerContext ctx) { ctx.sendUpstream( new UpstreamChannelStateEvent( ctx.getChannel(), ChannelState.INTEREST_OPS, Channel.OP_READ)); } /** * @deprecated Use {@link #fireChannelInterestChanged(ChannelHandlerContext)} instead. * * Sends a {@code "channelInterestChanged"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param interestOps the new interestOps */ @Deprecated public static void fireChannelInterestChanged( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, @SuppressWarnings("unused") int interestOps) { fireChannelInterestChanged(ctx); } /** * Sends a {@code "channelDisconnected"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. */ public static void fireChannelDisconnected(Channel channel) { channel.getPipeline().sendUpstream( new UpstreamChannelStateEvent( channel, ChannelState.CONNECTED, null)); } /** * Sends a {@code "channelDisconnected"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ public static void fireChannelDisconnected(ChannelHandlerContext ctx) { ctx.sendUpstream(new UpstreamChannelStateEvent( ctx.getChannel(), ChannelState.CONNECTED, null)); } /** * @deprecated Use {@link #fireChannelDisconnected(ChannelHandlerContext)} instead. * * Sends a {@code "channelDisconnected"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ @Deprecated public static void fireChannelDisconnected( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel) { fireChannelDisconnected(ctx); } /** * Sends a {@code "channelUnbound"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. */ public static void fireChannelUnbound(Channel channel) { channel.getPipeline().sendUpstream(new UpstreamChannelStateEvent( channel, ChannelState.BOUND, null)); } /** * Sends a {@code "channelUnbound"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ public static void fireChannelUnbound(ChannelHandlerContext ctx) { ctx.sendUpstream(new UpstreamChannelStateEvent( ctx.getChannel(), ChannelState.BOUND, null)); } /** * @deprecated Use {@link #fireChannelUnbound(ChannelHandlerContext)} instead. * * Sends a {@code "channelUnbound"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ @Deprecated public static void fireChannelUnbound( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel) { fireChannelUnbound(ctx); } /** * Sends a {@code "channelClosed"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. */ public static void fireChannelClosed(Channel channel) { channel.getPipeline().sendUpstream( new UpstreamChannelStateEvent( channel, ChannelState.OPEN, Boolean.FALSE)); // Notify the parent handler. if (channel.getParent() != null) { fireChildChannelStateChanged(channel.getParent(), channel); } } /** * Sends a {@code "channelClosed"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ public static void fireChannelClosed(ChannelHandlerContext ctx) { ctx.sendUpstream( new UpstreamChannelStateEvent( ctx.getChannel(), ChannelState.OPEN, Boolean.FALSE)); } /** * @deprecated Use {@link #fireChannelClosed(ChannelHandlerContext)}. * * Sends a {@code "channelClosed"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ @Deprecated public static void fireChannelClosed( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel) { fireChannelClosed(ctx); } /** * Sends a {@code "exceptionCaught"} event to the first * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. */ public static void fireExceptionCaught(Channel channel, Throwable cause) { channel.getPipeline().sendUpstream( new DefaultExceptionEvent(channel, cause)); } /** * Sends a {@code "exceptionCaught"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ public static void fireExceptionCaught(ChannelHandlerContext ctx, Throwable cause) { ctx.sendUpstream(new DefaultExceptionEvent(ctx.getChannel(), cause)); } /** * @deprecated Use {@link #fireExceptionCaught(ChannelHandlerContext, Throwable)} instead. * * Sends a {@code "exceptionCaught"} event to the next * {@link ChannelUpstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. */ @Deprecated public static void fireExceptionCaught( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, Throwable cause) { fireExceptionCaught(ctx, cause); } private static void fireChildChannelStateChanged( Channel channel, Channel childChannel) { channel.getPipeline().sendUpstream( new DefaultChildChannelStateEvent(channel, childChannel)); } /** * Sends a {@code "bind"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to bind * @param localAddress the local address to bind to * * @return the {@link ChannelFuture} which will be notified when the * bind operation is done */ public static ChannelFuture bind(Channel channel, SocketAddress localAddress) { if (localAddress == null) { throw new NullPointerException("localAddress"); } ChannelFuture future = future(channel); channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.BOUND, localAddress)); return future; } /** * Sends a {@code "bind"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified when the bind * operation is done * @param localAddress the local address to bind to */ public static void bind( ChannelHandlerContext ctx, ChannelFuture future, SocketAddress localAddress) { if (localAddress == null) { throw new NullPointerException("localAddress"); } ctx.sendDownstream(new DownstreamChannelStateEvent( ctx.getChannel(), future, ChannelState.BOUND, localAddress)); } /** * @deprecated Use {@link #bind(ChannelHandlerContext, ChannelFuture, SocketAddress)} instead. * * Sends a {@code "bind"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to bind * @param future the future which will be notified when the bind * operation is done * @param localAddress the local address to bind to */ @Deprecated public static void bind( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future, SocketAddress localAddress) { bind(ctx, future, localAddress); } /** * Sends a {@code "unbind"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified when the unbind * operation is done */ public static void unbind(ChannelHandlerContext ctx, ChannelFuture future) { ctx.sendDownstream(new DownstreamChannelStateEvent( ctx.getChannel(), future, ChannelState.BOUND, null)); } /** * @deprecated Use {@link #unbind(ChannelHandlerContext, ChannelFuture)} instead. * * Sends a {@code "unbind"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to unbind * @param future the future which will be notified when the unbind * operation is done */ @Deprecated public static void unbind( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future) { unbind(ctx, future); } /** * Sends a {@code "unbind"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to unbind * * @return the {@link ChannelFuture} which will be notified when the * unbind operation is done */ public static ChannelFuture unbind(Channel channel) { ChannelFuture future = future(channel); channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.BOUND, null)); return future; } /** * Sends a {@code "connect"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to attempt a connection * @param remoteAddress the remote address to connect to * * @return the {@link ChannelFuture} which will be notified when the * connection attempt is done */ public static ChannelFuture connect(Channel channel, SocketAddress remoteAddress) { if (remoteAddress == null) { throw new NullPointerException("remoteAddress"); } ChannelFuture future = future(channel, true); channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.CONNECTED, remoteAddress)); return future; } /** * Sends a {@code "connect"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified when the connection * attempt is done * @param remoteAddress the remote address to connect to */ public static void connect( ChannelHandlerContext ctx, ChannelFuture future, SocketAddress remoteAddress) { if (remoteAddress == null) { throw new NullPointerException("remoteAddress"); } ctx.sendDownstream(new DownstreamChannelStateEvent( ctx.getChannel(), future, ChannelState.CONNECTED, remoteAddress)); } /** * @deprecated Use {@link #connect(ChannelHandlerContext, ChannelFuture, SocketAddress)} instead. * * Sends a {@code "connect"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to attempt a connection * @param future the future which will be notified when the connection * attempt is done * @param remoteAddress the remote address to connect to */ @Deprecated public static void connect( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future, SocketAddress remoteAddress) { connect(ctx, future, remoteAddress); } /** * Sends a {@code "write"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to write a message * @param message the message to write to the channel * * @return the {@link ChannelFuture} which will be notified when the * write operation is done */ public static ChannelFuture write(Channel channel, Object message) { return write(channel, message, null); } /** * Sends a {@code "write"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified when the write * operation is done */ public static void write( ChannelHandlerContext ctx, ChannelFuture future, Object message) { write(ctx, future, message, null); } /** * @deprecated Use {@link #write(ChannelHandlerContext, ChannelFuture, Object)} instead. * * Sends a {@code "write"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to write a message * @param future the future which will be notified when the write * operation is done */ @Deprecated public static void write( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future, Object message) { write(ctx, future, message, null); } /** * Sends a {@code "write"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to write a message * @param message the message to write to the channel * @param remoteAddress the destination of the message. * {@code null} to use the default remote address * * @return the {@link ChannelFuture} which will be notified when the * write operation is done */ public static ChannelFuture write(Channel channel, Object message, SocketAddress remoteAddress) { ChannelFuture future = future(channel); channel.getPipeline().sendDownstream( new DownstreamMessageEvent(channel, future, message, remoteAddress)); return future; } /** * Sends a {@code "write"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified when the write * operation is done * @param message the message to write to the channel * @param remoteAddress the destination of the message. * {@code null} to use the default remote address. */ public static void write( ChannelHandlerContext ctx, ChannelFuture future, Object message, SocketAddress remoteAddress) { ctx.sendDownstream( new DownstreamMessageEvent(ctx.getChannel(), future, message, remoteAddress)); } /** * @deprecated Use {@link #write(ChannelHandlerContext, ChannelFuture, Object, SocketAddress)} instead. * * Sends a {@code "write"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to write a message * @param future the future which will be notified when the write * operation is done * @param message the message to write to the channel * @param remoteAddress the destination of the message. * {@code null} to use the default remote address. */ @Deprecated public static void write( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future, Object message, SocketAddress remoteAddress) { write(ctx, future, message, remoteAddress); } /** * Sends a {@code "setInterestOps"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to change its interestOps * @param interestOps the new interestOps * * @return the {@link ChannelFuture} which will be notified when the * interestOps is changed */ public static ChannelFuture setInterestOps(Channel channel, int interestOps) { validateInterestOps(interestOps); interestOps = filterDownstreamInterestOps(interestOps); ChannelFuture future = future(channel); channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.INTEREST_OPS, Integer.valueOf(interestOps))); return future; } /** * Sends a {@code "setInterestOps"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified when the interestOps is * changed. */ public static void setInterestOps( ChannelHandlerContext ctx, ChannelFuture future, int interestOps) { validateInterestOps(interestOps); interestOps = filterDownstreamInterestOps(interestOps); ctx.sendDownstream( new DownstreamChannelStateEvent( ctx.getChannel(), future, ChannelState.INTEREST_OPS, Integer.valueOf(interestOps))); } /** * @deprecated Use {@link #setInterestOps(ChannelHandlerContext, ChannelFuture, int)} instead. * * Sends a {@code "setInterestOps"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to change the interestOps * @param future the future which will be notified when the interestOps is * changed. */ @Deprecated public static void setInterestOps( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future, int interestOps) { setInterestOps(ctx, future, interestOps); } /** * Sends a {@code "disconnect"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to disconnect * * @return the {@link ChannelFuture} which will be notified on disconnection */ public static ChannelFuture disconnect(Channel channel) { ChannelFuture future = future(channel); channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.CONNECTED, null)); return future; } /** * Sends a {@code "disconnect"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified on disconnection */ public static void disconnect( ChannelHandlerContext ctx, ChannelFuture future) { ctx.sendDownstream(new DownstreamChannelStateEvent( ctx.getChannel(), future, ChannelState.CONNECTED, null)); } /** * @deprecated Use {@link #disconnect(ChannelHandlerContext, ChannelFuture)} instead. * * Sends a {@code "disconnect"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to disconnect * @param future the future which will be notified on disconnection */ @Deprecated public static void disconnect( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future) { disconnect(ctx, future); } /** * Sends a {@code "close"} request to the last * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} of * the specified {@link Channel}. * * @param channel the channel to close * * @return the {@link ChannelFuture} which will be notified on closure */ public static ChannelFuture close(Channel channel) { ChannelFuture future = channel.getCloseFuture(); channel.getPipeline().sendDownstream(new DownstreamChannelStateEvent( channel, future, ChannelState.OPEN, Boolean.FALSE)); return future; } /** * Sends a {@code "close"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param future the future which will be notified on closure */ public static void close( ChannelHandlerContext ctx, ChannelFuture future) { ctx.sendDownstream(new DownstreamChannelStateEvent( ctx.getChannel(), future, ChannelState.OPEN, Boolean.FALSE)); } /** * @deprecated Use {@link #close(ChannelHandlerContext, ChannelFuture)} instead. * * Sends a {@code "close"} request to the previous * {@link ChannelDownstreamHandler} in the {@link ChannelPipeline} where * the specified {@link ChannelHandlerContext} belongs. * * @param ctx the context * @param channel the channel to close * @param future the future which will be notified on closure */ @Deprecated public static void close( ChannelHandlerContext ctx, @SuppressWarnings("unused") Channel channel, ChannelFuture future) { close(ctx, future); } private static void validateInterestOps(int interestOps) { switch (interestOps) { case Channel.OP_NONE: case Channel.OP_READ: case Channel.OP_WRITE: case Channel.OP_READ_WRITE: break; default: throw new IllegalArgumentException( "Invalid interestOps: " + interestOps); } } private static int filterDownstreamInterestOps(int interestOps) { return interestOps & ~Channel.OP_WRITE; } private Channels() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelStateEvent.java0000644000175000017500000000407011107230242030410 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link ChannelEvent} which represents the change of the {@link Channel} * state. It can mean the notification of a change or the request for a * change, depending on whether it is an upstream event or a downstream event * respectively. Please refer to the {@link ChannelEvent} documentation to * find out what an upstream event and a downstream event are and what * fundamental differences they have. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 473 $, $Date: 2008-11-14 00:02:42 -0800 (Fri, 14 Nov 2008) $ * * @apiviz.has org.jboss.netty.channel.ChannelState */ public interface ChannelStateEvent extends ChannelEvent { /** * Returns the changed property of the {@link Channel}. */ ChannelState getState(); /** * Returns the value of the changed property of the {@link Channel}. * Please refer to {@link ChannelState} documentation to find out the * allowed values for each property. */ Object getValue(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DownstreamMessageEvent.java0000644000175000017500000000557011216134140031476 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; import org.jboss.netty.util.internal.StringUtil; /** * The default downstream {@link MessageEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ * */ public class DownstreamMessageEvent implements MessageEvent { private final Channel channel; private final ChannelFuture future; private final Object message; private final SocketAddress remoteAddress; /** * Creates a new instance. */ public DownstreamMessageEvent( Channel channel, ChannelFuture future, Object message, SocketAddress remoteAddress) { if (channel == null) { throw new NullPointerException("channel"); } if (future == null) { throw new NullPointerException("future"); } if (message == null) { throw new NullPointerException("message"); } this.channel = channel; this.future = future; this.message = message; this.remoteAddress = remoteAddress; } public Channel getChannel() { return channel; } public ChannelFuture getFuture() { return future; } public Object getMessage() { return message; } public SocketAddress getRemoteAddress() { return remoteAddress; } @Override public String toString() { if (getRemoteAddress() == null) { return getChannel().toString() + " WRITE: " + StringUtil.stripControlCharacters(getMessage()); } else { return getChannel().toString() + " WRITE: " + StringUtil.stripControlCharacters(getMessage()) + ", " + getRemoteAddress(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultExceptionEvent.java0000644000175000017500000000437411165336702031325 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.util.internal.StackTraceSimplifier; /** * The default {@link ExceptionEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class DefaultExceptionEvent implements ExceptionEvent { private final Channel channel; private final Throwable cause; /** * Creates a new instance. */ public DefaultExceptionEvent(Channel channel, Throwable cause) { if (channel == null) { throw new NullPointerException("channel"); } if (cause == null) { throw new NullPointerException("cause"); } this.channel = channel; this.cause = cause; StackTraceSimplifier.simplify(cause); } public Channel getChannel() { return channel; } public ChannelFuture getFuture() { return succeededFuture(getChannel()); } public Throwable getCause() { return cause; } @Override public String toString() { return getChannel().toString() + " EXCEPTION: " + cause; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelPipelineException.java0000644000175000017500000000414011057213775031770 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link ChannelException} which is thrown when a {@link ChannelPipeline} * failed to process a {@link ChannelEvent} or when a {@link ChannelPipelineFactory} * failed to initialize a {@link ChannelPipeline}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 184 $, $Date: 2008-09-02 03:39:57 -0700 (Tue, 02 Sep 2008) $ * * @apiviz.hidden */ public class ChannelPipelineException extends ChannelException { private static final long serialVersionUID = 3379174210419885980L; /** * Creates a new instance. */ public ChannelPipelineException() { super(); } /** * Creates a new instance. */ public ChannelPipelineException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public ChannelPipelineException(String message) { super(message); } /** * Creates a new instance. */ public ChannelPipelineException(Throwable cause) { super(cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/AbstractChannelSink.java0000644000175000017500000000416511066406360030735 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.jboss.netty.channel.Channels.*; /** * A skeletal {@link ChannelSink} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 303 $, $Date: 2008-09-24 02:48:32 -0700 (Wed, 24 Sep 2008) $ */ public abstract class AbstractChannelSink implements ChannelSink { /** * Creates a new instance. */ protected AbstractChannelSink() { super(); } /** * Sends an {@link ExceptionEvent} upstream with the specified * {@code cause}. * * @param event the {@link ChannelEvent} which caused a * {@link ChannelHandler} to raise an exception * @param cause the exception raised by a {@link ChannelHandler} */ public void exceptionCaught(ChannelPipeline pipeline, ChannelEvent event, ChannelPipelineException cause) throws Exception { Throwable actualCause = cause.getCause(); if (actualCause == null) { actualCause = cause; } fireExceptionCaught(event.getChannel(), actualCause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultChannelPipeline.java0000644000175000017500000006342411172035524031420 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.jboss.netty.channel.ChannelPipelineCoverage.*; import java.lang.annotation.AnnotationFormatError; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.NoSuchElementException; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * The default {@link ChannelPipeline} implementation. It is recommended * to use {@link Channels#pipeline()} to create a new {@link ChannelPipeline} * instance rather than calling the constructor directly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1212 $, $Date: 2009-04-17 01:18:28 -0700 (Fri, 17 Apr 2009) $ * */ public class DefaultChannelPipeline implements ChannelPipeline { static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelPipeline.class); private static final ChannelSink discardingSink = new DiscardingChannelSink(); private volatile Channel channel; private volatile ChannelSink sink; private volatile DefaultChannelHandlerContext head; private volatile DefaultChannelHandlerContext tail; private final Map name2ctx = new HashMap(4); /** * Creates a new empty pipeline. */ public DefaultChannelPipeline() { super(); } public Channel getChannel() { return channel; } public ChannelSink getSink() { ChannelSink sink = this.sink; if (sink == null) { return discardingSink; } return sink; } public void attach(Channel channel, ChannelSink sink) { if (channel == null) { throw new NullPointerException("channel"); } if (sink == null) { throw new NullPointerException("sink"); } if (this.channel != null || this.sink != null) { throw new IllegalStateException("attached already"); } this.channel = channel; this.sink = sink; } public boolean isAttached() { return sink != null; } public synchronized void addFirst(String name, ChannelHandler handler) { if (name2ctx.isEmpty()) { init(name, handler); } else { checkDuplicateName(name); DefaultChannelHandlerContext oldHead = head; DefaultChannelHandlerContext newHead = new DefaultChannelHandlerContext(null, oldHead, name, handler); callBeforeAdd(newHead); oldHead.prev = newHead; head = newHead; name2ctx.put(name, newHead); callAfterAdd(newHead); } } public synchronized void addLast(String name, ChannelHandler handler) { if (name2ctx.isEmpty()) { init(name, handler); } else { checkDuplicateName(name); DefaultChannelHandlerContext oldTail = tail; DefaultChannelHandlerContext newTail = new DefaultChannelHandlerContext(oldTail, null, name, handler); callBeforeAdd(newTail); oldTail.next = newTail; tail = newTail; name2ctx.put(name, newTail); callAfterAdd(newTail); } } public synchronized void addBefore(String baseName, String name, ChannelHandler handler) { DefaultChannelHandlerContext ctx = getContextOrDie(baseName); if (ctx == head) { addFirst(name, handler); } else { checkDuplicateName(name); DefaultChannelHandlerContext newCtx = new DefaultChannelHandlerContext(ctx.prev, ctx, name, handler); callBeforeAdd(newCtx); ctx.prev.next = newCtx; ctx.prev = newCtx; name2ctx.put(name, newCtx); callAfterAdd(newCtx); } } public synchronized void addAfter(String baseName, String name, ChannelHandler handler) { DefaultChannelHandlerContext ctx = getContextOrDie(baseName); if (ctx == tail) { addLast(name, handler); } else { checkDuplicateName(name); DefaultChannelHandlerContext newCtx = new DefaultChannelHandlerContext(ctx, ctx.next, name, handler); callBeforeAdd(newCtx); ctx.next.prev = newCtx; ctx.next = newCtx; name2ctx.put(name, newCtx); callAfterAdd(newCtx); } } public synchronized void remove(ChannelHandler handler) { remove(getContextOrDie(handler)); } public synchronized ChannelHandler remove(String name) { return remove(getContextOrDie(name)).getHandler(); } @SuppressWarnings("unchecked") public synchronized T remove(Class handlerType) { return (T) remove(getContextOrDie(handlerType)).getHandler(); } private DefaultChannelHandlerContext remove(DefaultChannelHandlerContext ctx) { if (head == tail) { head = tail = null; name2ctx.clear(); } else if (ctx == head) { removeFirst(); } else if (ctx == tail) { removeLast(); } else { callBeforeRemove(ctx); DefaultChannelHandlerContext prev = ctx.prev; DefaultChannelHandlerContext next = ctx.next; prev.next = next; next.prev = prev; name2ctx.remove(ctx.getName()); callAfterRemove(ctx); } return ctx; } public synchronized ChannelHandler removeFirst() { if (name2ctx.isEmpty()) { throw new NoSuchElementException(); } DefaultChannelHandlerContext oldHead = head; if (oldHead == null) { throw new NoSuchElementException(); } callBeforeRemove(oldHead); if (oldHead.next == null) { head = tail = null; name2ctx.clear(); } else { oldHead.next.prev = null; head = oldHead.next; name2ctx.remove(oldHead.getName()); } callAfterRemove(oldHead); return oldHead.getHandler(); } public synchronized ChannelHandler removeLast() { if (name2ctx.isEmpty()) { throw new NoSuchElementException(); } DefaultChannelHandlerContext oldTail = tail; if (oldTail == null) { throw new NoSuchElementException(); } callBeforeRemove(oldTail); if (oldTail.prev == null) { head = tail = null; name2ctx.clear(); } else { oldTail.prev.next = null; tail = oldTail.prev; name2ctx.remove(oldTail.getName()); } callBeforeRemove(oldTail); return oldTail.getHandler(); } public synchronized void replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler) { replace(getContextOrDie(oldHandler), newName, newHandler); } public synchronized ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler) { return replace(getContextOrDie(oldName), newName, newHandler); } @SuppressWarnings("unchecked") public synchronized T replace( Class oldHandlerType, String newName, ChannelHandler newHandler) { return (T) replace(getContextOrDie(oldHandlerType), newName, newHandler); } private ChannelHandler replace(DefaultChannelHandlerContext ctx, String newName, ChannelHandler newHandler) { if (ctx == head) { removeFirst(); addFirst(newName, newHandler); } else if (ctx == tail) { removeLast(); addLast(newName, newHandler); } else { boolean sameName = ctx.getName().equals(newName); if (!sameName) { checkDuplicateName(newName); } DefaultChannelHandlerContext prev = ctx.prev; DefaultChannelHandlerContext next = ctx.next; DefaultChannelHandlerContext newCtx = new DefaultChannelHandlerContext(prev, next, newName, newHandler); callBeforeRemove(ctx); callBeforeAdd(newCtx); prev.next = newCtx; next.prev = newCtx; if (!sameName) { name2ctx.remove(ctx.getName()); name2ctx.put(newName, newCtx); } ChannelHandlerLifeCycleException removeException = null; ChannelHandlerLifeCycleException addException = null; boolean removed = false; try { callAfterRemove(ctx); removed = true; } catch (ChannelHandlerLifeCycleException e) { removeException = e; } boolean added = false; try { callAfterAdd(newCtx); added = true; } catch (ChannelHandlerLifeCycleException e) { addException = e; } if (!removed && !added) { logger.warn(removeException.getMessage(), removeException); logger.warn(addException.getMessage(), addException); throw new ChannelHandlerLifeCycleException( "Both " + ctx.getHandler().getClass().getName() + ".afterRemove() and " + newCtx.getHandler().getClass().getName() + ".afterAdd() failed; see logs."); } else if (!removed) { throw removeException; } else if (!added) { throw addException; } } return ctx.getHandler(); } private void callBeforeAdd(ChannelHandlerContext ctx) { if (!(ctx.getHandler() instanceof LifeCycleAwareChannelHandler)) { return; } if (!isAttached()) { return; } LifeCycleAwareChannelHandler h = (LifeCycleAwareChannelHandler) ctx.getHandler(); try { h.beforeAdd(ctx); } catch (Throwable t) { throw new ChannelHandlerLifeCycleException( h.getClass().getName() + ".beforeAdd() has thrown an exception; not adding.", t); } } private void callAfterAdd(ChannelHandlerContext ctx) { if (!(ctx.getHandler() instanceof LifeCycleAwareChannelHandler)) { return; } if (!isAttached()) { return; } LifeCycleAwareChannelHandler h = (LifeCycleAwareChannelHandler) ctx.getHandler(); try { h.afterAdd(ctx); } catch (Throwable t) { boolean removed = false; try { remove((DefaultChannelHandlerContext) ctx); removed = true; } catch (Throwable t2) { logger.warn("Failed to remove a handler: " + ctx.getName(), t2); } if (removed) { throw new ChannelHandlerLifeCycleException( h.getClass().getName() + ".afterAdd() has thrown an exception; removed.", t); } else { throw new ChannelHandlerLifeCycleException( h.getClass().getName() + ".afterAdd() has thrown an exception; also failed to remove.", t); } } } private void callBeforeRemove(ChannelHandlerContext ctx) { if (!(ctx.getHandler() instanceof LifeCycleAwareChannelHandler)) { return; } if (!isAttached()) { return; } LifeCycleAwareChannelHandler h = (LifeCycleAwareChannelHandler) ctx.getHandler(); try { h.beforeRemove(ctx); } catch (Throwable t) { throw new ChannelHandlerLifeCycleException( h.getClass().getName() + ".beforeRemove() has thrown an exception; not removing.", t); } } private void callAfterRemove(ChannelHandlerContext ctx) { if (!(ctx.getHandler() instanceof LifeCycleAwareChannelHandler)) { return; } if (!isAttached()) { return; } LifeCycleAwareChannelHandler h = (LifeCycleAwareChannelHandler) ctx.getHandler(); try { h.afterRemove(ctx); } catch (Throwable t) { throw new ChannelHandlerLifeCycleException( h.getClass().getName() + ".afterRemove() has thrown an exception.", t); } } public synchronized ChannelHandler getFirst() { DefaultChannelHandlerContext head = this.head; if (head == null) { return null; } return head.getHandler(); } public synchronized ChannelHandler getLast() { DefaultChannelHandlerContext tail = this.tail; if (tail == null) { return null; } return tail.getHandler(); } public synchronized ChannelHandler get(String name) { DefaultChannelHandlerContext ctx = name2ctx.get(name); if (ctx == null) { return null; } else { return ctx.getHandler(); } } @SuppressWarnings("unchecked") public synchronized T get(Class handlerType) { ChannelHandlerContext ctx = getContext(handlerType); if (ctx == null) { return null; } else { return (T) ctx.getHandler(); } } public synchronized ChannelHandlerContext getContext(String name) { if (name == null) { throw new NullPointerException("name"); } return name2ctx.get(name); } public synchronized ChannelHandlerContext getContext(ChannelHandler handler) { if (handler == null) { throw new NullPointerException("handler"); } if (name2ctx.isEmpty()) { return null; } DefaultChannelHandlerContext ctx = head; for (;;) { if (ctx.getHandler() == handler) { return ctx; } ctx = ctx.next; if (ctx == null) { break; } } return null; } public synchronized ChannelHandlerContext getContext( Class handlerType) { if (name2ctx.isEmpty()) { return null; } DefaultChannelHandlerContext ctx = head; for (;;) { if (handlerType.isAssignableFrom(ctx.getHandler().getClass())) { return ctx; } ctx = ctx.next; if (ctx == null) { break; } } return null; } public Map toMap() { Map map = new LinkedHashMap(); if (name2ctx.isEmpty()) { return map; } DefaultChannelHandlerContext ctx = head; for (;;) { map.put(ctx.getName(), ctx.getHandler()); ctx = ctx.next; if (ctx == null) { break; } } return map; } /** * Returns the {@link String} representation of this pipeline. */ @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(getClass().getSimpleName()); buf.append('{'); DefaultChannelHandlerContext ctx = head; for (;;) { buf.append('('); buf.append(ctx.getName()); buf.append(" = "); buf.append(ctx.getHandler().getClass().getName()); buf.append(')'); ctx = ctx.next; if (ctx == null) { break; } buf.append(", "); } buf.append('}'); return buf.toString(); } public void sendUpstream(ChannelEvent e) { DefaultChannelHandlerContext head = getActualUpstreamContext(this.head); if (head == null) { logger.warn( "The pipeline contains no upstream handlers; discarding: " + e); return; } sendUpstream(head, e); } void sendUpstream(DefaultChannelHandlerContext ctx, ChannelEvent e) { try { ((ChannelUpstreamHandler) ctx.getHandler()).handleUpstream(ctx, e); } catch (Throwable t) { notifyHandlerException(e, t); } } public void sendDownstream(ChannelEvent e) { DefaultChannelHandlerContext tail = getActualDownstreamContext(this.tail); if (tail == null) { try { getSink().eventSunk(this, e); return; } catch (Throwable t) { notifyHandlerException(e, t); return; } } sendDownstream(tail, e); } void sendDownstream(DefaultChannelHandlerContext ctx, ChannelEvent e) { try { ((ChannelDownstreamHandler) ctx.getHandler()).handleDownstream(ctx, e); } catch (Throwable t) { notifyHandlerException(e, t); } } DefaultChannelHandlerContext getActualUpstreamContext(DefaultChannelHandlerContext ctx) { if (ctx == null) { return null; } DefaultChannelHandlerContext realCtx = ctx; while (!realCtx.canHandleUpstream()) { realCtx = realCtx.next; if (realCtx == null) { return null; } } return realCtx; } DefaultChannelHandlerContext getActualDownstreamContext(DefaultChannelHandlerContext ctx) { if (ctx == null) { return null; } DefaultChannelHandlerContext realCtx = ctx; while (!realCtx.canHandleDownstream()) { realCtx = realCtx.prev; if (realCtx == null) { return null; } } return realCtx; } protected void notifyHandlerException(ChannelEvent e, Throwable t) { if (e instanceof ExceptionEvent) { logger.warn( "An exception was thrown by a user handler " + "while handling an exception event (" + e + ")", t); return; } ChannelPipelineException pe; if (t instanceof ChannelPipelineException) { pe = (ChannelPipelineException) t; } else { pe = new ChannelPipelineException(t); } try { sink.exceptionCaught(this, e, pe); } catch (Exception e1) { logger.warn("An exception was thrown by an exception handler.", e1); } } private void init(String name, ChannelHandler handler) { DefaultChannelHandlerContext ctx = new DefaultChannelHandlerContext(null, null, name, handler); head = tail = ctx; name2ctx.clear(); name2ctx.put(name, ctx); } private void checkDuplicateName(String name) { if (name2ctx.containsKey(name)) { throw new IllegalArgumentException("Duplicate handler name."); } } private DefaultChannelHandlerContext getContextOrDie(String name) { DefaultChannelHandlerContext ctx = (DefaultChannelHandlerContext) getContext(name); if (ctx == null) { throw new NoSuchElementException(name); } else { return ctx; } } private DefaultChannelHandlerContext getContextOrDie(ChannelHandler handler) { DefaultChannelHandlerContext ctx = (DefaultChannelHandlerContext) getContext(handler); if (ctx == null) { throw new NoSuchElementException(handler.getClass().getName()); } else { return ctx; } } private DefaultChannelHandlerContext getContextOrDie(Class handlerType) { DefaultChannelHandlerContext ctx = (DefaultChannelHandlerContext) getContext(handlerType); if (ctx == null) { throw new NoSuchElementException(handlerType.getName()); } else { return ctx; } } private final class DefaultChannelHandlerContext implements ChannelHandlerContext { volatile DefaultChannelHandlerContext next; volatile DefaultChannelHandlerContext prev; private final String name; private final ChannelHandler handler; private final boolean canHandleUpstream; private final boolean canHandleDownstream; private volatile Object attachment; DefaultChannelHandlerContext( DefaultChannelHandlerContext prev, DefaultChannelHandlerContext next, String name, ChannelHandler handler) { if (name == null) { throw new NullPointerException("name"); } if (handler == null) { throw new NullPointerException("handler"); } canHandleUpstream = handler instanceof ChannelUpstreamHandler; canHandleDownstream = handler instanceof ChannelDownstreamHandler; if (!canHandleUpstream && !canHandleDownstream) { throw new IllegalArgumentException( "handler must be either " + ChannelUpstreamHandler.class.getName() + " or " + ChannelDownstreamHandler.class.getName() + '.'); } ChannelPipelineCoverage coverage = handler.getClass().getAnnotation(ChannelPipelineCoverage.class); if (coverage == null) { logger.warn( "Handler '" + handler.getClass().getName() + "' does not have a '" + ChannelPipelineCoverage.class.getSimpleName() + "' annotation with its class declaration. " + "It is strongly recommended to add the annotation " + "for a documentation purpose to tell if a single " + "handler instance can handle more than one pipeline " + "(\"" + ALL + "\") or not (\"" + ONE + "\")"); } else { String coverageValue = coverage.value(); if (coverageValue == null) { throw new AnnotationFormatError( ChannelPipelineCoverage.class.getSimpleName() + " annotation value is undefined for type: " + handler.getClass().getName()); } if (!coverageValue.equals(ALL) && !coverageValue.equals(ONE)) { throw new AnnotationFormatError( ChannelPipelineCoverage.class.getSimpleName() + " annotation value: " + coverageValue + " (must be either \"" + ALL + "\" or \"" + ONE + ")"); } } this.prev = prev; this.next = next; this.name = name; this.handler = handler; } public Channel getChannel() { return getPipeline().getChannel(); } public ChannelPipeline getPipeline() { return DefaultChannelPipeline.this; } public boolean canHandleDownstream() { return canHandleDownstream; } public boolean canHandleUpstream() { return canHandleUpstream; } public ChannelHandler getHandler() { return handler; } public String getName() { return name; } public Object getAttachment() { return attachment; } public void setAttachment(Object attachment) { this.attachment = attachment; } public void sendDownstream(ChannelEvent e) { DefaultChannelHandlerContext prev = getActualDownstreamContext(this.prev); if (prev == null) { try { getSink().eventSunk(DefaultChannelPipeline.this, e); } catch (Throwable t) { notifyHandlerException(e, t); } } else { DefaultChannelPipeline.this.sendDownstream(prev, e); } } public void sendUpstream(ChannelEvent e) { DefaultChannelHandlerContext next = getActualUpstreamContext(this.next); if (next != null) { DefaultChannelPipeline.this.sendUpstream(next, e); } } } private static final class DiscardingChannelSink implements ChannelSink { DiscardingChannelSink() { super(); } public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) { logger.warn("Not attached yet; discarding: " + e); } public void exceptionCaught(ChannelPipeline pipeline, ChannelEvent e, ChannelPipelineException cause) throws Exception { throw cause; } } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelEvent.java0000644000175000017500000000742411216125453027425 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * An I/O event or I/O request associated with a {@link Channel}. *

* A {@link ChannelEvent} is supposed to be handled by the * {@link ChannelPipeline} which is attached to the {@link Channel} that * the event belongs to. Once an event is sent to a {@link ChannelPipeline}, * it is handled by a list of {@link ChannelHandler}s. * *

Upstream events and downstream events, and their interpretation

*

* Every event can be either an upstream event or a downstream event. * If an event flows from the first handler to the last handler in a * {@link ChannelPipeline}, we call it an upstream event and say "an * event goes upstream." If an event flows from the last handler to * the first handler in a {@link ChannelPipeline}, we call it a downstream * event and say "an event goes downstream." (Please refer * to the diagram in {@link ChannelPipeline} for more explanation.) *

* A {@link ChannelEvent} is interpreted differently by a {@link ChannelHandler} * depending on whether the event is an upstream event or a downstream event. * An upstream event represents the notification of what happened in the past. * By contrast, a downstream event represents the request of what should happen * in the future. For example, a {@link MessageEvent} represents the * notification of a received message when it goes upstream, while it * represents the request of writing a message when it goes downstream. * *

Additional resources worth reading

*

* Please refer to the documentation of {@link ChannelHandler} and its sub-types * ({@link ChannelUpstreamHandler} for upstream events and * {@link ChannelDownstreamHandler} for downstream events) to find out how * a {@link ChannelEvent} is interpreted depending on the type of the handler * more in detail. Also, please refer to the {@link ChannelPipeline} * documentation to find out how an event flows in a pipeline. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1404 $, $Date: 2009-06-17 01:36:59 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.landmark * @apiviz.composedOf org.jboss.netty.channel.ChannelFuture */ public interface ChannelEvent { /** * Returns the {@link Channel} which is associated with this event. */ Channel getChannel(); /** * Returns the {@link ChannelFuture} which is associated with this event. * If this event is an upstream event, this method will always return a * {@link SucceededChannelFuture} because the event has occurred already. * If this event is a downstream event (i.e. I/O request), the returned * future will be notified when the I/O request succeeds or fails. */ ChannelFuture getFuture(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/SucceededChannelFuture.java0000644000175000017500000000344711047765477031446 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * The {@link CompleteChannelFuture} which is succeeded already. It is * recommended to use {@link Channels#succeededFuture(Channel)} instead of * calling the constructor of this future. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 50 $, $Date: 2008-08-11 00:33:19 -0700 (Mon, 11 Aug 2008) $ */ public class SucceededChannelFuture extends CompleteChannelFuture { /** * Creates a new instance. * * @param channel the {@link Channel} associated with this future */ public SucceededChannelFuture(Channel channel) { super(channel); } public Throwable getCause() { return null; } public boolean isSuccess() { return true; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultChannelFuture.java0000644000175000017500000002301611174012523031112 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static java.util.concurrent.TimeUnit.*; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.IoWorkerRunnable; /** * The default {@link ChannelFuture} implementation. It is recommended to * use {@link Channels#future(Channel)} and {@link Channels#future(Channel, boolean)} * to create a new {@link ChannelFuture} rather than calling the constructor * explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1241 $, $Date: 2009-04-23 00:14:27 -0700 (Thu, 23 Apr 2009) $ */ public class DefaultChannelFuture implements ChannelFuture { private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultChannelFuture.class); private static final Throwable CANCELLED = new Throwable(); private final Channel channel; private final boolean cancellable; private volatile ChannelFutureListener firstListener; private volatile List otherListeners; private boolean done; private Throwable cause; private int waiters; /** * Creates a new instance. * * @param channel * the {@link Channel} associated with this future * @param cancellable * {@code true} if and only if this future can be canceled */ public DefaultChannelFuture(Channel channel, boolean cancellable) { this.channel = channel; this.cancellable = cancellable; } public Channel getChannel() { return channel; } public synchronized boolean isDone() { return done; } public synchronized boolean isSuccess() { return done && cause == null; } public synchronized Throwable getCause() { if (cause != CANCELLED) { return cause; } else { return null; } } public synchronized boolean isCancelled() { return cause == CANCELLED; } public void addListener(ChannelFutureListener listener) { if (listener == null) { throw new NullPointerException("listener"); } boolean notifyNow = false; synchronized (this) { if (done) { notifyNow = true; } else { if (firstListener == null) { firstListener = listener; } else { if (otherListeners == null) { otherListeners = new ArrayList(1); } otherListeners.add(listener); } } } if (notifyNow) { notifyListener(listener); } } public void removeListener(ChannelFutureListener listener) { if (listener == null) { throw new NullPointerException("listener"); } synchronized (this) { if (!done) { if (listener == firstListener) { if (otherListeners != null && !otherListeners.isEmpty()) { firstListener = otherListeners.remove(0); } else { firstListener = null; } } else if (otherListeners != null) { otherListeners.remove(listener); } } } } public ChannelFuture await() throws InterruptedException { synchronized (this) { while (!done) { checkDeadLock(); waiters++; try { this.wait(); } finally { waiters--; } } } return this; } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return await0(unit.toNanos(timeout), true); } public boolean await(long timeoutMillis) throws InterruptedException { return await0(MILLISECONDS.toNanos(timeoutMillis), true); } public ChannelFuture awaitUninterruptibly() { synchronized (this) { while (!done) { checkDeadLock(); waiters++; try { this.wait(); } catch (InterruptedException e) { // Ignore. } finally { waiters--; } } } return this; } public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { try { return await0(unit.toNanos(timeout), false); } catch (InterruptedException e) { throw new InternalError(); } } public boolean awaitUninterruptibly(long timeoutMillis) { try { return await0(MILLISECONDS.toNanos(timeoutMillis), false); } catch (InterruptedException e) { throw new InternalError(); } } private boolean await0(long timeoutNanos, boolean interruptable) throws InterruptedException { long startTime = timeoutNanos <= 0 ? 0 : System.nanoTime(); long waitTime = timeoutNanos; synchronized (this) { if (done) { return done; } else if (waitTime <= 0) { return done; } checkDeadLock(); waiters++; try { for (;;) { try { this.wait(waitTime / 1000000, (int) (waitTime % 1000000)); } catch (InterruptedException e) { if (interruptable) { throw e; } } if (done) { return true; } else { waitTime = timeoutNanos - (System.nanoTime() - startTime); if (waitTime <= 0) { return done; } } } } finally { waiters--; } } } private void checkDeadLock() { if (IoWorkerRunnable.IN_IO_THREAD.get()) { throw new IllegalStateException( "await*() in I/O thread causes a dead lock or " + "sudden performance drop. Use addListener() instead or " + "call await*() from a different thread."); } } public boolean setSuccess() { synchronized (this) { // Allow only once. if (done) { return false; } done = true; if (waiters > 0) { notifyAll(); } } notifyListeners(); return true; } public boolean setFailure(Throwable cause) { synchronized (this) { // Allow only once. if (done) { return false; } this.cause = cause; done = true; if (waiters > 0) { notifyAll(); } } notifyListeners(); return true; } public boolean cancel() { if (!cancellable) { return false; } synchronized (this) { // Allow only once. if (done) { return false; } cause = CANCELLED; done = true; if (waiters > 0) { notifyAll(); } } notifyListeners(); return true; } private void notifyListeners() { // There won't be any visibility problem or concurrent modification // because 'ready' flag will be checked against both addListener and // removeListener calls. if (firstListener != null) { notifyListener(firstListener); firstListener = null; if (otherListeners != null) { for (ChannelFutureListener l: otherListeners) { notifyListener(l); } otherListeners = null; } } } private void notifyListener(ChannelFutureListener l) { try { l.operationComplete(this); } catch (Throwable t) { logger.warn( "An exception was thrown by " + ChannelFutureListener.class.getSimpleName() + ".", t); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/SimpleChannelHandler.java0000644000175000017500000003005111142473445031070 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * A {@link ChannelHandler} which provides an individual handler method * for each event type. This handler down-casts the received upstream or * or downstream event into more meaningful sub-type event and calls an * appropriate handler method with the down-cast event. For an upstream * event, the names of the methods are identical to the upstream event names, * as introduced in the {@link ChannelUpstreamHandler} documentation. For a * downstream event, the names of the methods starts with the name of the * operation and ends with {@code "Requested"} * (e.g. {@link #writeRequested(ChannelHandlerContext, MessageEvent) writeRequested}.) *

* Please use {@link SimpleChannelUpstreamHandler} or * {@link SimpleChannelDownstreamHandler} if you want to intercept only * upstream or downstream events. * *

Overriding the {@link #handleUpstream(ChannelHandlerContext, ChannelEvent) handleUpstream} * and {@link #handleDownstream(ChannelHandlerContext, ChannelEvent) handleDownstream} method

*

* You can override the {@link #handleUpstream(ChannelHandlerContext, ChannelEvent) handleUpstream} * and {@link #handleDownstream(ChannelHandlerContext, ChannelEvent) handleDownstream} * method just like overriding an ordinary Java method. Please make sure to * call {@code super.handleUpstream()} or {@code super.handleDownstream()} so * that other handler methods are invoked properly: *

*
public class MyChannelHandler extends SimpleChannelHandler {
 *
 *     public void handleUpstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *
 *         // Log all channel state changes.
 *         if (e instanceof ChannelStateEvent) {
 *             logger.info("Channel state changed: " + e);
 *         }
 *
 *         super.handleUpstream(ctx, e);
 *     }
 *
 *     public void handleDownstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *
 *         // Log all channel state changes.
 *         if (e instanceof MessageEvent) {
 *             logger.info("Writing:: " + e);
 *         }
 *
 *         super.handleDownstream(ctx, e);
 *     }
 * }
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 760 $, $Date: 2009-02-04 21:20:37 -0800 (Wed, 04 Feb 2009) $ */ public class SimpleChannelHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SimpleChannelHandler.class.getName()); /** * Creates a new instance. */ public SimpleChannelHandler() { super(); } /** * {@inheritDoc} Down-casts the received upstream event into more * meaningful sub-type event and calls an appropriate handler method with * the down-casted event. */ public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof MessageEvent) { messageReceived(ctx, (MessageEvent) e); } else if (e instanceof WriteCompletionEvent) { WriteCompletionEvent evt = (WriteCompletionEvent) e; writeComplete(ctx, evt); } else if (e instanceof ChildChannelStateEvent) { ChildChannelStateEvent evt = (ChildChannelStateEvent) e; if (evt.getChildChannel().isOpen()) { childChannelOpen(ctx, evt); } else { childChannelClosed(ctx, evt); } } else if (e instanceof ChannelStateEvent) { ChannelStateEvent evt = (ChannelStateEvent) e; switch (evt.getState()) { case OPEN: if (Boolean.TRUE.equals(evt.getValue())) { channelOpen(ctx, evt); } else { channelClosed(ctx, evt); } break; case BOUND: if (evt.getValue() != null) { channelBound(ctx, evt); } else { channelUnbound(ctx, evt); } break; case CONNECTED: if (evt.getValue() != null) { channelConnected(ctx, evt); } else { channelDisconnected(ctx, evt); } break; case INTEREST_OPS: channelInterestChanged(ctx, evt); break; default: ctx.sendDownstream(e); } } else if (e instanceof ExceptionEvent) { exceptionCaught(ctx, (ExceptionEvent) e); } else { ctx.sendUpstream(e); } } /** * Invoked when a message object (e.g: {@link ChannelBuffer}) was received * from a remote peer. */ public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when an exception was raised by an I/O thread or a * {@link ChannelHandler}. */ public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { if (this == ctx.getPipeline().getLast()) { logger.warn( "EXCEPTION, please implement " + getClass().getName() + ".exceptionCaught() for proper handling.", e.getCause()); } ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} is open, but not bound nor connected. */ public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} is open and bound to a local address, * but not connected. */ public void channelBound( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} is open, bound to a local address, and * connected to a remote address. */ public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel}'s {@link Channel#getInterestOps() interestOps} * was changed. */ public void channelInterestChanged( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} was disconnected from its remote peer. */ public void channelDisconnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} was unbound from the current local address. */ public void channelUnbound( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a {@link Channel} was closed and all its related resources * were released. */ public void channelClosed( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when something was written into a {@link Channel}. */ public void writeComplete( ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a child {@link Channel} was open. * (e.g. a server channel accepted a connection) */ public void childChannelOpen( ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * Invoked when a child {@link Channel} was closed. * (e.g. the accepted connection was closed) */ public void childChannelClosed( ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { ctx.sendUpstream(e); } /** * {@inheritDoc} Down-casts the received downstream event into more * meaningful sub-type event and calls an appropriate handler method with * the down-casted event. */ public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof MessageEvent) { writeRequested(ctx, (MessageEvent) e); } else if (e instanceof ChannelStateEvent) { ChannelStateEvent evt = (ChannelStateEvent) e; switch (evt.getState()) { case OPEN: if (!Boolean.TRUE.equals(evt.getValue())) { closeRequested(ctx, evt); } break; case BOUND: if (evt.getValue() != null) { bindRequested(ctx, evt); } else { unbindRequested(ctx, evt); } break; case CONNECTED: if (evt.getValue() != null) { connectRequested(ctx, evt); } else { disconnectRequested(ctx, evt); } break; case INTEREST_OPS: setInterestOpsRequested(ctx, evt); break; default: ctx.sendDownstream(e); } } else { ctx.sendDownstream(e); } } /** * Invoked when {@link Channel#write(Object)} is called. */ public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#bind(SocketAddress)} was called. */ public void bindRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#connect(SocketAddress)} was called. */ public void connectRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#setInterestOps(int)} was called. */ public void setInterestOpsRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#disconnect()} was called. */ public void disconnectRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#unbind()} was called. */ public void unbindRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#close()} was called. */ public void closeRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultChannelConfig.java0000644000175000017500000000713311216742125031054 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.Map; import java.util.Map.Entry; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.HeapChannelBufferFactory; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.handler.timeout.WriteTimeoutHandler; /** * The default {@link SocketChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1478 $, $Date: 2009-06-19 10:01:09 -0700 (Fri, 19 Jun 2009) $ * */ public class DefaultChannelConfig implements ChannelConfig { private volatile ChannelBufferFactory bufferFactory = HeapChannelBufferFactory.getInstance(); private volatile int connectTimeoutMillis = 10000; // 10 seconds /** * Creates a new instance. */ public DefaultChannelConfig() { super(); } public void setOptions(Map options) { for (Entry e: options.entrySet()) { setOption(e.getKey(), e.getValue()); } } public boolean setOption(String key, Object value) { if (key.equals("pipelineFactory")) { setPipelineFactory((ChannelPipelineFactory) value); } else if (key.equals("bufferFactory")) { setBufferFactory((ChannelBufferFactory) value); } else { return false; } return true; } public int getConnectTimeoutMillis() { return connectTimeoutMillis; } public ChannelBufferFactory getBufferFactory() { return bufferFactory; } public void setBufferFactory(ChannelBufferFactory bufferFactory) { if (bufferFactory == null) { throw new NullPointerException("bufferFactory"); } this.bufferFactory = bufferFactory; } public ChannelPipelineFactory getPipelineFactory() { return null; } /** * @deprecated Use {@link WriteTimeoutHandler} instead. */ @Deprecated public int getWriteTimeoutMillis() { return 0; } public void setConnectTimeoutMillis(int connectTimeoutMillis) { if (connectTimeoutMillis < 0) { throw new IllegalArgumentException("connectTimeoutMillis: " + connectTimeoutMillis); } this.connectTimeoutMillis = connectTimeoutMillis; } public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) { // Unused } /** * @deprecated Use {@link WriteTimeoutHandler} instead. */ @Deprecated public void setWriteTimeoutMillis(int writeTimeoutMillis) { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelConfig.java0000644000175000017500000001611311216742125027545 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.io.IOException; import java.nio.ByteOrder; import java.util.Map; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.HeapChannelBufferFactory; import org.jboss.netty.channel.socket.SocketChannelConfig; import org.jboss.netty.channel.socket.nio.NioSocketChannelConfig; import org.jboss.netty.handler.timeout.WriteTimeoutHandler; /** * A set of configuration properties of a {@link Channel}. *

* Please down-cast to more specific configuration type such as * {@link SocketChannelConfig} or use {@link #setOptions(Map)} to set the * transport-specific properties: *

 * Channel ch = ...;
 * SocketChannelConfig cfg = (SocketChannelConfig) ch.getConfig();
 * cfg.setTcpNoDelay(false);
 * 
* *

Option map

* * An option map property is a dynamic write-only property which allows * the configuration of a {@link Channel} without down-casting its associated * {@link ChannelConfig}. To update an option map, please call {@link #setOptions(Map)}. *

* All {@link ChannelConfig} has the following options: * * * * * * * * * * * *
NameAssociated setter method
{@code "bufferFactory"}{@link #setBufferFactory(ChannelBufferFactory)}
{@code "connectTimeoutMillis"}{@link #setConnectTimeoutMillis(int)}
{@code "pipelineFactory"}{@link #setPipelineFactory(ChannelPipelineFactory)}
*

* More options are available in the sub-types of {@link ChannelConfig}. For * example, you can configure the parameters which are specific to a TCP/IP * socket as explained in {@link SocketChannelConfig} or {@link NioSocketChannelConfig}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1478 $, $Date: 2009-06-19 10:01:09 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.has org.jboss.netty.channel.ChannelPipelineFactory * @apiviz.composedOf org.jboss.netty.channel.ReceiveBufferSizePredictor * * @apiviz.excludeSubtypes */ public interface ChannelConfig { /** * Sets the configuration properties from the specified {@link Map}. */ void setOptions(Map options); /** * Sets a configuration property with the specified name and value. * To override this method properly, you must call the super class: *

     * public boolean setOption(String name, Object value) {
     *     if (super.setOption(name, value)) {
     *         return true;
     *     }
     *
     *     if (name.equals("additionalOption")) {
     *         ....
     *         return true;
     *     }
     *
     *     return false;
     * }
     * 
* * @return {@code true} if and only if the property has been set */ boolean setOption(String name, Object value); /** * Returns the default {@link ChannelBufferFactory} used to create a new * {@link ChannelBuffer}. The default is {@link HeapChannelBufferFactory}. * You can specify a different factory to change the default * {@link ByteOrder} for example. */ ChannelBufferFactory getBufferFactory(); /** * Sets the default {@link ChannelBufferFactory} used to create a new * {@link ChannelBuffer}. The default is {@link HeapChannelBufferFactory}. * You can specify a different factory to change the default * {@link ByteOrder} for example. */ void setBufferFactory(ChannelBufferFactory bufferFactory); /** * Returns the {@link ChannelPipelineFactory} which will be used when * a child channel is created. If the {@link Channel} does not create * a child channel, this property is not used at all, and therefore will * be ignored. */ ChannelPipelineFactory getPipelineFactory(); /** * Sets the {@link ChannelPipelineFactory} which will be used when * a child channel is created. If the {@link Channel} does not create * a child channel, this property is not used at all, and therefore will * be ignored. */ void setPipelineFactory(ChannelPipelineFactory pipelineFactory); /** * Returns the connect timeout of the channel in milliseconds. If the * {@link Channel} does not support connect operation, this property is not * used at all, and therefore will be ignored. * * @return the connect timeout in milliseconds. {@code 0} if disabled. */ int getConnectTimeoutMillis(); /** * Sets the connect timeout of the channel in milliseconds. If the * {@link Channel} does not support connect operation, this property is not * used at all, and therefore will be ignored. * * @param connectTimeoutMillis the connect timeout in milliseconds. * {@code 0} to disable. */ void setConnectTimeoutMillis(int connectTimeoutMillis); /** * @deprecated Use {@link WriteTimeoutHandler} instead. * * Returns the write timeout of the channel in milliseconds. If a write * operation is not completed within the write timeout, an * {@link IOException} will be raised. If the {@link Channel} does not * support write operation, this property is not used at all, and therefore * will be ignored. * * @return the write timeout in milliseconds. {@code 0} if disabled. */ @Deprecated int getWriteTimeoutMillis(); /** * @deprecated Use {@link WriteTimeoutHandler} instead. * * Sets the write timeout of the channel in milliseconds. If a write * operation is not completed within the write timeout, an * {@link IOException} will be raised. If the {@link Channel} does not * support write operation, this property is not used at all, and therefore * will be ignored. * * @param writeTimeoutMillis the write timeout in milliseconds. * {@code 0} to disable. */ @Deprecated void setWriteTimeoutMillis(int writeTimeoutMillis); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelFactory.java0000644000175000017500000000757511175574066027776 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.concurrent.Executor; import org.jboss.netty.channel.group.ChannelGroup; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.util.ExternalResourceReleasable; /** * The main interface to a transport that creates a {@link Channel} associated * with a certain communication entity such as a network socket. For example, * the {@link NioServerSocketChannelFactory} creates a channel which has a * NIO-based server socket as its underlying communication entity. *

* Once a new {@link Channel} is created, the {@link ChannelPipeline} which * was specified as a parameter in the {@link #newChannel(ChannelPipeline)} * is attached to the new {@link Channel}, and starts to handle all associated * {@link ChannelEvent}s. * *

Graceful shutdown

*

* To shut down a network application service which is managed by a factory. * you should follow the following steps: *

    *
  1. close all channels created by the factory and their child channels * usually using {@link ChannelGroup#close()}, and
  2. *
  3. call {@link #releaseExternalResources()}.
  4. *
*

* For detailed transport-specific information on shutting down a factory, * please refer to the Javadoc of {@link ChannelFactory}'s subtypes, such as * {@link NioServerSocketChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark * @apiviz.has org.jboss.netty.channel.Channel oneway - - creates * * @apiviz.exclude ^org\.jboss\.netty\.channel\.([a-z]+\.)+.*ChannelFactory$ */ public interface ChannelFactory extends ExternalResourceReleasable { /** * Creates and opens a new {@link Channel} and attaches the specified * {@link ChannelPipeline} to the new {@link Channel}. * * @param pipeline the {@link ChannelPipeline} which is going to be * attached to the new {@link Channel} * * @return the newly open channel * * @throws ChannelException if failed to create and open a new channel */ Channel newChannel(ChannelPipeline pipeline); /** * Releases the external resources that this factory depends on to function. * An external resource is a resource that this factory didn't create by * itself. For example, {@link Executor}s that you specified in the factory * constructor are external resources. You can call this method to release * all external resources conveniently when the resources are not used by * this factory or any other part of your application. An unexpected * behavior will be resulted in if the resources are released when there's * an open channel which is managed by this factory. */ void releaseExternalResources(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChildChannelStateEvent.java0000644000175000017500000000375511216651554031403 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link ChannelEvent} which represents the notification of the state of * a child {@link Channel}. This event is for going upstream only. Please * refer to the {@link ChannelEvent} documentation to find out what an upstream * event and a downstream event are and what fundamental differences they have. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1450 $, $Date: 2009-06-19 01:59:24 -0700 (Fri, 19 Jun 2009) $ */ public interface ChildChannelStateEvent extends ChannelEvent { /** * Returns the parent {@link Channel} which is associated * with this event. Please note that you should use {@link #getChildChannel()} * to get the {@link Channel} created or accepted by the parent {@link Channel}. */ Channel getChannel(); /** * Returns the child {@link Channel} whose state has been changed. */ Channel getChildChannel(); } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/FixedReceiveBufferSizePredictor.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/FixedReceiveBufferSizePredictor.j0000644000175000017500000000405511216134140032554 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * The {@link ReceiveBufferSizePredictor} that always yields the same buffer * size prediction. This predictor ignores the feed back from the I/O thread. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ */ public class FixedReceiveBufferSizePredictor implements ReceiveBufferSizePredictor { private final int bufferSize; /** * Creates a new predictor that always returns the same prediction of * the specified buffer size. */ public FixedReceiveBufferSizePredictor(int bufferSize) { if (bufferSize <= 0) { throw new IllegalArgumentException( "bufferSize must greater than 0: " + bufferSize); } this.bufferSize = bufferSize; } public int nextReceiveBufferSize() { return bufferSize; } public void previousReceiveBufferSize(int previousReceiveBufferSize) { // Ignore } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/package-info.java0000644000175000017500000000334711175567165027415 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * The core channel API which is asynchronous and event-driven abstraction of * various transports such as a * NIO Channel. * * @apiviz.landmark * @apiviz.exclude ^java * @apiviz.exclude ^org\.jboss\.netty\.channel\.[^\.]+\. * @apiviz.exclude ^org\.jboss\.netty\.(bootstrap|handler|util)\. * @apiviz.exclude \.(Abstract|Default).*$ * @apiviz.exclude \.(Downstream|Upstream).*Event$ * @apiviz.exclude \.[A-Za-z]+ChannelFuture$ * @apiviz.exclude \.ChannelPipelineFactory$ * @apiviz.exclude \.ChannelHandlerContext$ * @apiviz.exclude \.ChannelSink$ * @apiviz.exclude \.ChannelLocal$ * @apiviz.exclude \.[^\.]+ReceiveBufferSizePredictor$ */ package org.jboss.netty.channel; libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelHandler.java0000644000175000017500000000565511216131646027726 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * Handles or intercepts a {@link ChannelEvent}, and sends a * {@link ChannelEvent} to the next or previous handler in a * {@link ChannelPipeline}. * *

Sub-types

*

* {@link ChannelHandler} itself does not provide any method. To handle a * {@link ChannelEvent} you need to implement its sub-interfaces. There are * two sub-interfaces which handles a received event, one for upstream events * and the other for downstream events: *

    *
  • {@link ChannelUpstreamHandler} handles and intercepts an upstream {@link ChannelEvent}.
  • *
  • {@link ChannelDownstreamHandler} handles and intercepts a downstream {@link ChannelEvent}.
  • *
* * You will also find more detailed explanation from the documentation of * each sub-interface on how an event is interpreted when it goes upstream and * downstream respectively. * *

The context object

*

* A {@link ChannelHandler} is provided with a {@link ChannelHandlerContext} * object. A {@link ChannelHandler} is supposed to interact with the * {@link ChannelPipeline} it belongs to via a context object. Using the * context object, the {@link ChannelHandler} can pass events to the next * or the previous handler or modify the behavior of the pipeline, or store the * information (attachment) which is specific to the handler. * *

Additional resources worth reading

*

* Please refer to the {@link ChannelEvent} and {@link ChannelPipeline} to find * out what a upstream event and a downstream event are, what fundamental * differences they have, and how they flow in a pipeline. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1405 $, $Date: 2009-06-17 02:13:10 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.landmark * @apiviz.exclude ^org\.jboss\.netty\.handler\..*$ */ public interface ChannelHandler { // This is a tag interface. } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DownstreamChannelStateEvent.java0000644000175000017500000000705611216134140032464 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * The default downstream {@link ChannelStateEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ * */ public class DownstreamChannelStateEvent implements ChannelStateEvent { private final Channel channel; private final ChannelFuture future; private final ChannelState state; private final Object value; /** * Creates a new instance. */ public DownstreamChannelStateEvent( Channel channel, ChannelFuture future, ChannelState state, Object value) { if (channel == null) { throw new NullPointerException("channel"); } if (future == null) { throw new NullPointerException("future"); } if (state == null) { throw new NullPointerException("state"); } this.channel = channel; this.future = future; this.state = state; this.value = value; } public Channel getChannel() { return channel; } public ChannelFuture getFuture() { return future; } public ChannelState getState() { return state; } public Object getValue() { return value; } @Override public String toString() { String channelString = getChannel().toString(); StringBuilder buf = new StringBuilder(channelString.length() + 64); buf.append(channelString); switch (getState()) { case OPEN: if (Boolean.TRUE.equals(getValue())) { buf.append(" OPEN"); } else { buf.append(" CLOSE"); } break; case BOUND: if (getValue() != null) { buf.append(" BIND: "); buf.append(getValue()); } else { buf.append(" UNBIND"); } break; case CONNECTED: if (getValue() != null) { buf.append(" CONNECT: "); buf.append(getValue()); } else { buf.append(" DISCONNECT"); } break; case INTEREST_OPS: buf.append(" CHANGE_INTEREST: "); buf.append(getValue()); break; default: buf.append(' '); buf.append(getState().name()); buf.append(": "); buf.append(getValue()); } return buf.toString(); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/SimpleChannelDownstreamHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/SimpleChannelDownstreamHandler.ja0000644000175000017500000001336411141470277032614 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; /** * A {@link ChannelDownstreamHandler} which provides an individual handler * method for each event type. This handler down-casts the received downstream * event into more meaningful sub-type event and calls an appropriate handler * method with the down-cast event. The names of the methods starts with the * name of the operation and ends with {@code "Requested"} * (e.g. {@link #writeRequested(ChannelHandlerContext, MessageEvent) writeRequested}.) *

* Please use {@link SimpleChannelHandler} if you need to implement both * {@link ChannelUpstreamHandler} and {@link ChannelDownstreamHandler}. * *

Overriding the {@link #handleDownstream(ChannelHandlerContext, ChannelEvent) handleDownstream} method

*

* You can override the {@link #handleDownstream(ChannelHandlerContext, ChannelEvent) handleDownstream} * method just like overriding an ordinary Java method. Please make sure to * call {@code super.handleDownstream()} so that other handler methods are * invoked properly: *

*
public class MyChannelHandler extends SimpleChannelDownstreamHandler {
 *
 *     public void handleDownstream({@link ChannelHandlerContext} ctx, {@link ChannelEvent} e) throws Exception {
 *
 *         // Log all channel state changes.
 *         if (e instanceof MessageEvent) {
 *             logger.info("Writing:: " + e);
 *         }
 *
 *         super.handleDownstream(ctx, e);
 *     }
 * }
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 741 $, $Date: 2009-02-01 20:04:15 -0800 (Sun, 01 Feb 2009) $ */ public class SimpleChannelDownstreamHandler implements ChannelDownstreamHandler { /** * Creates a new instance. */ public SimpleChannelDownstreamHandler() { super(); } /** * {@inheritDoc} Down-casts the received downstream event into more * meaningful sub-type event and calls an appropriate handler method with * the down-casted event. */ public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof MessageEvent) { writeRequested(ctx, (MessageEvent) e); } else if (e instanceof ChannelStateEvent) { ChannelStateEvent evt = (ChannelStateEvent) e; switch (evt.getState()) { case OPEN: if (!Boolean.TRUE.equals(evt.getValue())) { closeRequested(ctx, evt); } break; case BOUND: if (evt.getValue() != null) { bindRequested(ctx, evt); } else { unbindRequested(ctx, evt); } break; case CONNECTED: if (evt.getValue() != null) { connectRequested(ctx, evt); } else { disconnectRequested(ctx, evt); } break; case INTEREST_OPS: setInterestOpsRequested(ctx, evt); break; default: ctx.sendDownstream(e); } } else { ctx.sendDownstream(e); } } /** * Invoked when {@link Channel#write(Object)} is called. */ public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#bind(SocketAddress)} was called. */ public void bindRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#connect(SocketAddress)} was called. */ public void connectRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#setInterestOps(int)} was called. */ public void setInterestOpsRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#disconnect()} was called. */ public void disconnectRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#unbind()} was called. */ public void unbindRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } /** * Invoked when {@link Channel#close()} was called. */ public void closeRequested(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { ctx.sendDownstream(e); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelHandlerLifeCycleException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelHandlerLifeCycleException.0000644000175000017500000000411411216131646032510 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link RuntimeException} which is thrown when a * {@link LifeCycleAwareChannelHandler} throws an {@link Exception} * in its handler methods. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1405 $, $Date: 2009-06-17 02:13:10 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.hidden */ public class ChannelHandlerLifeCycleException extends RuntimeException { private static final long serialVersionUID = 8764799996088850672L; /** * Creates a new exception. */ public ChannelHandlerLifeCycleException() { super(); } /** * Creates a new exception. */ public ChannelHandlerLifeCycleException(String message, Throwable cause) { super(message, cause); } /** * Creates a new exception. */ public ChannelHandlerLifeCycleException(String message) { super(message); } /** * Creates a new exception. */ public ChannelHandlerLifeCycleException(Throwable cause) { super(cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/UnfailingChannelFuture.java0000644000175000017500000000370611150677153031460 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * The {@link ChannelFuture} which can not fail at all. Any attempt to mark * this future as failure, by calling {@link #setFailure(Throwable)} will raise * an {@link IllegalStateException}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 932 $, $Date: 2009-02-23 20:58:19 -0800 (Mon, 23 Feb 2009) $ */ public class UnfailingChannelFuture extends DefaultChannelFuture { /** * Creates a new instance. * * @param channel * the {@link Channel} associated with this future * @param cancellable * {@code true} if and only if this future can be canceled */ public UnfailingChannelFuture(Channel channel, boolean cancellable) { super(channel, cancellable); } @Override public boolean setFailure(Throwable cause) { throw new IllegalStateException("Can not fail", cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/MessageEvent.java0000644000175000017500000000407011107230242027423 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.net.SocketAddress; /** * A {@link ChannelEvent} which represents the transmission or reception of a * message. It can mean the notification of a received message or the request * for writing a message, depending on whether it is an upstream event or a * downstream event respectively. Please refer to the {@link ChannelEvent} * documentation to find out what an upstream event and a downstream event are * and what fundamental differences they have. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 473 $, $Date: 2008-11-14 00:02:42 -0800 (Fri, 14 Nov 2008) $ */ public interface MessageEvent extends ChannelEvent { /** * Returns the message. */ Object getMessage(); /** * Returns the remote address. * * @return the remote address. {@code null} if the remote address is * same with the default remote address returned by {@link Channel#getRemoteAddress()}. */ SocketAddress getRemoteAddress(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/0000755000175000017500000000000011316313131025264 5ustar deckerdecker././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalServerChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalServerChannelFactory.j0000644000175000017500000000303111216747541032515 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ServerChannelFactory; /** * A {@link ServerChannelFactory} that creates a {@link LocalServerChannel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public interface LocalServerChannelFactory extends ServerChannelFactory { LocalServerChannel newChannel(ChannelPipeline pipeline); } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalClientChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalClientChannelFactory.j0000644000175000017500000000300711216747541032470 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; /** * A {@link ChannelFactory} that creates a client-side {@link LocalChannel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public interface LocalClientChannelFactory extends ChannelFactory { LocalChannel newChannel(ChannelPipeline pipeline); } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalServerChannelSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalServerChannelSink.java0000644000175000017500000001324211216747541032507 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ final class LocalServerChannelSink extends AbstractChannelSink { LocalServerChannelSink() { super(); } public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception { Channel channel = e.getChannel(); if (channel instanceof DefaultLocalServerChannel) { handleServerChannel(e); } else if (channel instanceof DefaultLocalChannel) { handleAcceptedChannel(e); } } private void handleServerChannel(ChannelEvent e) { if (!(e instanceof ChannelStateEvent)) { return; } ChannelStateEvent event = (ChannelStateEvent) e; DefaultLocalServerChannel channel = (DefaultLocalServerChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { close(channel, future); } break; case BOUND: if (value != null) { bind(channel, future, (LocalAddress) value); } else { close(channel, future); } break; } } private void handleAcceptedChannel(ChannelEvent e) { if (e instanceof ChannelStateEvent) { ChannelStateEvent event = (ChannelStateEvent) e; DefaultLocalChannel channel = (DefaultLocalChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { channel.closeNow(future); } break; case BOUND: case CONNECTED: if (value == null) { channel.closeNow(future); } break; case INTEREST_OPS: // Unsupported - discard silently. future.setSuccess(); break; } } else if (e instanceof MessageEvent) { MessageEvent event = (MessageEvent) e; DefaultLocalChannel channel = (DefaultLocalChannel) event.getChannel(); boolean offered = channel.writeBuffer.offer(event); assert offered; channel.flushWriteBuffer(); } } private void bind(DefaultLocalServerChannel channel, ChannelFuture future, LocalAddress localAddress) { try { if (!LocalChannelRegistry.register(localAddress, channel)) { throw new ChannelException("address already in use: " + localAddress); } if (!channel.bound.compareAndSet(false, true)) { throw new ChannelException("already bound"); } channel.localAddress = localAddress; future.setSuccess(); fireChannelBound(channel, localAddress); } catch (Throwable t) { LocalChannelRegistry.unregister(localAddress); future.setFailure(t); fireExceptionCaught(channel, t); } } private void close(DefaultLocalServerChannel channel, ChannelFuture future) { try { if (channel.setClosed()) { future.setSuccess(); LocalAddress localAddress = channel.localAddress; if (channel.bound.compareAndSet(true, false)) { channel.localAddress = null; LocalChannelRegistry.unregister(localAddress); fireChannelUnbound(channel); } fireChannelClosed(channel); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(channel, t); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalClientChannelSink.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalClientChannelSink.java0000644000175000017500000001413111216747541032455 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import static org.jboss.netty.channel.Channels.*; import java.net.ConnectException; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ final class LocalClientChannelSink extends AbstractChannelSink { private static final InternalLogger logger = InternalLoggerFactory.getInstance(LocalClientChannelSink.class); LocalClientChannelSink() { super(); } public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { ChannelStateEvent event = (ChannelStateEvent) e; DefaultLocalChannel channel = (DefaultLocalChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { channel.closeNow(future); } break; case BOUND: if (value != null) { bind(channel, future, (LocalAddress) value); } else { channel.closeNow(future); } break; case CONNECTED: if (value != null) { connect(channel, future, (LocalAddress) value); } else { channel.closeNow(future); } break; case INTEREST_OPS: // Unsupported - discard silently. future.setSuccess(); break; } } else if (e instanceof MessageEvent) { MessageEvent event = (MessageEvent) e; DefaultLocalChannel channel = (DefaultLocalChannel) event.getChannel(); boolean offered = channel.writeBuffer.offer(event); assert offered; channel.flushWriteBuffer(); } } private void bind(DefaultLocalChannel channel, ChannelFuture future, LocalAddress localAddress) { try { if (!LocalChannelRegistry.register(localAddress, channel)) { throw new ChannelException("address already in use: " + localAddress); } if (!channel.bound.compareAndSet(false, true)) { throw new ChannelException("already bound"); } channel.localAddress = localAddress; future.setSuccess(); fireChannelBound(channel, localAddress); } catch (Throwable t) { LocalChannelRegistry.unregister(localAddress); future.setFailure(t); fireExceptionCaught(channel, t); } } private void connect(DefaultLocalChannel channel, ChannelFuture future, LocalAddress remoteAddress) { Channel remoteChannel = LocalChannelRegistry.getChannel(remoteAddress); if (!(remoteChannel instanceof DefaultLocalServerChannel)) { future.setFailure(new ConnectException("connection refused")); return; } DefaultLocalServerChannel serverChannel = (DefaultLocalServerChannel) remoteChannel; ChannelPipeline pipeline; try { pipeline = serverChannel.getConfig().getPipelineFactory().getPipeline(); } catch (Exception e) { future.setFailure(e); logger.warn( "Failed to initialize an accepted socket.", e); return; } future.setSuccess(); DefaultLocalChannel acceptedChannel = new DefaultLocalChannel( serverChannel, serverChannel.getFactory(), pipeline, this, channel); channel.pairedChannel = acceptedChannel; bind(channel, succeededFuture(channel), new LocalAddress(LocalAddress.EPHEMERAL)); channel.remoteAddress = serverChannel.getLocalAddress(); fireChannelConnected(channel, serverChannel.getLocalAddress()); acceptedChannel.localAddress = serverChannel.getLocalAddress(); acceptedChannel.bound.set(true); fireChannelBound(acceptedChannel, channel.getRemoteAddress()); acceptedChannel.remoteAddress = channel.getLocalAddress(); fireChannelConnected(acceptedChannel, channel.getLocalAddress()); // Flush something that was written in channelBound / channelConnected channel.flushWriteBuffer(); acceptedChannel.flushWriteBuffer(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalChannel.java0000644000175000017500000000305311216747541030472 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; /** * A {@link Channel} for the local transport. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public interface LocalChannel extends Channel { ChannelConfig getConfig(); LocalAddress getLocalAddress(); LocalAddress getRemoteAddress(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalAddress.java0000644000175000017500000000675011216747541030516 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import java.net.SocketAddress; /** * An endpoint in the local transport. Each endpoint is identified by a unique * case-insensitive string, except for the pre-defined value called * {@code "ephemeral"}. * *

Ephemeral Address

* * An ephemeral address is an anonymous address which is assigned temporarily * and is released as soon as the connection is closed. All ephemeral addresses * have the same ID, {@code "ephemeral"}, but they are not equals to each other. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public final class LocalAddress extends SocketAddress implements Comparable { private static final long serialVersionUID = -3601961747680808645L; public static final String EPHEMERAL = "ephemeral"; private final String id; private final boolean ephemeral; /** * Creates a new instance with the specified ID. */ public LocalAddress(int id) { this(String.valueOf(id)); } /** * Creates a new instance with the specified ID. */ public LocalAddress(String id) { if (id == null) { throw new NullPointerException("id"); } id = id.trim().toLowerCase(); if (id.length() == 0) { throw new IllegalArgumentException("empty id"); } this.id = id; ephemeral = id.equals("ephemeral"); } /** * Returns the ID of this address. */ public String getId() { return id; } /** * Returns {@code true} if and only if this address is ephemeral. */ public boolean isEphemeral() { return ephemeral; } @Override public int hashCode() { if (ephemeral) { return System.identityHashCode(this); } else { return id.hashCode(); } } @Override public boolean equals(Object o) { if (!(o instanceof LocalAddress)) { return false; } if (ephemeral) { return this == o; } else { return getId().equals(((LocalAddress) o).getId()); } } public int compareTo(LocalAddress o) { // FIXME: Ephemeral port return getId().compareTo(o.getId()); } @Override public String toString() { return "local:" + getId(); } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/DefaultLocalServerChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/DefaultLocalServerChannel.j0000644000175000017500000000506711216747541032505 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import static org.jboss.netty.channel.Channels.*; import java.util.concurrent.atomic.AtomicBoolean; import org.jboss.netty.channel.AbstractServerChannel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.DefaultServerChannelConfig; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ final class DefaultLocalServerChannel extends AbstractServerChannel implements LocalServerChannel { final ChannelConfig channelConfig; final AtomicBoolean bound = new AtomicBoolean(); volatile LocalAddress localAddress; DefaultLocalServerChannel(ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { super(factory, pipeline, sink); channelConfig = new DefaultServerChannelConfig(); fireChannelOpen(this); } public ChannelConfig getConfig() { return channelConfig; } public boolean isBound() { return isOpen() && bound.get(); } public LocalAddress getLocalAddress() { return isBound()? localAddress : null; } public LocalAddress getRemoteAddress() { return null; } @Override protected boolean setClosed() { return super.setClosed(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalServerChannel.java0000644000175000017500000000310311216747541031655 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ServerChannel; /** * A {@link ServerChannel} for the local transport. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public interface LocalServerChannel extends ServerChannel { ChannelConfig getConfig(); LocalAddress getLocalAddress(); LocalAddress getRemoteAddress(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/package-info.java0000644000175000017500000000222611216140766030470 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * A virtual transport that enables the communication between the two * parties in the same virtual machine. */ package org.jboss.netty.channel.local; libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/LocalChannelRegistry.java0000644000175000017500000000377411165336702032231 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import java.util.concurrent.ConcurrentMap; import org.jboss.netty.channel.Channel; import org.jboss.netty.util.internal.ConcurrentHashMap; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ final class LocalChannelRegistry { private static final ConcurrentMap map = new ConcurrentHashMap(); static boolean isRegistered(LocalAddress address) { return map.containsKey(address); } static Channel getChannel(LocalAddress address) { return map.get(address); } static boolean register(LocalAddress address, Channel channel) { return map.putIfAbsent(address, channel) == null; } static boolean unregister(LocalAddress address) { return map.remove(address) != null; } private LocalChannelRegistry() { // Unused } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/DefaultLocalClientChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/DefaultLocalClientChannelFa0000644000175000017500000000401711216747541032466 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; /** * The default {@link LocalClientChannelFactory} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultLocalClientChannelFactory implements LocalClientChannelFactory { private final ChannelSink sink; /** * Creates a new instance. */ public DefaultLocalClientChannelFactory() { sink = new LocalClientChannelSink(); } public LocalChannel newChannel(ChannelPipeline pipeline) { return new DefaultLocalChannel(null, this, pipeline, sink, null); } /** * Does nothing because this implementation does not require any external * resources. */ public void releaseExternalResources() { // No external resources. } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/DefaultLocalChannel.java0000644000175000017500000001402311216747541031776 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import static org.jboss.netty.channel.Channels.*; import java.nio.channels.ClosedChannelException; import java.nio.channels.NotYetConnectedException; import java.util.Queue; import java.util.concurrent.atomic.AtomicBoolean; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.DefaultChannelConfig; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.internal.LinkedTransferQueue; import org.jboss.netty.util.internal.ThreadLocalBoolean; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ final class DefaultLocalChannel extends AbstractChannel implements LocalChannel { private final ChannelConfig config; private final ThreadLocalBoolean delivering = new ThreadLocalBoolean(); final AtomicBoolean bound = new AtomicBoolean(); final Queue writeBuffer = new LinkedTransferQueue(); volatile DefaultLocalChannel pairedChannel; volatile LocalAddress localAddress; volatile LocalAddress remoteAddress; DefaultLocalChannel(LocalServerChannel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, DefaultLocalChannel pairedChannel) { super(parent, factory, pipeline, sink); this.pairedChannel = pairedChannel; config = new DefaultChannelConfig(); fireChannelOpen(this); } public ChannelConfig getConfig() { return config; } public boolean isBound() { return isOpen() && bound.get(); } public boolean isConnected() { return localAddress != null && remoteAddress != null; } public LocalAddress getLocalAddress() { return isBound()? localAddress : null; } public LocalAddress getRemoteAddress() { return remoteAddress; } void closeNow(ChannelFuture future) { LocalAddress localAddress = this.localAddress; try { // Close the self. if (!setClosed()) { return; } DefaultLocalChannel pairedChannel = this.pairedChannel; if (pairedChannel != null) { this.pairedChannel = null; this.localAddress = null; fireChannelDisconnected(this); fireChannelUnbound(this); } fireChannelClosed(this); // Close the peer. if (pairedChannel == null || !pairedChannel.setClosed()) { return; } DefaultLocalChannel me = pairedChannel.pairedChannel; if (me != null) { pairedChannel.pairedChannel = null; pairedChannel.localAddress = null; fireChannelDisconnected(pairedChannel); fireChannelUnbound(pairedChannel); } fireChannelClosed(pairedChannel); } finally { future.setSuccess(); if (localAddress != null) { LocalChannelRegistry.unregister(localAddress); } } } void flushWriteBuffer() { DefaultLocalChannel pairedChannel = this.pairedChannel; if (pairedChannel != null) { if (pairedChannel.isConnected()){ // Channel is open and connected and channelConnected event has // been fired. if (!delivering.get()) { delivering.set(true); try { for (;;) { MessageEvent e = writeBuffer.poll(); if(e == null) { break; } e.getFuture().setSuccess(); fireMessageReceived(pairedChannel, e.getMessage()); fireWriteComplete(this, 1); } } finally { delivering.set(false); } } } else { // Channel is open and connected but channelConnected event has // not been fired yet. } } else { // Channel is closed or not connected yet - notify as failures. Exception cause; if (isOpen()) { cause = new NotYetConnectedException(); } else { cause = new ClosedChannelException(); } for (;;) { MessageEvent e = writeBuffer.poll(); if(e == null) { break; } e.getFuture().setFailure(cause); fireExceptionCaught(this, cause); } } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/DefaultLocalServerChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/local/DefaultLocalServerChannelFa0000644000175000017500000000400211216747541032510 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.local; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; /** * The default {@link LocalServerChannelFactory} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultLocalServerChannelFactory implements LocalServerChannelFactory { private final ChannelSink sink = new LocalServerChannelSink(); /** * Creates a new instance. */ public DefaultLocalServerChannelFactory() { super(); } public LocalServerChannel newChannel(ChannelPipeline pipeline) { return new DefaultLocalServerChannel(this, pipeline, sink); } /** * Does nothing because this implementation does not require any external * resources. */ public void releaseExternalResources() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelPipelineCoverage.java0000644000175000017500000001243211167316731031566 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; /** * Specifies if the same instance of the annotated {@link ChannelHandler} type * can be added to more than one {@link ChannelPipeline}. *

* All handler types are expected to specify this annotation. Otherwise you * will be warned in runtime. Only two values are allowed for this annotation: * {@code "all"} and {@code "one"}. *

* Please note that this annotation does not prevent a handler annotated with * the value {@code "one"} from being added to more than one pipeline. This * annotation is used for documentation purpose only. * *

{@code ChannelPipelineCoverage("all")}

* * {@code "all"} means you can add the same instance of the annotated handler * type to more than one {@link ChannelPipeline}. It means the member * variables of the handler instance is shared among multiple channels and it * is designed to be OK to do so (or there's nothing to share.) The following * code shows an example of a handler type annotated with {@code "all"} value: * *
 * public class StatelessHandler extends SimpleChannelHandler {
 *
 *     // No state properties - you are safe to add the same instance to
 *     //                       multiple pipelines.
 *
 *     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *         // Prepend a length field to the message.
 *         ChannelBuffer body = (ChannelBuffer) e.getMessage();
 *         ChannelBuffer header = ChannelBuffers.buffer(4);
 *         header.writeInt(body.readableBytes());
 *
 *         // Create a message prepended with the header and send a new event.
 *         ChannelBuffer message = ChannelBuffers.wrappedBuffer(header, body);
 *         Channels.fireMessageReceived(ctx, message, e.getRemoteAddress());
 *     }
 *     ...
 * }
 * 
* *

{@code ChannelPipelineCoverage("one")}

* * {@code "one"} means you must create a new instance of the annotated handler * type for each new channel. It means the member variables of the handler * instance can not be shared at all, and violating this contract will lead * the handler to a race condition. A new handler instance is usually created * by {@link ChannelPipelineFactory}. The following code shows an example of a * handler type annotated with {@code "one"} value: * *
 * public class StatefulHandler extends SimpleChannelHandler {
 *
 *     // Stateful property - adding the same instance to multiple pipelines
 *     //                     can lead to a race condition.
 *     private int messageId;
 *
 *     public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *         // Prepend a message ID and length field to the message.
 *         ChannelBuffer body = (ChannelBuffer) e.getMessage();
 *         ChannelBuffer header = ChannelBuffers.buffer(8);
 *         header.writeInt(messageId);
 *         header.writeInt(body.readableBytes());
 *
 *         // Update the stateful property.
 *         messageId ++;
 *
 *         // Create a message prepended with the header and send a new event.
 *         ChannelBuffer message = ChannelBuffers.wrappedBuffer(header, body);
 *         Channels.fireMessageReceived(ctx, message, e.getRemoteAddress());
 *     }
 *     ...
 * }
 *
 * // Create a new handler instance per channel.
 * public class MyPipelineFactory implements ChannelPipelineFactory {
 *
 *     public ChannelPipeline getPipeline() {
 *         ChannelPipeline p = Channels.pipeline();
 *         p.addLast("handler", new StatefulHandler());
 *     }
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1158 $, $Date: 2009-04-09 00:03:53 -0700 (Thu, 09 Apr 2009) $ * * @apiviz.landmark */ @Inherited @Documented @Target(ElementType.TYPE) @Retention(RetentionPolicy.RUNTIME) public @interface ChannelPipelineCoverage { /** * {@code "all"} */ public static final String ALL = "all"; /** * {@code "one"} */ public static final String ONE = "one"; /** * The value of this annotation */ String value(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ExceptionEvent.java0000644000175000017500000000327111107230242027777 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link ChannelEvent} which represents the notification of an exception * raised by a {@link ChannelHandler} or an I/O thread. This event is for * going upstream only. Please refer to the {@link ChannelEvent} documentation * to find out what an upstream event and a downstream event are and what * fundamental differences they have. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 473 $, $Date: 2008-11-14 00:02:42 -0800 (Fri, 14 Nov 2008) $ */ public interface ExceptionEvent extends ChannelEvent { /** * Returns the raised exception. */ Throwable getCause(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/UpstreamMessageEvent.java0000644000175000017500000000537411216134140031155 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.jboss.netty.channel.Channels.*; import java.net.SocketAddress; import org.jboss.netty.util.internal.StringUtil; /** * The default upstream {@link MessageEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ * */ public class UpstreamMessageEvent implements MessageEvent { private final Channel channel; private final Object message; private final SocketAddress remoteAddress; /** * Creates a new instance. */ public UpstreamMessageEvent( Channel channel, Object message, SocketAddress remoteAddress) { if (channel == null) { throw new NullPointerException("channel"); } if (message == null) { throw new NullPointerException("message"); } this.channel = channel; this.message = message; this.remoteAddress = remoteAddress; } public Channel getChannel() { return channel; } public ChannelFuture getFuture() { return succeededFuture(getChannel()); } public Object getMessage() { return message; } public SocketAddress getRemoteAddress() { return remoteAddress; } @Override public String toString() { if (getRemoteAddress() == null) { return getChannel().toString() + " RECEIVED: " + StringUtil.stripControlCharacters(getMessage()); } else { return getChannel().toString() + " RECEIVED: " + StringUtil.stripControlCharacters(getMessage()) + ", " + getRemoteAddress(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelException.java0000644000175000017500000000366211057213775030312 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link RuntimeException} which is thrown when an I/O operation fails. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 184 $, $Date: 2008-09-02 03:39:57 -0700 (Tue, 02 Sep 2008) $ * * @apiviz.hidden */ public class ChannelException extends RuntimeException { private static final long serialVersionUID = 2908618315971075004L; /** * Creates a new exception. */ public ChannelException() { super(); } /** * Creates a new exception. */ public ChannelException(String message, Throwable cause) { super(message, cause); } /** * Creates a new exception. */ public ChannelException(String message) { super(message); } /** * Creates a new exception. */ public ChannelException(Throwable cause) { super(cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelPipeline.java0000644000175000017500000004502011175574066030117 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.Map; import java.util.NoSuchElementException; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.handler.execution.ExecutionHandler; import org.jboss.netty.handler.execution.OrderedMemoryAwareThreadPoolExecutor; import org.jboss.netty.handler.ssl.SslHandler; /** * A list of {@link ChannelHandler}s which handles or intercepts * {@link ChannelEvent}s of a {@link Channel}. {@link ChannelPipeline} * implements an advanced form of the * Intercepting * Filter pattern to give a user full control over how an event is handled * and how the {@link ChannelHandler}s in the pipeline interact with each other. * *

Creation of a pipeline

*

* It is recommended to create a new pipeline using the helper methods in * {@link Channels} rather than calling an individual implementation's * constructor: *

 * import static org.jboss.netty.channel.Channels.*;
 * ChannelPipeline pipeline = pipeline(); // same with Channels.pipeline()
 * 
* *

How an event flows in a pipeline

*

* The following diagram describes how {@link ChannelEvent}s are processed by * {@link ChannelHandler}s in a {@link ChannelPipeline} typically. * A {@link ChannelEvent} can be handled by either a {@link ChannelUpstreamHandler} * or a {@link ChannelDownstreamHandler} and be forwarded to the next or * previous handler by calling {@link ChannelHandlerContext#sendUpstream(ChannelEvent)} * or {@link ChannelHandlerContext#sendDownstream(ChannelEvent)}. The meaning * of the event is interpreted somewhat differently depending on whether it is * going upstream or going downstream. Please refer to {@link ChannelEvent} for * more information. * *

 *
 *                                            I/O Request
 *                                          via {@link Channel} or
 *                                      {@link ChannelHandlerContext}
 *                                                |
 *  +---------------------------------------------+--------------------+
 *  |                       ChannelPipeline       |                    |
 *  |                                            \|/                   |
 *  |       +----------------------+  +-----------+------------+       |
 *  |  LAST | Upstream Handler  N  |  | Downstream Handler  M  | LAST  |
 *  |   .   +----------+-----------+  +-----------+------------+   .   |
 *  |   .             /|\                         |                .   |
 *  |   .              |                         \|/               .   |
 *  |   .   +----------+-----------+  +-----------+------------+   .   |
 *  |   .   | Upstream Handler N-1 |  | Downstream Handler M-1 |   .   |
 *  |   .   +----------+-----------+  +-----------+------------+   .   |
 *  |   .             /|\                         .                .   |
 *  |   .              .                          .                .   |
 *  |   .      [ Going UPSTREAM ]        [ Going DOWNSTREAM ]      .   |
 *  |   .              .                          .                .   |
 *  |   .              .                         \|/               .   |
 *  |   .   +----------+-----------+  +-----------+------------+   .   |
 *  |   .   | Upstream Handler  2  |  | Downstream Handler  2  |   .   |
 *  |   .   +----------+-----------+  +-----------+------------+   .   |
 *  |   .             /|\                         |                .   |
 *  |   .              |                         \|/               .   |
 *  |   .   +----------+-----------+  +-----------+------------+   .   |
 *  | FIRST | Upstream Handler  1  |  | Downstream Handler  1  | FIRST |
 *  |       +----------+-----------+  +-----------+------------+       |
 *  |                 /|\                         |                    |
 *  +------------------+--------------------------+--------------------+
 *                     |                         \|/
 *  +------------------+--------------------------+--------------------+
 *  |             I/O Threads (Transport Implementation)               |
 *  +------------------------------------------------------------------+
 * 
* Please note that an upstream event flows from the first upstream handler * to the last upstream handler (i.e. to the next) and a downstream event * flows from the last downstream handler to the first downstream handler * (i.e. to the previous). *

* For example, let us assume that we created the following pipeline: *

 * ChannelPipeline p = Channels.pipeline();
 * p.addLast("1", new UpstreamHandlerA());
 * p.addLast("2", new UpstreamHandlerB());
 * p.addLast("3", new DownstreamHandlerA());
 * p.addLast("4", new DownstreamHandlerB());
 * p.addLast("5", new UpstreamHandlerX());
 * 
* In the example above, the class whose name starts with {@code Upstream} means * it is an upstream handler. The class whose name starts with * {@code Downstream} means it is a downstream handler. *

* In the given example configuration, the handler evaluation order is 1, 2, 3, * 4, 5 when an event goes upstream. When an event goes downstream, the order * is 5, 4, 3, 2, 1. On top of this principle, {@link ChannelPipeline} skips * the evaluation of certain handlers to shorten the stack depth: *

    *
  • 3 and 4 don't implement {@link ChannelUpstreamHandler}, and therefore the * actual evaluation order of an upstream event will be: 1, 2, and 5.
  • *
  • 1, 2, and 5 don't implement {@link ChannelDownstreamHandler}, and * therefore the actual evaluation order of a downstream event will be: * 4 and 3.
  • *
  • If 5 extended {@link SimpleChannelHandler} which implements both * {@link ChannelUpstreamHandler} and {@link ChannelDownstreamHandler}, the * evaluation order of an upstream and a downstream event could be 125 and * 543 respectively.
  • *
* *

Building a pipeline

*

* A user is supposed to have one or more {@link ChannelHandler}s in a * pipeline to receive I/O events (e.g. read) and to request I/O operations * (e.g. write and close). For example, a typical server will have the following * handlers in each channel's pipeline, but your mileage may vary depending on * the complexity and characteristics of the protocol and business logic: * *

    *
  1. Protocol Decoder - translates binary data (e.g. {@link ChannelBuffer}) * into a Java object.
  2. *
  3. Protocol Encoder - translates a Java object into binary data.
  4. *
  5. {@link ExecutionHandler} - applies a thread model.
  6. *
  7. Business Logic Handler - performs the actual business logic * (e.g. database access).
  8. *
* * and it could be represented as shown in the following example: * *
 * ChannelPipeline pipeline = {@link Channels#pipeline() Channels.pipeline()};
 * pipeline.addLast("decoder", new MyProtocolDecoder());
 * pipeline.addLast("encoder", new MyProtocolEncoder());
 * pipeline.addLast("executor", new {@link ExecutionHandler}(new {@link OrderedMemoryAwareThreadPoolExecutor}(16, 1048576, 1048576)));
 * pipeline.addLast("handler", new MyBusinessLogicHandler());
 * 
* *

Thread safety

*

* A {@link ChannelHandler} can be added or removed at any time because a * {@link ChannelPipeline} is thread safe. For example, you can insert a * {@link SslHandler} when sensitive information is about to be exchanged, * and remove it after the exchange. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1260 $, $Date: 2009-04-28 05:36:06 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark * @apiviz.composedOf org.jboss.netty.channel.ChannelHandlerContext * @apiviz.owns org.jboss.netty.channel.ChannelHandler * @apiviz.uses org.jboss.netty.channel.ChannelSink - - sends events downstream */ public interface ChannelPipeline { /** * Inserts a {@link ChannelHandler} at the first position of this pipeline. * * @param name the name of the handler to insert first * @param handler the handler to insert first * * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified name or handler is {@code null} */ void addFirst (String name, ChannelHandler handler); /** * Appends a {@link ChannelHandler} at the last position of this pipeline. * * @param name the name of the handler to append * @param handler the handler to append * * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified name or handler is {@code null} */ void addLast (String name, ChannelHandler handler); /** * Inserts a {@link ChannelHandler} before an existing handler of this * pipeline. * * @param baseName the name of the existing handler * @param name the name of the handler to insert before * @param handler the handler to insert before * * @throws NoSuchElementException * if there's no such entry with the specified {@code baseName} * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified baseName, name, or handler is {@code null} */ void addBefore(String baseName, String name, ChannelHandler handler); /** * Inserts a {@link ChannelHandler} after an existing handler of this * pipeline. * * @param baseName the name of the existing handler * @param name the name of the handler to insert after * @param handler the handler to insert after * * @throws NoSuchElementException * if there's no such entry with the specified {@code baseName} * @throws IllegalArgumentException * if there's an entry with the same name already in the pipeline * @throws NullPointerException * if the specified baseName, name, or handler is {@code null} */ void addAfter (String baseName, String name, ChannelHandler handler); /** * Removes the specified {@link ChannelHandler} from this pipeline. * * @throws NoSuchElementException * if there's no such handler in this pipeline * @throws NullPointerException * if the specified handler is {@code null} */ void remove(ChannelHandler handler); /** * Removes the {@link ChannelHandler} with the specified name from this * pipeline. * * @return the removed handler * * @throws NoSuchElementException * if there's no such handler with the specified name in this pipeline * @throws NullPointerException * if the specified name is {@code null} */ ChannelHandler remove(String name); /** * Removes the {@link ChannelHandler} of the specified type from this * pipeline * * @param the type of the handler * @param handlerType the type of the handler * * @return the removed handler * * @throws NoSuchElementException * if there's no such handler of the specified type in this pipeline * @throws NullPointerException * if the specified handler type is {@code null} */ T remove(Class handlerType); /** * Removes the first {@link ChannelHandler} in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if this pipeline is empty */ ChannelHandler removeFirst(); /** * Removes the last {@link ChannelHandler} in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if this pipeline is empty */ ChannelHandler removeLast(); /** * Replaces the specified {@link ChannelHandler} with a new handler in * this pipeline. * * @throws NoSuchElementException * if the specified old handler does not exist in this pipeline * @throws IllegalArgumentException * if a handler with the specified new name already exists in this * pipeline, except for the handler to be replaced * @throws NullPointerException * if the specified old handler, new name, or new handler is * {@code null} */ void replace(ChannelHandler oldHandler, String newName, ChannelHandler newHandler); /** * Replaces the {@link ChannelHandler} of the specified name with a new * handler in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if the handler with the specified old name does not exist in this pipeline * @throws IllegalArgumentException * if a handler with the specified new name already exists in this * pipeline, except for the handler to be replaced * @throws NullPointerException * if the specified old handler, new name, or new handler is * {@code null} */ ChannelHandler replace(String oldName, String newName, ChannelHandler newHandler); /** * Replaces the {@link ChannelHandler} of the specified type with a new * handler in this pipeline. * * @return the removed handler * * @throws NoSuchElementException * if the handler of the specified old handler type does not exist * in this pipeline * @throws IllegalArgumentException * if a handler with the specified new name already exists in this * pipeline, except for the handler to be replaced * @throws NullPointerException * if the specified old handler, new name, or new handler is * {@code null} */ T replace(Class oldHandlerType, String newName, ChannelHandler newHandler); /** * Returns the first {@link ChannelHandler} in this pipeline. * * @return the first handler. {@code null} if this pipeline is empty. */ ChannelHandler getFirst(); /** * Returns the last {@link ChannelHandler} in this pipeline. * * @return the last handler. {@code null} if this pipeline is empty. */ ChannelHandler getLast(); /** * Returns the {@link ChannelHandler} with the specified name in this * pipeline. * * @return the handler with the specified name. * {@code null} if there's no such handler in this pipeline. */ ChannelHandler get(String name); /** * Returns the {@link ChannelHandler} of the specified type in this * pipeline. * * @return the handler of the specified handler type. * {@code null} if there's no such handler in this pipeline. */ T get(Class handlerType); /** * Returns the context object of the specified {@link ChannelHandler} in * this pipeline. * * @return the context object of the specified handler. * {@code null} if there's no such handler in this pipeline. */ ChannelHandlerContext getContext(ChannelHandler handler); /** * Returns the context object of the {@link ChannelHandler} with the * specified name in this pipeline. * * @return the context object of the handler with the specified name. * {@code null} if there's no such handler in this pipeline. */ ChannelHandlerContext getContext(String name); /** * Returns the context object of the {@link ChannelHandler} of the * specified type in this pipeline. * * @return the context object of the handler of the specified type. * {@code null} if there's no such handler in this pipeline. */ ChannelHandlerContext getContext(Class handlerType); /** * Sends the specified {@link ChannelEvent} to the first * {@link ChannelUpstreamHandler} in this pipeline. * * @throws NullPointerException * if the specified event is {@code null} */ void sendUpstream(ChannelEvent e); /** * Sends the specified {@link ChannelEvent} to the last * {@link ChannelDownstreamHandler} in this pipeline. * * @throws NullPointerException * if the specified event is {@code null} */ void sendDownstream(ChannelEvent e); /** * Returns the {@link Channel} that this pipeline is attached to. * * @return the channel. {@code null} if this pipeline is not attached yet. */ Channel getChannel(); /** * Returns the {@link ChannelSink} that this pipeline is attached to. * * @return the sink. {@code null} if this pipeline is not attached yet. */ ChannelSink getSink(); /** * Attaches this pipeline to the specified {@link Channel} and * {@link ChannelSink}. Once a pipeline is attached, it can't be detached * nor attached again. * * @throws IllegalStateException if this pipeline is attached already */ void attach(Channel channel, ChannelSink sink); /** * Returns {@code true} if and only if this pipeline is attached to * a {@link Channel}. */ boolean isAttached(); /** * Converts this pipeline into an ordered {@link Map} whose keys are * handler names and whose values are handlers. */ Map toMap(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ChannelLocal.java0000644000175000017500000000777511216136021027400 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.concurrent.ConcurrentMap; import org.jboss.netty.util.internal.ConcurrentIdentityWeakKeyHashMap; /** * A global variable that is local to a {@link Channel}. Think of this as a * variation of {@link ThreadLocal} whose key is a {@link Channel} rather than * a {@link Thread#currentThread()}. One difference is that you always have to * specify the {@link Channel} to access the variable. *

* As an alternative, you might want to use an attachment storage provided by * {@link ChannelHandlerContext}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1407 $, $Date: 2009-06-17 02:49:05 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.stereotype utility */ public class ChannelLocal { private final ConcurrentMap map = new ConcurrentIdentityWeakKeyHashMap(); /** * Creates a {@link Channel} local variable. */ public ChannelLocal() { super(); } /** * Returns the initial value of the variable. By default, it returns * {@code null}. Override it to change the initial value. */ protected T initialValue(@SuppressWarnings("unused") Channel channel) { return null; } /** * Returns the value of this variable. */ public T get(Channel channel) { if (channel == null) { throw new NullPointerException("channel"); } T value = map.get(channel); if (value == null) { value = initialValue(channel); if (value != null) { T oldValue = setIfAbsent(channel, value); if (oldValue != null) { value = oldValue; } } } return value; } /** * Sets the value of this variable. * * @return the old value. {@code null} if there was no old value. */ public T set(Channel channel, T value) { if (value == null) { return remove(channel); } else { if (channel == null) { throw new NullPointerException("channel"); } return map.put(channel, value); } } /** * Sets the value of this variable only when no value was set. * * @return {@code null} if the specified value was set. * An existing value if failed to set. */ public T setIfAbsent(Channel channel, T value) { if (value == null) { return get(channel); } else { if (channel == null) { throw new NullPointerException("channel"); } return map.putIfAbsent(channel, value); } } /** * Removes the variable. * * @return the removed value. {@code null} if no value was set. */ public T remove(Channel channel) { if (channel == null) { throw new NullPointerException("channel"); } return map.remove(channel); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/0000755000175000017500000000000011316313132025150 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioServerChannelSink.java0000644000175000017500000000576411151260632032254 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import java.net.SocketAddress; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 941 $, $Date: 2009-02-25 07:19:54 -0800 (Wed, 25 Feb 2009) $ */ final class XnioServerChannelSink extends AbstractChannelSink { private final XnioClientChannelSink acceptedChannelSink = new XnioClientChannelSink(); XnioServerChannelSink() { super(); } public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { Channel channel = e.getChannel(); if (channel instanceof DefaultXnioServerChannel) { handleServerSocket(e); } else if (channel instanceof XnioChannel) { acceptedChannelSink.eventSunk(pipeline, e); } else { throw new Error("should not reach here"); } } private void handleServerSocket(ChannelEvent e) { if (!(e instanceof ChannelStateEvent)) { return; } ChannelStateEvent event = (ChannelStateEvent) e; DefaultXnioServerChannel channel = (DefaultXnioServerChannel) event.getChannel(); ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { channel.closeNow(future); } break; case BOUND: if (value != null) { channel.bindNow(future, (SocketAddress) value); } else { channel.closeNow(future); } break; } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioServerChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioServerChannelFactory.jav0000644000175000017500000000445411216405642032615 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ServerChannelFactory; import org.jboss.xnio.channels.BoundServer; /** * A {@link ServerChannelFactory} which uses * JBoss XNIO as its I/O provider. *

* Please note that you must specify an {@link XnioAcceptedChannelHandlerFactory} * when you create a {@link BoundServer} to integrate XNIO into Netty. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1427 $, $Date: 2009-06-18 02:40:50 -0700 (Thu, 18 Jun 2009) $ */ @SuppressWarnings("unchecked") public class XnioServerChannelFactory implements ServerChannelFactory { private final BoundServer xnioServer; final XnioServerChannelSink sink; public XnioServerChannelFactory(BoundServer xnioServer) { if (xnioServer == null) { throw new NullPointerException("xnioServer"); } this.xnioServer = xnioServer; sink = new XnioServerChannelSink(); } public XnioServerChannel newChannel(ChannelPipeline pipeline) { return new DefaultXnioServerChannel(this, pipeline, sink, xnioServer); } public void releaseExternalResources() { // Nothing to release. } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/DefaultXnioServerChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/DefaultXnioServerChannel.jav0000644000175000017500000001161711205427501032565 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; import java.net.SocketAddress; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.xnio.IoFuture; import org.jboss.xnio.IoUtils; import org.jboss.xnio.channels.BoundChannel; import org.jboss.xnio.channels.BoundServer; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1296 $, $Date: 2009-05-21 21:51:13 -0700 (Thu, 21 May 2009) $ */ @SuppressWarnings("unchecked") final class DefaultXnioServerChannel extends BaseXnioChannel implements XnioServerChannel { private static final Object bindLock = new Object(); final BoundServer xnioServer; DefaultXnioServerChannel( XnioServerChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, BoundServer xnioServer) { super(null, factory, pipeline, sink, new DefaultXnioChannelConfig()); this.xnioServer = xnioServer; fireChannelOpen(this); } @Override public XnioServerChannelFactory getFactory() { return (XnioServerChannelFactory) super.getFactory(); } @Override public ChannelFuture connect(SocketAddress remoteAddress) { return getUnsupportedOperationFuture(); } @Override public ChannelFuture disconnect() { return getUnsupportedOperationFuture(); } @Override public int getInterestOps() { return OP_NONE; } @Override public ChannelFuture setInterestOps(int interestOps) { return getUnsupportedOperationFuture(); } @Override protected void setInterestOpsNow(int interestOps) { // Ignore. } void bindNow(ChannelFuture future, SocketAddress localAddress) { try { synchronized (bindLock) { IoFuture bindFuture = xnioServer.bind(localAddress); for (;;) { IoFuture.Status bindStatus = bindFuture.await(); switch (bindStatus) { case WAITING: // Keep waiting for the result. continue; case CANCELLED: throw new Error("should not reach here"); case DONE: break; case FAILED: throw bindFuture.getException(); default: throw new Error("should not reach here: " + bindStatus); } // Break the loop if done. break; } BoundChannel xnioChannel = bindFuture.get(); this.xnioChannel = xnioChannel; XnioChannelRegistry.registerServerChannel(this); } future.setSuccess(); fireChannelBound(this, getLocalAddress()); } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(this, t); } } @Override void closeNow(ChannelFuture future) { SocketAddress localAddress = getLocalAddress(); boolean bound = localAddress != null; try { if (setClosed()) { future.setSuccess(); synchronized (bindLock) { IoUtils.safeClose(xnioChannel); XnioChannelRegistry.unregisterServerChannel(localAddress); XnioChannelRegistry.unregisterChannelMapping(this); } if (bound) { fireChannelUnbound(this); } fireChannelClosed(this); } else { future.setSuccess(); } } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(this, t); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/AbstractXnioChannelHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/AbstractXnioChannelHandler.j0000644000175000017500000002363711216747541032544 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.net.SocketAddress; import java.nio.ByteBuffer; import java.nio.channels.AsynchronousCloseException; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.util.Queue; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.xnio.IoHandler; import org.jboss.xnio.channels.MultipointReadResult; import org.jboss.xnio.channels.MultipointReadableMessageChannel; import org.jboss.xnio.channels.MultipointWritableMessageChannel; import org.jboss.xnio.channels.ReadableMessageChannel; import org.jboss.xnio.channels.SuspendableReadChannel; import org.jboss.xnio.channels.SuspendableWriteChannel; import org.jboss.xnio.channels.WritableMessageChannel; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ @SuppressWarnings("unchecked") abstract class AbstractXnioChannelHandler implements IoHandler { protected AbstractXnioChannelHandler() { super(); } public void handleReadable(java.nio.channels.Channel channel) { BaseXnioChannel c = XnioChannelRegistry.getChannel(channel); boolean closed = false; ReceiveBufferSizePredictor predictor = c.getConfig().getReceiveBufferSizePredictor(); ChannelBufferFactory bufferFactory = c.getConfig().getBufferFactory(); ChannelBuffer buf = bufferFactory.getBuffer(predictor.nextReceiveBufferSize()); SocketAddress remoteAddress = null; Throwable exception = null; if (channel instanceof ScatteringByteChannel) { try { while (buf.writable()) { int readBytes = buf.writeBytes((ScatteringByteChannel) channel, buf.writableBytes()); if (readBytes == 0) { break; } else if (readBytes < 0) { closed = true; break; } } } catch (IOException e) { exception = e; closed = true; } } else if (channel instanceof MultipointReadableMessageChannel) { ByteBuffer nioBuf = buf.toByteBuffer(); try { MultipointReadResult res = ((MultipointReadableMessageChannel) channel).receive(nioBuf); if (res != null) { buf = ChannelBuffers.wrappedBuffer(nioBuf); remoteAddress = (SocketAddress) res.getSourceAddress(); } } catch (IOException e) { exception = e; closed = true; } } else if (channel instanceof ReadableMessageChannel) { ByteBuffer nioBuf = buf.toByteBuffer(); try { int readBytes = ((ReadableMessageChannel) channel).receive(nioBuf); if (readBytes > 0) { buf = ChannelBuffers.wrappedBuffer(nioBuf); } else if (readBytes < 0) { closed = true; } } catch (IOException e) { exception = e; closed = true; } } if (buf.readable()) { // Update the predictor. predictor.previousReceiveBufferSize(buf.readableBytes()); // Fire the event. fireMessageReceived(c, buf, remoteAddress); } if (exception != null) { fireExceptionCaught(c, exception); } if (closed) { close(c); } else { resumeRead(channel); } } public void handleWritable(java.nio.channels.Channel channel) { BaseXnioChannel c = XnioChannelRegistry.getChannel(channel); int writtenBytes = 0; boolean open = true; boolean addOpWrite = false; MessageEvent evt; ChannelBuffer buf; int bufIdx; Queue writeBuffer = c.writeBuffer; synchronized (c.writeLock) { evt = c.currentWriteEvent; for (;;) { if (evt == null) { evt = writeBuffer.poll(); if (evt == null) { c.currentWriteEvent = null; break; } buf = (ChannelBuffer) evt.getMessage(); bufIdx = buf.readerIndex(); } else { buf = (ChannelBuffer) evt.getMessage(); bufIdx = c.currentWriteIndex; } try { final int writeSpinCount = c.getConfig().getWriteSpinCount(); boolean sent = false; for (int i = writeSpinCount; i > 0; i --) { if (channel instanceof GatheringByteChannel) { int localWrittenBytes = buf.getBytes( bufIdx, (GatheringByteChannel) channel, buf.writerIndex() - bufIdx); if (localWrittenBytes != 0) { bufIdx += localWrittenBytes; writtenBytes += localWrittenBytes; break; } } else if (channel instanceof MultipointWritableMessageChannel) { ByteBuffer nioBuf = buf.toByteBuffer(bufIdx, buf.writerIndex() - bufIdx); int nioBufSize = nioBuf.remaining(); SocketAddress remoteAddress = evt.getRemoteAddress(); if (remoteAddress == null) { remoteAddress = c.getRemoteAddress(); } sent = ((MultipointWritableMessageChannel) channel).send(remoteAddress, nioBuf); if (sent) { bufIdx += nioBufSize; writtenBytes += nioBufSize; break; } } else if (channel instanceof WritableMessageChannel) { ByteBuffer nioBuf = buf.toByteBuffer(bufIdx, buf.writerIndex() - bufIdx); int nioBufSize = nioBuf.remaining(); sent = ((WritableMessageChannel) channel).send(nioBuf); if (sent) { bufIdx += nioBufSize; writtenBytes += nioBufSize; break; } } else { throw new IllegalArgumentException("Unsupported channel type: " + channel.getClass().getName()); } } if (bufIdx == buf.writerIndex() || sent) { // Successful write - proceed to the next message. evt.getFuture().setSuccess(); evt = null; } else { // Not written fully - perhaps the kernel buffer is full. c.currentWriteEvent = evt; c.currentWriteIndex = bufIdx; addOpWrite = true; break; } } catch (AsynchronousCloseException e) { // Doesn't need a user attention - ignore. } catch (Throwable t) { evt.getFuture().setFailure(t); evt = null; fireExceptionCaught(c, t); if (t instanceof IOException) { open = false; c.closeNow(succeededFuture(c)); } } } } if (writtenBytes > 0) { fireWriteComplete(c, writtenBytes); } if (open) { if (addOpWrite && channel instanceof SuspendableWriteChannel) { ((SuspendableWriteChannel) channel).resumeWrites(); } } } public void handleClosed(java.nio.channels.Channel channel) { close(XnioChannelRegistry.getChannel(channel)); } protected void resumeRead(java.nio.channels.Channel channel) { if (channel instanceof SuspendableReadChannel) { ((SuspendableReadChannel) channel).resumeReads(); } } protected void close(BaseXnioChannel c) { if (c != null) { c.closeNow(c.getCloseFuture()); } } } ././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioAcceptedChannelHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioAcceptedChannelHandler.j0000644000175000017500000000641711216750342032477 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; import java.net.SocketAddress; import org.jboss.xnio.IoUtils; import org.jboss.xnio.channels.BoundChannel; import org.jboss.xnio.channels.MultipointMessageChannel; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1483 $, $Date: 2009-06-19 10:54:42 -0700 (Fri, 19 Jun 2009) $ */ @SuppressWarnings("unchecked") final class XnioAcceptedChannelHandler extends AbstractXnioChannelHandler { public void handleOpened(java.nio.channels.Channel channel) { // Get the parent channel DefaultXnioServerChannel parent = null; if (channel instanceof BoundChannel) { SocketAddress localAddress = (SocketAddress) ((BoundChannel) channel).getLocalAddress(); parent = XnioChannelRegistry.getServerChannel(localAddress); if (parent == null) { // An accepted channel with no parent // probably a race condition or a port not bound by Netty. IoUtils.safeClose(channel); return; } } else { // Should not reach here. IoUtils.safeClose(channel); return; } if (parent.xnioChannel instanceof MultipointMessageChannel) { // Multipoint channel XnioChannelRegistry.registerChannelMapping(parent); } else { // Accepted child channel try { BaseXnioChannel c = new XnioAcceptedChannel( parent, parent.getFactory(), parent.getConfig().getPipelineFactory().getPipeline(), parent.getFactory().sink); c.xnioChannel = channel; fireChannelOpen(c); if (c.isBound()) { fireChannelBound(c, c.getLocalAddress()); if (c.isConnected()) { fireChannelConnected(c, c.getRemoteAddress()); } } XnioChannelRegistry.registerChannelMapping(c); } catch (Throwable t) { t.printStackTrace(); } } // Start to read. resumeRead(channel); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioChannelRegistry.java0000644000175000017500000001046211165336702031767 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import java.net.InetAddress; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.ConcurrentMap; import org.jboss.netty.util.internal.ConcurrentHashMap; import org.jboss.netty.util.internal.ConcurrentIdentityHashMap; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ final class XnioChannelRegistry { private static final ConcurrentMap serverChannels = new ConcurrentHashMap(); private static final ConcurrentMap mapping = new ConcurrentIdentityHashMap(); private static final InetAddress ANY_IPV4; private static final InetAddress ANY_IPV6; static { InetAddress any4 = null; try { any4 = InetAddress.getByAddress(new byte[] { 0, 0, 0, 0 }); } catch (Throwable t) { // Ignore } finally { ANY_IPV4 = any4; } InetAddress any6 = null; try { any6 = InetAddress.getByAddress(new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }); } catch (Throwable t) { // Ignore } finally { ANY_IPV6 = any6; } } static void registerServerChannel(DefaultXnioServerChannel channel) { SocketAddress localAddress = channel.getLocalAddress(); if (localAddress == null) { throw new IllegalStateException("cannot register an unbound channel"); } if (serverChannels.putIfAbsent(localAddress, channel) != null) { throw new IllegalStateException("duplicate local address: " + localAddress); } } static void unregisterServerChannel(SocketAddress localAddress) { if (localAddress == null) { return; } serverChannels.remove(localAddress); } static DefaultXnioServerChannel getServerChannel(SocketAddress localAddress) { // XXX: More IPv4 <-> IPv6 address conversion DefaultXnioServerChannel answer = serverChannels.get(localAddress); if (answer == null && localAddress instanceof InetSocketAddress) { InetSocketAddress a = (InetSocketAddress) localAddress; answer = serverChannels.get(new InetSocketAddress(ANY_IPV6, a.getPort())); if (answer == null) { answer = serverChannels.get(new InetSocketAddress(ANY_IPV4, a.getPort())); } } return answer; } static void registerChannelMapping(BaseXnioChannel channel) { if (mapping.putIfAbsent(channel.xnioChannel, channel) != null) { throw new IllegalStateException("duplicate mapping: " + channel); } } static void unregisterChannelMapping(BaseXnioChannel channel) { java.nio.channels.Channel xnioChannel = channel.xnioChannel; if (xnioChannel != null) { mapping.remove(xnioChannel); } } static BaseXnioChannel getChannel(java.nio.channels.Channel channel) { return mapping.get(channel); } private XnioChannelRegistry() { super(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioChannelConfig.java0000644000175000017500000000767011165336702031373 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import java.nio.ByteBuffer; import java.nio.channels.WritableByteChannel; import org.jboss.netty.channel.AdaptiveReceiveBufferSizePredictor; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.channel.socket.SocketChannelConfig; /** * A {@link ChannelConfig} for an {@link XnioChannel}. * *

Available options

* * In addition to the options provided by {@link ChannelConfig} and * {@link SocketChannelConfig}, {@link XnioChannelConfig} allows the * following options in the option map: * * * * * * * * * *
NameAssociated setter method
{@code "writeSpinCount"}{@link #setWriteSpinCount(int)}
{@code "receiveBufferSizePredictor"}{@link #setReceiveBufferSizePredictor(ReceiveBufferSizePredictor)}
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public interface XnioChannelConfig extends ChannelConfig { int getWriteBufferHighWaterMark(); void setWriteBufferHighWaterMark(int writeBufferHighWaterMark); int getWriteBufferLowWaterMark(); void setWriteBufferLowWaterMark(int writeBufferLowWaterMark); /** * Returns the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. */ int getWriteSpinCount(); /** * Sets the maximum loop count for a write operation until * {@link WritableByteChannel#write(ByteBuffer)} returns a non-zero value. * It is similar to what a spin lock is used for in concurrency programming. * It improves memory utilization and write throughput depending on * the platform that JVM runs on. The default value is {@code 16}. * * @throws IllegalArgumentException * if the specified value is {@code 0} or less than {@code 0} */ void setWriteSpinCount(int writeSpinCount); /** * Returns the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link AdaptiveReceiveBufferSizePredictor}. */ ReceiveBufferSizePredictor getReceiveBufferSizePredictor(); /** * Sets the {@link ReceiveBufferSizePredictor} which predicts the * number of readable bytes in the socket receive buffer. The default * predictor is {@link AdaptiveReceiveBufferSizePredictor}. */ void setReceiveBufferSizePredictor(ReceiveBufferSizePredictor predictor); }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioServerChannel.java0000644000175000017500000000276211216405642031426 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import org.jboss.netty.channel.ServerChannel; /** * A {@link ServerChannel} which uses * JBoss XNIO as its I/O provider. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1427 $, $Date: 2009-06-18 02:40:50 -0700 (Thu, 18 Jun 2009) $ */ public interface XnioServerChannel extends XnioChannel, ServerChannel { XnioServerChannelFactory getFactory(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/BaseXnioChannel.java0000644000175000017500000002140111205427501031015 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; import java.net.SocketAddress; import java.nio.channels.GatheringByteChannel; import java.util.Queue; import java.util.concurrent.atomic.AtomicInteger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.internal.LinkedTransferQueue; import org.jboss.netty.util.internal.ThreadLocalBoolean; import org.jboss.xnio.IoUtils; import org.jboss.xnio.channels.BoundChannel; import org.jboss.xnio.channels.ConnectedChannel; import org.jboss.xnio.channels.MultipointWritableMessageChannel; import org.jboss.xnio.channels.WritableMessageChannel; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 937 $, $Date: 2009-02-25 19:43:03 +0900 (Wed, 25 Feb 2009) $ */ @SuppressWarnings("unchecked") class BaseXnioChannel extends AbstractChannel implements XnioChannel { private final XnioChannelConfig config; volatile java.nio.channels.Channel xnioChannel; final Object writeLock = new Object(); final Queue writeBuffer = new WriteBuffer(); final AtomicInteger writeBufferSize = new AtomicInteger(); final AtomicInteger highWaterMarkCounter = new AtomicInteger(); MessageEvent currentWriteEvent; int currentWriteIndex; BaseXnioChannel( Channel parent, ChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, XnioChannelConfig config) { super(parent, factory, pipeline, sink); this.config = config; } public XnioChannelConfig getConfig() { return config; } public SocketAddress getLocalAddress() { java.nio.channels.Channel xnioChannel = this.xnioChannel; if (!isOpen() || !(xnioChannel instanceof BoundChannel)) { return null; } return (SocketAddress) ((BoundChannel) xnioChannel).getLocalAddress(); } public SocketAddress getRemoteAddress() { java.nio.channels.Channel xnioChannel = this.xnioChannel; if (!isOpen() || !(xnioChannel instanceof ConnectedChannel)) { return null; } return (SocketAddress) ((ConnectedChannel) xnioChannel).getPeerAddress(); } public boolean isBound() { return getLocalAddress() != null; } public boolean isConnected() { return getRemoteAddress() != null; } @Override public int getInterestOps() { if (!isOpen()) { return Channel.OP_WRITE; } int interestOps = getRawInterestOps(); int writeBufferSize = this.writeBufferSize.get(); if (writeBufferSize != 0) { if (highWaterMarkCounter.get() > 0) { int lowWaterMark = getConfig().getWriteBufferLowWaterMark(); if (writeBufferSize >= lowWaterMark) { interestOps |= Channel.OP_WRITE; } else { interestOps &= ~Channel.OP_WRITE; } } else { int highWaterMark = getConfig().getWriteBufferHighWaterMark(); if (writeBufferSize >= highWaterMark) { interestOps |= Channel.OP_WRITE; } else { interestOps &= ~Channel.OP_WRITE; } } } else { interestOps &= ~Channel.OP_WRITE; } return interestOps; } int getRawInterestOps() { return super.getInterestOps(); } void setRawInterestOpsNow(int interestOps) { super.setInterestOpsNow(interestOps); } @Override public ChannelFuture write(Object message) { java.nio.channels.Channel xnioChannel = this.xnioChannel; if (xnioChannel instanceof MultipointWritableMessageChannel) { SocketAddress remoteAddress = getRemoteAddress(); if (remoteAddress != null) { return write(message, remoteAddress); } else { return getUnsupportedOperationFuture(); } } if (xnioChannel instanceof GatheringByteChannel || xnioChannel instanceof WritableMessageChannel) { return super.write(message); } else { return getUnsupportedOperationFuture(); } } @Override public ChannelFuture write(Object message, SocketAddress remoteAddress) { if (remoteAddress == null) { return write(message); } java.nio.channels.Channel xnioChannel = this.xnioChannel; if (xnioChannel instanceof MultipointWritableMessageChannel) { return super.write(message); } else { return getUnsupportedOperationFuture(); } } void closeNow(ChannelFuture future) { SocketAddress localAddress = getLocalAddress(); SocketAddress remoteAddress = getRemoteAddress(); if (!setClosed()) { future.setSuccess(); return; } try { IoUtils.safeClose(xnioChannel); xnioChannel = null; XnioChannelRegistry.unregisterChannelMapping(this); future.setSuccess(); if (remoteAddress != null) { fireChannelDisconnected(this); } if (localAddress != null) { fireChannelUnbound(this); } fireChannelClosed(this); } catch (Throwable t) { future.setFailure(t); fireExceptionCaught(this, t); } } private final class WriteBuffer extends LinkedTransferQueue { private final ThreadLocalBoolean notifying = new ThreadLocalBoolean(); WriteBuffer() { super(); } @Override public boolean offer(MessageEvent e) { boolean success = super.offer(e); assert success; int messageSize = ((ChannelBuffer) e.getMessage()).readableBytes(); int newWriteBufferSize = writeBufferSize.addAndGet(messageSize); int highWaterMark = getConfig().getWriteBufferHighWaterMark(); if (newWriteBufferSize >= highWaterMark) { if (newWriteBufferSize - messageSize < highWaterMark) { highWaterMarkCounter.incrementAndGet(); if (!notifying.get()) { notifying.set(Boolean.TRUE); fireChannelInterestChanged(BaseXnioChannel.this); notifying.set(Boolean.FALSE); } } } return true; } @Override public MessageEvent poll() { MessageEvent e = super.poll(); if (e != null) { int messageSize = ((ChannelBuffer) e.getMessage()).readableBytes(); int newWriteBufferSize = writeBufferSize.addAndGet(-messageSize); int lowWaterMark = getConfig().getWriteBufferLowWaterMark(); if (newWriteBufferSize == 0 || newWriteBufferSize < lowWaterMark) { if (newWriteBufferSize + messageSize >= lowWaterMark) { highWaterMarkCounter.decrementAndGet(); if (!notifying.get()) { notifying.set(Boolean.TRUE); fireChannelInterestChanged(BaseXnioChannel.this); notifying.set(Boolean.FALSE); } } } } return e; } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioAcceptedChannelHandlerFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioAcceptedChannelHandlerFa0000644000175000017500000000341011216404661032504 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import org.jboss.xnio.IoHandler; import org.jboss.xnio.IoHandlerFactory; import org.jboss.xnio.channels.BoundServer; /** * An XNIO {@link IoHandlerFactory} implementation that must be specified when * you create a {@link BoundServer} to integrate XNIO into Netty. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1426 $, $Date: 2009-06-18 02:32:33 -0700 (Thu, 18 Jun 2009) $ */ public class XnioAcceptedChannelHandlerFactory implements IoHandlerFactory { private final XnioAcceptedChannelHandler handler = new XnioAcceptedChannelHandler(); public IoHandler createHandler() { return handler; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioClientChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioClientChannelFactory.jav0000644000175000017500000000425211216405764032566 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.xnio.Connector; /** * A client-side {@link ChannelFactory} which uses * JBoss XNIO as its I/O provider. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1428 $, $Date: 2009-06-18 02:42:12 -0700 (Thu, 18 Jun 2009) $ */ @SuppressWarnings("unchecked") public class XnioClientChannelFactory implements ChannelFactory { private final Connector xnioConnector; private final XnioClientChannelSink sink; public XnioClientChannelFactory(Connector xnioConnector) { if (xnioConnector == null) { throw new NullPointerException("xnioConnector"); } this.xnioConnector = xnioConnector; sink = new XnioClientChannelSink(); } public Channel newChannel(ChannelPipeline pipeline) { return new XnioClientChannel(this, pipeline, sink, xnioConnector); } public void releaseExternalResources() { // Nothing to release. } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/DefaultXnioChannelConfig.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/DefaultXnioChannelConfig.jav0000644000175000017500000001666111165336702032537 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import java.util.Map; import java.util.Map.Entry; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.HeapChannelBufferFactory; import org.jboss.netty.channel.AdaptiveReceiveBufferSizePredictor; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ReceiveBufferSizePredictor; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.ConversionUtil; /** * The default {@link XnioChannelConfig} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ final class DefaultXnioChannelConfig implements XnioChannelConfig { private static final InternalLogger logger = InternalLoggerFactory.getInstance(DefaultXnioChannelConfig.class); private volatile ChannelBufferFactory bufferFactory = HeapChannelBufferFactory.getInstance(); private volatile ChannelPipelineFactory pipelineFactory; private volatile int writeBufferHighWaterMark = 64 * 1024; private volatile int writeBufferLowWaterMark = 32 * 1024; private volatile ReceiveBufferSizePredictor predictor = new AdaptiveReceiveBufferSizePredictor(); private volatile int writeSpinCount = 16; DefaultXnioChannelConfig() { super(); } public void setOptions(Map options) { for (Entry e: options.entrySet()) { setOption(e.getKey(), e.getValue()); } if (getWriteBufferHighWaterMark() < getWriteBufferLowWaterMark()) { // Recover the integrity of the configuration with a sensible value. setWriteBufferLowWaterMark0(getWriteBufferHighWaterMark() >>> 1); // Notify the user about misconfiguration. logger.warn( "writeBufferLowWaterMark cannot be greater than " + "writeBufferHighWaterMark; setting to the half of the " + "writeBufferHighWaterMark."); } } public boolean setOption(String key, Object value) { if (key.equals("pipelineFactory")) { setPipelineFactory((ChannelPipelineFactory) value); } else if (key.equals("bufferFactory")) { setBufferFactory((ChannelBufferFactory) value); } else if (key.equals("writeBufferHighWaterMark")) { setWriteBufferHighWaterMark0(ConversionUtil.toInt(value)); } else if (key.equals("writeBufferLowWaterMark")) { setWriteBufferLowWaterMark0(ConversionUtil.toInt(value)); } else if (key.equals("writeSpinCount")) { setWriteSpinCount(ConversionUtil.toInt(value)); } else if (key.equals("receiveBufferSizePredictor")) { setReceiveBufferSizePredictor((ReceiveBufferSizePredictor) value); } else { return false; } return true; } public int getWriteBufferHighWaterMark() { return writeBufferHighWaterMark; } public void setWriteBufferHighWaterMark(int writeBufferHighWaterMark) { if (writeBufferHighWaterMark < getWriteBufferLowWaterMark()) { throw new IllegalArgumentException( "writeBufferHighWaterMark cannot be less than " + "writeBufferLowWaterMark (" + getWriteBufferLowWaterMark() + "): " + writeBufferHighWaterMark); } setWriteBufferHighWaterMark0(writeBufferHighWaterMark); } private void setWriteBufferHighWaterMark0(int writeBufferHighWaterMark) { if (writeBufferHighWaterMark < 0) { throw new IllegalArgumentException( "writeBufferHighWaterMark: " + writeBufferHighWaterMark); } this.writeBufferHighWaterMark = writeBufferHighWaterMark; } public int getWriteBufferLowWaterMark() { return writeBufferLowWaterMark; } public void setWriteBufferLowWaterMark(int writeBufferLowWaterMark) { if (writeBufferLowWaterMark > getWriteBufferHighWaterMark()) { throw new IllegalArgumentException( "writeBufferLowWaterMark cannot be greater than " + "writeBufferHighWaterMark (" + getWriteBufferHighWaterMark() + "): " + writeBufferLowWaterMark); } setWriteBufferLowWaterMark0(writeBufferLowWaterMark); } private void setWriteBufferLowWaterMark0(int writeBufferLowWaterMark) { if (writeBufferLowWaterMark < 0) { throw new IllegalArgumentException( "writeBufferLowWaterMark: " + writeBufferLowWaterMark); } this.writeBufferLowWaterMark = writeBufferLowWaterMark; } public int getWriteSpinCount() { return writeSpinCount; } public void setWriteSpinCount(int writeSpinCount) { if (writeSpinCount <= 0) { throw new IllegalArgumentException( "writeSpinCount must be a positive integer."); } this.writeSpinCount = writeSpinCount; } public ReceiveBufferSizePredictor getReceiveBufferSizePredictor() { return predictor; } public void setReceiveBufferSizePredictor( ReceiveBufferSizePredictor predictor) { if (predictor == null) { throw new NullPointerException("predictor"); } this.predictor = predictor; } public ChannelPipelineFactory getPipelineFactory() { return pipelineFactory; } public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) { if (pipelineFactory == null) { throw new NullPointerException("pipelineFactory"); } this.pipelineFactory = pipelineFactory; } public ChannelBufferFactory getBufferFactory() { return bufferFactory; } public void setBufferFactory(ChannelBufferFactory bufferFactory) { if (bufferFactory == null) { throw new NullPointerException("bufferFactory"); } this.bufferFactory = bufferFactory; } public int getConnectTimeoutMillis() { return 0; } public void setConnectTimeoutMillis(int connectTimeoutMillis) { // Preconfigured by XNIO. } @Deprecated public int getWriteTimeoutMillis() { return 0; } @Deprecated public void setWriteTimeoutMillis(int writeTimeoutMillis) { // Unused. } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioClientChannel.java0000644000175000017500000000402211151257636031373 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.xnio.Connector; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 940 $, $Date: 2009-02-25 07:11:26 -0800 (Wed, 25 Feb 2009) $ */ @SuppressWarnings("unchecked") final class XnioClientChannel extends BaseXnioChannel { final Object connectLock = new Object(); final Connector xnioConnector; volatile boolean connecting; XnioClientChannel( XnioClientChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink, Connector xnioConnector) { super(null, factory, pipeline, sink, new DefaultXnioChannelConfig()); this.xnioConnector = xnioConnector; fireChannelOpen(this); } @Override public XnioClientChannelFactory getFactory() { return (XnioClientChannelFactory) super.getFactory(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioAcceptedChannel.java0000644000175000017500000000423411151257636031672 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; import java.net.SocketAddress; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 940 $, $Date: 2009-02-25 07:11:26 -0800 (Wed, 25 Feb 2009) $ */ final class XnioAcceptedChannel extends BaseXnioChannel { XnioAcceptedChannel( XnioServerChannel parent, XnioServerChannelFactory factory, ChannelPipeline pipeline, ChannelSink sink) { super(parent, factory, pipeline, sink, new DefaultXnioChannelConfig()); fireChannelOpen(this); } @Override public XnioClientChannelFactory getFactory() { return (XnioClientChannelFactory) super.getFactory(); } @Override public ChannelFuture connect(SocketAddress remoteAddress) { return getUnsupportedOperationFuture(); } @Override public ChannelFuture bind(SocketAddress remoteAddress) { return getUnsupportedOperationFuture(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioClientChannelHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioClientChannelHandler.jav0000644000175000017500000000340111216747541032531 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ final class XnioClientChannelHandler extends AbstractXnioChannelHandler { public void handleOpened(java.nio.channels.Channel channel) { XnioChannel c = XnioChannelRegistry.getChannel(channel); fireChannelOpen(c); if (c.isBound()) { fireChannelBound(c, c.getLocalAddress()); if (c.isConnected()) { fireChannelConnected(c, c.getRemoteAddress()); } } // Start to read. resumeRead(channel); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/package-info.java0000644000175000017500000000233111216400161030334 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * An alternative channel API implementation which uses * JBoss XNIO as its I/O provider. * * @apiviz.exclude \.(Abstract|Default).*$ */ package org.jboss.netty.channel.xnio; libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioClientChannelSink.java0000644000175000017500000001571311157356355032235 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import static org.jboss.netty.channel.Channels.*; import java.nio.channels.AlreadyConnectedException; import java.nio.channels.ConnectionPendingException; import java.nio.channels.GatheringByteChannel; import org.jboss.netty.channel.AbstractChannelSink; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.xnio.FutureConnection; import org.jboss.xnio.IoFuture; import org.jboss.xnio.IoFuture.Notifier; import org.jboss.xnio.channels.MultipointWritableMessageChannel; import org.jboss.xnio.channels.SuspendableReadChannel; import org.jboss.xnio.channels.SuspendableWriteChannel; import org.jboss.xnio.channels.WritableMessageChannel; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1070 $, $Date: 2009-03-15 22:00:29 -0700 (Sun, 15 Mar 2009) $ */ final class XnioClientChannelSink extends AbstractChannelSink { private static final XnioClientChannelHandler HANDLER = new XnioClientChannelHandler(); XnioClientChannelSink() { super(); } @SuppressWarnings("unchecked") public void eventSunk( ChannelPipeline pipeline, ChannelEvent e) throws Exception { BaseXnioChannel channel = (BaseXnioChannel) e.getChannel(); if (e instanceof ChannelStateEvent) { ChannelStateEvent event = (ChannelStateEvent) e; ChannelFuture future = event.getFuture(); ChannelState state = event.getState(); Object value = event.getValue(); switch (state) { case OPEN: if (Boolean.FALSE.equals(value)) { channel.closeNow(future); } break; case BOUND: case CONNECTED: if (value != null) { if (channel instanceof XnioClientChannel) { final XnioClientChannel cc = (XnioClientChannel) channel; synchronized (cc.connectLock) { if (cc.connecting) { Exception cause = new ConnectionPendingException(); future.setFailure(cause); fireExceptionCaught(channel, cause); } else { cc.connecting = true; java.nio.channels.Channel xnioChannel = cc.xnioChannel; if (xnioChannel == null) { FutureConnection fc = cc.xnioConnector.connectTo(value, HANDLER); fc.addNotifier(new FutureConnectionNotifier(cc), future); } else { Exception cause = new AlreadyConnectedException(); future.setFailure(cause); fireExceptionCaught(cc, cause); } } } } else { Exception cause = new UnsupportedOperationException(); future.setFailure(cause); fireExceptionCaught(channel, cause); } } else { channel.closeNow(future); } break; case INTEREST_OPS: int interestOps = ((Integer) value).intValue(); java.nio.channels.Channel xnioChannel = channel.xnioChannel; if (xnioChannel instanceof SuspendableReadChannel) { if ((interestOps & Channel.OP_READ) == 0) { ((SuspendableReadChannel) xnioChannel).suspendReads(); channel.setRawInterestOpsNow(Channel.OP_NONE); } else { ((SuspendableReadChannel) xnioChannel).resumeReads(); channel.setRawInterestOpsNow(Channel.OP_READ); } } e.getFuture().setSuccess(); break; } } else if (e instanceof MessageEvent) { MessageEvent event = (MessageEvent) e; java.nio.channels.Channel xnioChannel = channel.xnioChannel; if (xnioChannel instanceof GatheringByteChannel || xnioChannel instanceof MultipointWritableMessageChannel || xnioChannel instanceof WritableMessageChannel) { boolean offered = channel.writeBuffer.offer(event); assert offered; if (xnioChannel instanceof SuspendableWriteChannel) { ((SuspendableWriteChannel) xnioChannel).resumeWrites(); } } else { event.getFuture().setFailure(new IllegalStateException()); } } } @SuppressWarnings("unchecked") private static final class FutureConnectionNotifier implements Notifier { private final XnioClientChannel cc; FutureConnectionNotifier(XnioClientChannel cc) { this.cc = cc; } public void notify(IoFuture future, Object attachment) { ChannelFuture cf = (ChannelFuture) attachment; try { java.nio.channels.Channel xnioChannel = (java.nio.channels.Channel) future.get(); cc.xnioChannel = xnioChannel; XnioChannelRegistry.registerChannelMapping(cc); cf.setSuccess(); } catch (Throwable t) { cf.setFailure(t); fireExceptionCaught(cc, t); } finally { cc.connecting = false; } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/xnio/XnioChannel.java0000644000175000017500000000270511216405642030234 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel.xnio; import org.jboss.netty.channel.Channel; /** * A {@link Channel} which uses JBoss XNIO * as its I/O provider. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1427 $, $Date: 2009-06-18 02:40:50 -0700 (Thu, 18 Jun 2009) $ */ public interface XnioChannel extends Channel { XnioChannelConfig getConfig(); } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultChildChannelStateEvent.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultChildChannelStateEvent.jav0000644000175000017500000000502611146252445032536 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.jboss.netty.channel.Channels.*; /** * The default {@link ChildChannelStateEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 899 $, $Date: 2009-02-16 03:59:33 -0800 (Mon, 16 Feb 2009) $ * */ public class DefaultChildChannelStateEvent implements ChildChannelStateEvent { private final Channel parentChannel; private final Channel childChannel; /** * Creates a new instance. */ public DefaultChildChannelStateEvent(Channel parentChannel, Channel childChannel) { if (parentChannel == null) { throw new NullPointerException("parentChannel"); } if (childChannel == null) { throw new NullPointerException("childChannel"); } this.parentChannel = parentChannel; this.childChannel = childChannel; } public Channel getChannel() { return parentChannel; } public ChannelFuture getFuture() { return succeededFuture(getChannel()); } public Channel getChildChannel() { return childChannel; } @Override public String toString() { String channelString = getChannel().toString(); StringBuilder buf = new StringBuilder(channelString.length() + 32); buf.append(channelString); buf.append(getChildChannel().isOpen()? " CHILD_OPEN: " : " CHILD_CLOSED: "); buf.append(getChildChannel().getId()); return buf.toString(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ServerChannel.java0000644000175000017500000000302711216134140027576 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import org.jboss.netty.channel.socket.ServerSocketChannel; /** * A {@link Channel} that accepts an incoming connection attempt and creates * its child {@link Channel}s by accepting them. {@link ServerSocketChannel} is * a good example. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ */ public interface ServerChannel extends Channel { // This is a tag interface. } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/CompleteChannelFuture.java0000644000175000017500000000654311113212374031303 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import java.util.concurrent.TimeUnit; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * A skeletal {@link ChannelFuture} implementation which represents a * {@link ChannelFuture} which has been completed already. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 515 $, $Date: 2008-11-26 01:21:00 -0800 (Wed, 26 Nov 2008) $ */ public abstract class CompleteChannelFuture implements ChannelFuture { private static final InternalLogger logger = InternalLoggerFactory.getInstance(CompleteChannelFuture.class); private final Channel channel; /** * Creates a new instance. * * @param channel the {@link Channel} associated with this future */ protected CompleteChannelFuture(Channel channel) { if (channel == null) { throw new NullPointerException("channel"); } this.channel = channel; } public void addListener(ChannelFutureListener listener) { try { listener.operationComplete(this); } catch (Throwable t) { logger.warn( "An exception was thrown by " + ChannelFutureListener.class.getSimpleName() + ".", t); } } public void removeListener(ChannelFutureListener listener) { // NOOP } public ChannelFuture await() throws InterruptedException { return this; } public boolean await(long timeout, TimeUnit unit) throws InterruptedException { return true; } public boolean await(long timeoutMillis) throws InterruptedException { return true; } public ChannelFuture awaitUninterruptibly() { return this; } public boolean awaitUninterruptibly(long timeout, TimeUnit unit) { return true; } public boolean awaitUninterruptibly(long timeoutMillis) { return true; } public Channel getChannel() { return channel; } public boolean isDone() { return true; } public boolean setFailure(Throwable cause) { return false; } public boolean setSuccess() { return false; } public boolean cancel() { return false; } public boolean isCancelled() { return false; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/DefaultWriteCompletionEvent.java0000644000175000017500000000475611146252445032517 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; import static org.jboss.netty.channel.Channels.*; /** * The default {@link WriteCompletionEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 899 $, $Date: 2009-02-16 03:59:33 -0800 (Mon, 16 Feb 2009) $ */ public class DefaultWriteCompletionEvent implements WriteCompletionEvent { private final Channel channel; private final int writtenAmount; /** * Creates a new instance. */ public DefaultWriteCompletionEvent(Channel channel, int writtenAmount) { if (channel == null) { throw new NullPointerException("channel"); } if (writtenAmount <= 0) { throw new IllegalArgumentException( "writtenAmount must be a positive integer: " + writtenAmount); } this.channel = channel; this.writtenAmount = writtenAmount; } public Channel getChannel() { return channel; } public ChannelFuture getFuture() { return succeededFuture(getChannel()); } public int getWrittenAmount() { return writtenAmount; } @Override public String toString() { String channelString = getChannel().toString(); StringBuilder buf = new StringBuilder(channelString.length() + 32); buf.append(channelString); buf.append(" WRITTEN_AMOUNT: "); buf.append(getWrittenAmount()); return buf.toString(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/channel/ServerChannelFactory.java0000644000175000017500000000274711216134140031136 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.channel; /** * A {@link ChannelFactory} that creates a {@link ServerChannel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1406 $, $Date: 2009-06-17 02:33:20 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.has org.jboss.netty.channel.ServerChannel oneway - - creates */ public interface ServerChannelFactory extends ChannelFactory { ServerChannel newChannel(ChannelPipeline pipeline); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/0000755000175000017500000000000011316313127024215 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/Log4JLogger.java0000644000175000017500000000501211216655372027147 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import org.apache.log4j.Logger; /** * Apache Log4J * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ * */ class Log4JLogger extends AbstractInternalLogger { private final Logger logger; Log4JLogger(Logger logger) { this.logger = logger; } public void debug(String msg) { logger.debug(msg); } public void debug(String msg, Throwable cause) { logger.debug(msg, cause); } public void error(String msg) { logger.error(msg); } public void error(String msg, Throwable cause) { logger.error(msg, cause); } public void info(String msg) { logger.info(msg); } public void info(String msg, Throwable cause) { logger.info(msg, cause); } public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public boolean isErrorEnabled() { return true; } public boolean isInfoEnabled() { return logger.isInfoEnabled(); } public boolean isWarnEnabled() { return true; } public void warn(String msg) { logger.warn(msg); } public void warn(String msg, Throwable cause) { logger.warn(msg, cause); } @Override public String toString() { return String.valueOf(logger.getName()); } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/InternalLoggerFactory.java0000644000175000017500000001266611216655372031351 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import org.jboss.netty.util.internal.StackTraceSimplifier; /** * Creates an {@link InternalLogger} or changes the default factory * implementation. This factory allows you to choose what logging framework * Netty should use. The default factory is {@link JdkLoggerFactory}. * You can change it to your preferred logging framework before other Netty * classes are loaded: *
 * InternalLoggerFactory.setDefaultFactory(new {@link Log4JLoggerFactory}());
 * 
* Please note that the new default factory is effective only for the classes * which were loaded after the default factory is changed. Therefore, * {@link #setDefaultFactory(InternalLoggerFactory)} should be called as early * as possible and shouldn't be called more than once. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.landmark * @apiviz.has org.jboss.netty.logging.InternalLogger oneway - - creates */ public abstract class InternalLoggerFactory { private static volatile InternalLoggerFactory defaultFactory = new JdkLoggerFactory(); static { // Load the dependent classes in advance to avoid the case where // the VM fails to load the required classes because of too many open // files. StackTraceSimplifier.simplify(new Exception()); } /** * Returns the default factory. The initial default factory is * {@link JdkLoggerFactory}. */ public static InternalLoggerFactory getDefaultFactory() { return defaultFactory; } /** * Changes the default factory. */ public static void setDefaultFactory(InternalLoggerFactory defaultFactory) { if (defaultFactory == null) { throw new NullPointerException("defaultFactory"); } InternalLoggerFactory.defaultFactory = defaultFactory; } /** * Creates a new logger instance with the name of the specified class. */ public static InternalLogger getInstance(Class clazz) { return getInstance(clazz.getName()); } /** * Creates a new logger instance with the specified name. */ public static InternalLogger getInstance(String name) { final InternalLogger logger = getDefaultFactory().newInstance(name); return new InternalLogger() { public void debug(String msg) { logger.debug(msg); } public void debug(String msg, Throwable cause) { StackTraceSimplifier.simplify(cause); logger.debug(msg, cause); } public void error(String msg) { logger.error(msg); } public void error(String msg, Throwable cause) { StackTraceSimplifier.simplify(cause); logger.error(msg, cause); } public void info(String msg) { logger.info(msg); } public void info(String msg, Throwable cause) { StackTraceSimplifier.simplify(cause); logger.info(msg, cause); } public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public boolean isErrorEnabled() { return logger.isErrorEnabled(); } public boolean isInfoEnabled() { return logger.isInfoEnabled(); } public boolean isWarnEnabled() { return logger.isWarnEnabled(); } public void warn(String msg) { logger.warn(msg); } public void warn(String msg, Throwable cause) { StackTraceSimplifier.simplify(cause); logger.warn(msg, cause); } public boolean isEnabled(InternalLogLevel level) { return logger.isEnabled(level); } public void log(InternalLogLevel level, String msg) { logger.log(level, msg); } public void log(InternalLogLevel level, String msg, Throwable cause) { StackTraceSimplifier.simplify(cause); logger.log(level, msg, cause); } }; } /** * Creates a new logger instance with the specified name. */ public abstract InternalLogger newInstance(String name); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/CommonsLogger.java0000644000175000017500000000517211216655372027652 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import org.apache.commons.logging.Log; /** * Apache Commons Logging * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ * */ class CommonsLogger extends AbstractInternalLogger { private final Log logger; private final String loggerName; CommonsLogger(Log logger, String loggerName) { this.logger = logger; this.loggerName = loggerName; } public void debug(String msg) { logger.debug(msg); } public void debug(String msg, Throwable cause) { logger.debug(msg, cause); } public void error(String msg) { logger.error(msg); } public void error(String msg, Throwable cause) { logger.error(msg, cause); } public void info(String msg) { logger.info(msg); } public void info(String msg, Throwable cause) { logger.info(msg, cause); } public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public boolean isErrorEnabled() { return logger.isErrorEnabled(); } public boolean isInfoEnabled() { return logger.isInfoEnabled(); } public boolean isWarnEnabled() { return logger.isWarnEnabled(); } public void warn(String msg) { logger.warn(msg); } public void warn(String msg, Throwable cause) { logger.warn(msg, cause); } @Override public String toString() { return loggerName; } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/OsgiLogger.java0000644000175000017500000001027211216655372027135 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import org.osgi.service.log.LogService; /** * OSGi {@link LogService} logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ * */ class OsgiLogger extends AbstractInternalLogger { private final OsgiLoggerFactory parent; private final InternalLogger fallback; private final String name; private final String prefix; OsgiLogger(OsgiLoggerFactory parent, String name, InternalLogger fallback) { this.parent = parent; this.name = name; this.fallback = fallback; prefix = "[" + name + "] "; } public void debug(String msg) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_DEBUG, prefix + msg); } else { fallback.debug(msg); } } public void debug(String msg, Throwable cause) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_DEBUG, prefix + msg, cause); } else { fallback.debug(msg, cause); } } public void error(String msg) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_ERROR, prefix + msg); } else { fallback.error(msg); } } public void error(String msg, Throwable cause) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_ERROR, prefix + msg, cause); } else { fallback.error(msg, cause); } } public void info(String msg) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_INFO, prefix + msg); } else { fallback.info(msg); } } public void info(String msg, Throwable cause) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_INFO, prefix + msg, cause); } else { fallback.info(msg, cause); } } public boolean isDebugEnabled() { return true; } public boolean isErrorEnabled() { return true; } public boolean isInfoEnabled() { return true; } public boolean isWarnEnabled() { return true; } public void warn(String msg) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_WARNING, prefix + msg); } else { fallback.warn(msg); } } public void warn(String msg, Throwable cause) { LogService logService = parent.getLogService(); if (logService != null) { logService.log(LogService.LOG_WARNING, prefix + msg, cause); } else { fallback.warn(msg, cause); } } @Override public String toString() { return name; } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/JBossLogger.java0000644000175000017500000000514111216655372027253 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import org.jboss.logging.Logger; /** * JBoss Logging * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ * */ class JBossLogger extends AbstractInternalLogger { private final Logger logger; JBossLogger(Logger logger) { this.logger = logger; } public void debug(String msg) { logger.debug(msg); } public void debug(String msg, Throwable cause) { logger.debug(msg, cause); } public void error(String msg) { logger.error(msg); } public void error(String msg, Throwable cause) { logger.error(msg, cause); } public void info(String msg) { logger.info(msg); } public void info(String msg, Throwable cause) { logger.info(msg, cause); } @SuppressWarnings("deprecation") public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public boolean isErrorEnabled() { return true; } @SuppressWarnings("deprecation") public boolean isInfoEnabled() { return logger.isInfoEnabled(); } public boolean isWarnEnabled() { return true; } public void warn(String msg) { logger.warn(msg); } public void warn(String msg, Throwable cause) { logger.warn(msg, cause); } @Override public String toString() { return String.valueOf(logger.getName()); } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/JBossLoggerFactory.java0000644000175000017500000000317611054503230030572 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * Logger factory which creates a * JBoss Logging * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 119 $, $Date: 2008-08-25 03:16:56 -0700 (Mon, 25 Aug 2008) $ * */ public class JBossLoggerFactory extends InternalLoggerFactory { @Override public InternalLogger newInstance(String name) { final org.jboss.logging.Logger logger = org.jboss.logging.Logger.getLogger(name); return new JBossLogger(logger); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/InternalLogLevel.java0000644000175000017500000000300111216723540030263 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * The log level that {@link InternalLogger} can log at. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1471 $, $Date: 2009-06-19 07:57:36 -0700 (Fri, 19 Jun 2009) $ */ public enum InternalLogLevel { /** * 'DEBUG' log level. */ DEBUG, /** * 'INFO' log level. */ INFO, /** * 'WARN' log level. */ WARN, /** * 'ERROR' log level. */ ERROR; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/InternalLogger.java0000644000175000017500000000547211216655372030016 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * Internal-use-only logger used by Netty. DO NOT * access this class outside of Netty. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ */ public interface InternalLogger { /** * Returns {@code true} if a DEBUG level message is logged. */ boolean isDebugEnabled(); /** * Returns {@code true} if an INFO level message is logged. */ boolean isInfoEnabled(); /** * Returns {@code true} if a WARN level message is logged. */ boolean isWarnEnabled(); /** * Returns {@code true} if an ERROR level message is logged. */ boolean isErrorEnabled(); /** * Returns {@code true} if the specified log level message is logged. */ boolean isEnabled(InternalLogLevel level); /** * Logs a DEBUG level message. */ void debug(String msg); /** * Logs a DEBUG level message. */ void debug(String msg, Throwable cause); /** * Logs an INFO level message. */ void info(String msg); /** * Logs an INFO level message. */ void info(String msg, Throwable cause); /** * Logs a WARN level message. */ void warn(String msg); /** * Logs a WARN level message. */ void warn(String msg, Throwable cause); /** * Logs an ERROR level message. */ void error(String msg); /** * Logs an ERROR level message. */ void error(String msg, Throwable cause); /** * Logs a message. */ void log(InternalLogLevel level, String msg); /** * Logs a message. */ void log(InternalLogLevel level, String msg, Throwable cause); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/Log4JLoggerFactory.java0000644000175000017500000000316111054503230030463 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * Logger factory which creates an * Apache Log4J * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 119 $, $Date: 2008-08-25 03:16:56 -0700 (Mon, 25 Aug 2008) $ * */ public class Log4JLoggerFactory extends InternalLoggerFactory { @Override public InternalLogger newInstance(String name) { final org.apache.log4j.Logger logger = org.apache.log4j.Logger.getLogger(name); return new Log4JLogger(logger); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/OsgiLoggerFactory.java0000644000175000017500000000637511133040116030454 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceReference; import org.osgi.service.log.LogService; import org.osgi.util.tracker.ServiceTracker; /** * Logger factory which creates an OSGi * {@link LogService} logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 687 $, $Date: 2009-01-12 23:18:38 -0800 (Mon, 12 Jan 2009) $ * */ public class OsgiLoggerFactory extends InternalLoggerFactory { private final ServiceTracker logServiceTracker; private final InternalLoggerFactory fallback; volatile LogService logService; public OsgiLoggerFactory(BundleContext ctx) { this(ctx, null); } public OsgiLoggerFactory(BundleContext ctx, InternalLoggerFactory fallback) { if (ctx == null) { throw new NullPointerException("ctx"); } if (fallback == null) { fallback = InternalLoggerFactory.getDefaultFactory(); if (fallback instanceof OsgiLoggerFactory) { fallback = new JdkLoggerFactory(); } } this.fallback = fallback; logServiceTracker = new ServiceTracker( ctx, "org.osgi.service.log.LogService", null) { @Override public Object addingService(ServiceReference reference) { LogService service = (LogService) super.addingService(reference); logService = service; return service; } @Override public void removedService(ServiceReference reference, Object service) { logService = null; } }; logServiceTracker.open(); } public InternalLoggerFactory getFallback() { return fallback; } public LogService getLogService() { return logService; } public void destroy() { logService = null; logServiceTracker.close(); } @Override public InternalLogger newInstance(String name) { return new OsgiLogger(this, name, fallback.newInstance(name)); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/package-info.java0000644000175000017500000000226711060216745027417 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Simplistic internal-use-only logging layer which allows a user to * decide what logging framework Netty should use. * * @apiviz.hidden */ package org.jboss.netty.logging;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/JdkLogger.java0000644000175000017500000000570511216655372026751 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import java.util.logging.Level; import java.util.logging.Logger; /** * java.util.logging * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ * */ class JdkLogger extends AbstractInternalLogger { private final Logger logger; private final String loggerName; JdkLogger(Logger logger, String loggerName) { this.logger = logger; this.loggerName = loggerName; } public void debug(String msg) { logger.logp(Level.FINE, loggerName, null, msg); } public void debug(String msg, Throwable cause) { logger.logp(Level.FINE, loggerName, null, msg, cause); } public void error(String msg) { logger.logp(Level.SEVERE, loggerName, null, msg); } public void error(String msg, Throwable cause) { logger.logp(Level.SEVERE, loggerName, null, msg, cause); } public void info(String msg) { logger.logp(Level.INFO, loggerName, null, msg); } public void info(String msg, Throwable cause) { logger.logp(Level.INFO, loggerName, null, msg, cause); } public boolean isDebugEnabled() { return logger.isLoggable(Level.FINE); } public boolean isErrorEnabled() { return logger.isLoggable(Level.SEVERE); } public boolean isInfoEnabled() { return logger.isLoggable(Level.INFO); } public boolean isWarnEnabled() { return logger.isLoggable(Level.WARNING); } public void warn(String msg) { logger.logp(Level.WARNING, loggerName, null, msg); } public void warn(String msg, Throwable cause) { logger.logp(Level.WARNING, loggerName, null, msg, cause); } @Override public String toString() { return loggerName; } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/Slf4JLogger.java0000644000175000017500000000500511216655372027154 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; import org.slf4j.Logger; /** * SLF4J logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ * */ class Slf4JLogger extends AbstractInternalLogger { private final Logger logger; Slf4JLogger(Logger logger) { this.logger = logger; } public void debug(String msg) { logger.debug(msg); } public void debug(String msg, Throwable cause) { logger.debug(msg, cause); } public void error(String msg) { logger.error(msg); } public void error(String msg, Throwable cause) { logger.error(msg, cause); } public void info(String msg) { logger.info(msg); } public void info(String msg, Throwable cause) { logger.info(msg, cause); } public boolean isDebugEnabled() { return logger.isDebugEnabled(); } public boolean isErrorEnabled() { return logger.isErrorEnabled(); } public boolean isInfoEnabled() { return logger.isInfoEnabled(); } public boolean isWarnEnabled() { return logger.isWarnEnabled(); } public void warn(String msg) { logger.warn(msg); } public void warn(String msg, Throwable cause) { logger.warn(msg, cause); } @Override public String toString() { return String.valueOf(logger.getName()); } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/JdkLoggerFactory.java0000644000175000017500000000321711054520103030254 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * Logger factory which creates a * java.util.logging * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 127 $, $Date: 2008-08-25 05:06:27 -0700 (Mon, 25 Aug 2008) $ * */ public class JdkLoggerFactory extends InternalLoggerFactory { @Override public InternalLogger newInstance(String name) { final java.util.logging.Logger logger = java.util.logging.Logger.getLogger(name); return new JdkLogger(logger, name); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/Slf4JLoggerFactory.java0000644000175000017500000000310611054503230030465 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * Logger factory which creates a SLF4J * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 119 $, $Date: 2008-08-25 03:16:56 -0700 (Mon, 25 Aug 2008) $ * */ public class Slf4JLoggerFactory extends InternalLoggerFactory { @Override public InternalLogger newInstance(String name) { final org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(name); return new Slf4JLogger(logger); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/CommonsLoggerFactory.java0000644000175000017500000000321311054510641031161 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * Logger factory which creates an * Apache Commons Logging * logger. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 122 $, $Date: 2008-08-25 04:04:01 -0700 (Mon, 25 Aug 2008) $ * */ public class CommonsLoggerFactory extends InternalLoggerFactory { @Override public InternalLogger newInstance(String name) { final org.apache.commons.logging.Log logger = org.apache.commons.logging.LogFactory.getLog(name); return new CommonsLogger(logger, name); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/logging/AbstractInternalLogger.java0000644000175000017500000000547611216655372031506 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.logging; /** * A skeletal implementation of {@link InternalLogger}. This class implements * all methods that have a {@link InternalLogLevel} parameter by default to call * specific logger methods such as {@link #info(String)} or {@link #isInfoEnabled()}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1456 $, $Date: 2009-06-19 02:31:38 -0700 (Fri, 19 Jun 2009) $ */ public abstract class AbstractInternalLogger implements InternalLogger { /** * Creates a new instance. */ protected AbstractInternalLogger() { super(); } public boolean isEnabled(InternalLogLevel level) { switch (level) { case DEBUG: return isDebugEnabled(); case INFO: return isInfoEnabled(); case WARN: return isWarnEnabled(); case ERROR: return isErrorEnabled(); default: throw new Error(); } } public void log(InternalLogLevel level, String msg, Throwable cause) { switch (level) { case DEBUG: debug(msg, cause); break; case INFO: info(msg, cause); break; case WARN: warn(msg, cause); break; case ERROR: error(msg, cause); break; default: throw new Error(); } } public void log(InternalLogLevel level, String msg) { switch (level) { case DEBUG: debug(msg); break; case INFO: info(msg); break; case WARN: warn(msg); break; case ERROR: error(msg); break; default: throw new Error(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/0000755000175000017500000000000011316313154023544 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/TimerTask.java0000644000175000017500000000320211216107460026307 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import java.util.concurrent.TimeUnit; /** * A task which is executed after the delay specified with * {@link Timer#newTimeout(TimerTask, long, TimeUnit)}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1397 $, $Date: 2009-06-16 23:37:36 -0700 (Tue, 16 Jun 2009) $ */ public interface TimerTask { /** * Executed after the delay specified with * {@link Timer#newTimeout(TimerTask, long, TimeUnit)}. * * @param timeout a handle which is associated with this task */ void run(Timeout timeout) throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/DefaultObjectSizeEstimator.java0000644000175000017500000001101011216077425031645 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.nio.ByteBuffer; import java.util.HashSet; import java.util.Set; import java.util.concurrent.ConcurrentMap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.util.internal.ConcurrentIdentityWeakKeyHashMap; /** * The default {@link ObjectSizeEstimator} implementation for general purpose. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1395 $, $Date: 2009-06-16 22:28:53 -0700 (Tue, 16 Jun 2009) $ * */ public class DefaultObjectSizeEstimator implements ObjectSizeEstimator { private final ConcurrentMap, Integer> class2size = new ConcurrentIdentityWeakKeyHashMap, Integer>(); /** * Creates a new instance. */ public DefaultObjectSizeEstimator() { class2size.put(boolean.class, 4); // Probably an integer. class2size.put(byte.class, 1); class2size.put(char.class, 2); class2size.put(int.class, 4); class2size.put(short.class, 2); class2size.put(long.class, 8); class2size.put(float.class, 4); class2size.put(double.class, 8); class2size.put(void.class, 0); } public int estimateSize(Object o) { if (o == null) { return 8; } int answer = 8 + estimateSize(o.getClass(), null); if (o instanceof EstimatableObjectWrapper) { answer += estimateSize(((EstimatableObjectWrapper) o).unwrap()); } else if (o instanceof MessageEvent) { answer += estimateSize(((MessageEvent) o).getMessage()); } else if (o instanceof ChannelBuffer) { answer += ((ChannelBuffer) o).capacity(); } else if (o instanceof byte[]) { answer += ((byte[]) o).length; } else if (o instanceof ByteBuffer) { answer += ((ByteBuffer) o).remaining(); } else if (o instanceof CharSequence) { answer += ((CharSequence) o).length() << 1; } else if (o instanceof Iterable) { for (Object m : (Iterable) o) { answer += estimateSize(m); } } return align(answer); } private int estimateSize(Class clazz, Set> visitedClasses) { Integer objectSize = class2size.get(clazz); if (objectSize != null) { return objectSize; } if (visitedClasses != null) { if (visitedClasses.contains(clazz)) { return 0; } } else { visitedClasses = new HashSet>(); } visitedClasses.add(clazz); int answer = 8; // Basic overhead. for (Class c = clazz; c != null; c = c.getSuperclass()) { Field[] fields = c.getDeclaredFields(); for (Field f : fields) { if ((f.getModifiers() & Modifier.STATIC) != 0) { // Ignore static fields. continue; } answer += estimateSize(f.getType(), visitedClasses); } } visitedClasses.remove(clazz); // Some alignment. answer = align(answer); // Put the final answer. class2size.putIfAbsent(clazz, answer); return answer; } private static int align(int size) { int r = size % 8; if (r != 0) { size += 8 - r; } return size; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/0000755000175000017500000000000011316313154025360 5ustar deckerdecker././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/CaseIgnoringComparator.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/CaseIgnoringComparator.java0000644000175000017500000000344111216747541032637 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.io.Serializable; import java.util.Comparator; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public final class CaseIgnoringComparator implements Comparator, Serializable { private static final long serialVersionUID = 4582133183775373862L; public static final CaseIgnoringComparator INSTANCE = new CaseIgnoringComparator(); private CaseIgnoringComparator() { super(); } public int compare(String o1, String o2) { return o1.compareToIgnoreCase(o2); } private Object readResolve() { return INSTANCE; } }././@LongLink0000000000000000000000000000015000000000000011561 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConcurrentIdentityHashMap.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConcurrentIdentityHashMap.j0000644000175000017500000014017111213433461032635 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.util.internal; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; /** * An alternative identity-comparing {@link ConcurrentMap} which is similar to * {@link java.util.concurrent.ConcurrentHashMap}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Doug Lea * @author Jason T. Greene * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1336 $, $Date: 2009-06-09 03:19:29 -0700 (Tue, 09 Jun 2009) $ * * @param the type of keys maintained by this map * @param the type of mapped values */ public final class ConcurrentIdentityHashMap extends AbstractMap implements ConcurrentMap{ /** * The default initial capacity for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The default load factor for this table, used when not otherwise specified * in a constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The default concurrency level for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * The maximum capacity, used if a higher value is implicitly specified by * either of the constructors with arguments. MUST be a power of two * <= 1<<30 to ensure that entries are indexable using integers. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The maximum number of segments to allow; used to bound constructor * arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** * Number of unsynchronized retries in size and containsValue methods before * resorting to locking. This is used to avoid unbounded retries if tables * undergo continuous modification which would make it impossible to obtain * an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** * Mask value for indexing into segments. The upper bits of a key's hash * code are used to choose the segment. */ final int segmentMask; /** * Shift value for indexing within segments. */ final int segmentShift; /** * The segments, each of which is a specialized hash table */ final Segment[] segments; Set keySet; Set> entrySet; Collection values; /* ---------------- Small Utilities -------------- */ /** * Applies a supplemental hash function to a given hashCode, which defends * against poor quality hash functions. This is critical because * ConcurrentReferenceHashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ in lower * or upper bits. */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += h << 15 ^ 0xffffcd7d; h ^= h >>> 10; h += h << 3; h ^= h >>> 6; h += (h << 2) + (h << 14); return h ^ h >>> 16; } /** * Returns the segment that should be used for key with given hash. * * @param hash the hash code for the key * @return the segment */ final Segment segmentFor(int hash) { return segments[hash >>> segmentShift & segmentMask]; } private int hashOf(Object key) { return hash(System.identityHashCode(key)); } /** * ConcurrentReferenceHashMap list entry. Note that this is never exported * out as a user-visible Map.Entry. * * Because the value field is volatile, not final, it is legal wrt * the Java Memory Model for an unsynchronized reader to see null * instead of initial value when read via a data race. Although a * reordering leading to this is not likely to ever actually * occur, the Segment.readValueUnderLock method is used as a * backup in case a null (pre-initialized) value is ever seen in * an unsynchronized access method. */ static final class HashEntry { final Object key; final int hash; volatile Object value; final HashEntry next; HashEntry( K key, int hash, HashEntry next, V value) { this.hash = hash; this.next = next; this.key = key; this.value = value; } @SuppressWarnings("unchecked") final K key() { return (K) key; } @SuppressWarnings("unchecked") final V value() { return (V) value; } final void setValue(V value) { this.value = value; } @SuppressWarnings("unchecked") static final HashEntry[] newArray(int i) { return new HashEntry[i]; } } /** * Segments are specialized versions of hash tables. This subclasses from * ReentrantLock opportunistically, just to simplify some locking and avoid * separate construction. */ static final class Segment extends ReentrantLock { /* * Segments maintain a table of entry lists that are ALWAYS kept in a * consistent state, so can be read without locking. Next fields of * nodes are immutable (final). All list additions are performed at the * front of each bin. This makes it easy to check changes, and also fast * to traverse. When nodes would otherwise be changed, new nodes are * created to replace them. This works well for hash tables since the * bin lists tend to be short. (The average length is less than two for * the default load factor threshold.) * * Read operations can thus proceed without locking, but rely on * selected uses of volatiles to ensure that completed write operations * performed by other threads are noticed. For most purposes, the * "count" field, tracking the number of elements, serves as that * volatile variable ensuring visibility. This is convenient because * this field needs to be read in many read operations anyway: * * - All (unsynchronized) read operations must first read the * "count" field, and should not look at table entries if * it is 0. * * - All (synchronized) write operations should write to * the "count" field after structurally changing any bin. * The operations must not take any action that could even * momentarily cause a concurrent read operation to see * inconsistent data. This is made easier by the nature of * the read operations in Map. For example, no operation * can reveal that the table has grown but the threshold * has not yet been updated, so there are no atomicity * requirements for this with respect to reads. * * As a guide, all critical volatile reads and writes to the count field * are marked in code comments. */ private static final long serialVersionUID = 5207829234977119743L; /** * The number of elements in this segment's region. */ transient volatile int count; /** * Number of updates that alter the size of the table. This is used * during bulk-read methods to make sure they see a consistent snapshot: * If modCounts change during a traversal of segments computing size or * checking containsValue, then we might have an inconsistent view of * state so (usually) must retry. */ int modCount; /** * The table is rehashed when its size exceeds this threshold. * (The value of this field is always (capacity * loadFactor).) */ int threshold; /** * The per-segment table. */ transient volatile HashEntry[] table; /** * The load factor for the hash table. Even though this value is same * for all segments, it is replicated to avoid needing links to outer * object. * * @serial */ final float loadFactor; Segment(int initialCapacity, float lf) { loadFactor = lf; setTable(HashEntry. newArray(initialCapacity)); } @SuppressWarnings("unchecked") static final Segment[] newArray(int i) { return new Segment[i]; } private boolean keyEq(Object src, Object dest) { return src == dest; } /** * Sets table to new HashEntry array. Call only while holding lock or in * constructor. */ void setTable(HashEntry[] newTable) { threshold = (int) (newTable.length * loadFactor); table = newTable; } /** * Returns properly casted first entry of bin for given hash. */ HashEntry getFirst(int hash) { HashEntry[] tab = table; return tab[hash & tab.length - 1]; } HashEntry newHashEntry( K key, int hash, HashEntry next, V value) { return new HashEntry(key, hash, next, value); } /** * Reads value field of an entry under lock. Called if value field ever * appears to be null. This is possible only if a compiler happens to * reorder a HashEntry initialization with its table assignment, which * is legal under memory model but is not known to ever occur. */ V readValueUnderLock(HashEntry e) { lock(); try { return e.value(); } finally { unlock(); } } /* Specialized implementations of map methods */ V get(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { V opaque = e.value(); if (opaque != null) { return opaque; } return readValueUnderLock(e); // recheck } e = e.next; } } return null; } boolean containsKey(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { return true; } e = e.next; } } return false; } boolean containsValue(Object value) { if (count != 0) { // read-volatile HashEntry[] tab = table; int len = tab.length; for (int i = 0; i < len; i ++) { for (HashEntry e = tab[i]; e != null; e = e.next) { V opaque = e.value(); V v; if (opaque == null) { v = readValueUnderLock(e); // recheck } else { v = opaque; } if (value.equals(v)) { return true; } } } } return false; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } boolean replaced = false; if (e != null && oldValue.equals(e.value())) { replaced = true; e.setValue(newValue); } return replaced; } finally { unlock(); } } V replace(K key, int hash, V newValue) { lock(); try { HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { oldValue = e.value(); e.setValue(newValue); } return oldValue; } finally { unlock(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { int c = count; if (c ++ > threshold) { // ensure capacity int reduced = rehash(); if (reduced > 0) { count = (c -= reduced) - 1; // write-volatile } } HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue; if (e != null) { oldValue = e.value(); if (!onlyIfAbsent) { e.setValue(value); } } else { oldValue = null; ++ modCount; tab[index] = newHashEntry(key, hash, first, value); count = c; // write-volatile } return oldValue; } finally { unlock(); } } int rehash() { HashEntry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) { return 0; } /* * Reclassify nodes in each list to new Map. Because we are using * power-of-two expansion, the elements from each bin must either * stay at same index, or move with a power of two offset. We * eliminate unnecessary node creation by catching cases where old * nodes can be reused because their next fields won't change. * Statistically, at the default threshold, only about one-sixth of * them need cloning when a table doubles. The nodes they replace * will be garbage collectable as soon as they are no longer * referenced by any reader thread that may be in the midst of * traversing table right now. */ HashEntry[] newTable = HashEntry.newArray(oldCapacity << 1); threshold = (int) (newTable.length * loadFactor); int sizeMask = newTable.length - 1; int reduce = 0; for (int i = 0; i < oldCapacity; i ++) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. HashEntry e = oldTable[i]; if (e != null) { HashEntry next = e.next; int idx = e.hash & sizeMask; // Single node on list if (next == null) { newTable[idx] = e; } else { // Reuse trailing consecutive sequence at same slot HashEntry lastRun = e; int lastIdx = idx; for (HashEntry last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (HashEntry p = e; p != lastRun; p = p.next) { // Skip GC'd weak references K key = p.key(); if (key == null) { reduce ++; continue; } int k = p.hash & sizeMask; HashEntry n = newTable[k]; newTable[k] = newHashEntry(key, p.hash, n, p.value()); } } } } table = newTable; return reduce; } /** * Remove; match on key only if value null, else match both. */ V remove(Object key, int hash, Object value, boolean refRemove) { lock(); try { int c = count - 1; HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; // a reference remove operation compares the Reference instance while (e != null && key != e.key && (refRemove || hash != e.hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { V v = e.value(); if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay in list, // but all preceding ones need to be cloned. ++ modCount; HashEntry newFirst = e.next; for (HashEntry p = first; p != e; p = p.next) { K pKey = p.key(); if (pKey == null) { // Skip GC'd keys c --; continue; } newFirst = newHashEntry( pKey, p.hash, newFirst, p.value()); } tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } } void clear() { if (count != 0) { lock(); try { HashEntry[] tab = table; for (int i = 0; i < tab.length; i ++) { tab[i] = null; } ++ modCount; count = 0; // write-volatile } finally { unlock(); } } } } /* ---------------- Public operations -------------- */ /** * Creates a new, empty map with the specified initial capacity, load factor * and concurrency level. * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently updating * threads. The implementation performs internal * sizing to try to accommodate this many threads. * @throws IllegalArgumentException if the initial capacity is negative or * the load factor or concurrencyLevel are * nonpositive. */ public ConcurrentIdentityHashMap( int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) { throw new IllegalArgumentException(); } if (concurrencyLevel > MAX_SEGMENTS) { concurrencyLevel = MAX_SEGMENTS; } // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; while (ssize < concurrencyLevel) { ++ sshift; ssize <<= 1; } segmentShift = 32 - sshift; segmentMask = ssize - 1; this.segments = Segment.newArray(ssize); if (initialCapacity > MAXIMUM_CAPACITY) { initialCapacity = MAXIMUM_CAPACITY; } int c = initialCapacity / ssize; if (c * ssize < initialCapacity) { ++ c; } int cap = 1; while (cap < c) { cap <<= 1; } for (int i = 0; i < this.segments.length; ++ i) { this.segments[i] = new Segment(cap, loadFactor); } } /** * Creates a new, empty map with the specified initial capacity and load * factor and with the default reference types (weak keys, strong values), * and concurrencyLevel (16). * * @param initialCapacity The implementation performs internal sizing to * accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @throws IllegalArgumentException if the initial capacity of elements is * negative or the load factor is * nonpositive */ public ConcurrentIdentityHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with the specified initial capacity, and with * default reference types (weak keys, strong values), load factor (0.75) * and concurrencyLevel (16). * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @throws IllegalArgumentException if the initial capacity of elements is * negative. */ public ConcurrentIdentityHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with a default initial capacity (16), reference * types (weak keys, strong values), default load factor (0.75) and * concurrencyLevel (16). */ public ConcurrentIdentityHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new map with the same mappings as the given map. The map is * created with a capacity of 1.5 times the number of mappings in the given * map or 16 (whichever is greater), and a default load factor (0.75) and * concurrencyLevel (16). * * @param m the map */ public ConcurrentIdentityHashMap(Map m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); putAll(m); } /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ @Override public boolean isEmpty() { final Segment[] segments = this.segments; /* * We keep track of per-segment modCounts to avoid ABA problems in which * an element in one segment was added and in another removed during * traversal, in which case the table was never actually empty at any * point. Note the similar use of modCounts in the size() and * containsValue() methods, which are the only other methods also * susceptible to ABA problems. */ int[] mc = new int[segments.length]; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0) { return false; } else { mcsum += mc[i] = segments[i].modCount; } } // If mcsum happens to be zero, then we know we got a snapshot before // any modifications at all were made. This is probably common enough // to bother tracking. if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0 || mc[i] != segments[i].modCount) { return false; } } } return true; } /** * Returns the number of key-value mappings in this map. If the map contains * more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ @Override public int size() { final Segment[] segments = this.segments; long sum = 0; long check = 0; int[] mc = new int[segments.length]; // Try a few times to get accurate count. On failure due to continuous // async changes in table, resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { check = 0; sum = 0; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; mcsum += mc[i] = segments[i].modCount; } if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { check += segments[i].count; if (mc[i] != segments[i].modCount) { check = -1; // force retry break; } } } if (check == sum) { break; } } if (check != sum) { // Resort to locking all segments sum = 0; for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; } for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } if (sum > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) sum; } } /** * Returns the value to which the specified key is mapped, or {@code null} * if this map contains no mapping for the key. * *

More formally, if this map contains a mapping from a key {@code k} to * a value {@code v} such that {@code key.equals(k)}, then this method * returns {@code v}; otherwise it returns {@code null}. (There can be at * most one such mapping.) * * @throws NullPointerException if the specified key is null */ @Override public V get(Object key) { int hash = hashOf(key); return segmentFor(hash).get(key, hash); } /** * Tests if the specified object is a key in this table. * * @param key possible key * @return true if and only if the specified object is a key in * this table, as determined by the equals method; * false otherwise. * @throws NullPointerException if the specified key is null */ @Override public boolean containsKey(Object key) { int hash = hashOf(key); return segmentFor(hash).containsKey(key, hash); } /** * Returns true if this map maps one or more keys to the specified * value. Note: This method requires a full internal traversal of the hash * table, and so is much slower than method containsKey. * * @param value value whose presence in this map is to be tested * @return true if this map maps one or more keys to the specified * value * @throws NullPointerException if the specified value is null */ @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } // See explanation of modCount use above final Segment[] segments = this.segments; int[] mc = new int[segments.length]; // Try a few times without locking for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { mcsum += mc[i] = segments[i].modCount; if (segments[i].containsValue(value)) { return true; } } boolean cleanSweep = true; if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (mc[i] != segments[i].modCount) { cleanSweep = false; break; } } } if (cleanSweep) { return false; } } // Resort to locking all segments for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } boolean found = false; try { for (int i = 0; i < segments.length; ++ i) { if (segments[i].containsValue(value)) { found = true; break; } } } finally { for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } return found; } /** * Legacy method testing if some key maps into the specified value in this * table. This method is identical in functionality to * {@link #containsValue}, and exists solely to ensure full compatibility * with class {@link Hashtable}, which supported this method prior to * introduction of the Java Collections framework. * * @param value a value to search for * @return true if and only if some key maps to the value * argument in this table as determined by the equals * method; false otherwise * @throws NullPointerException if the specified value is null */ public boolean contains(Object value) { return containsValue(value); } /** * Maps the specified key to the specified value in this table. Neither the * key nor the value can be null. * *

The value can be retrieved by calling the get method with a * key that is equal to the original key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key or value is null */ @Override public V put(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, false); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V putIfAbsent(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, true); } /** * Copies all of the mappings from the specified map to this one. These * mappings replace any mappings that this map had for any of the keys * currently in the specified map. * * @param m mappings to be stored in this map */ @Override public void putAll(Map m) { for (Map.Entry e: m.entrySet()) { put(e.getKey(), e.getValue()); } } /** * Removes the key (and its corresponding value) from this map. This method * does nothing if the key is not in the map. * * @param key the key that needs to be removed * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key is null */ @Override public V remove(Object key) { int hash = hashOf(key); return segmentFor(hash).remove(key, hash, null, false); } /** * {@inheritDoc} * * @throws NullPointerException if the specified key is null */ public boolean remove(Object key, Object value) { int hash = hashOf(key); if (value == null) { return false; } return segmentFor(hash).remove(key, hash, value, false) != null; } /** * {@inheritDoc} * * @throws NullPointerException if any of the arguments are null */ public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, oldValue, newValue); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V replace(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, value); } /** * Removes all of the mappings from this map. */ @Override public void clear() { for (int i = 0; i < segments.length; ++ i) { segments[i].clear(); } } /** * Returns a {@link Set} view of the keys contained in this map. The set is * backed by the map, so changes to the map are reflected in the set, and * vice-versa. The set supports element removal, which removes the * corresponding mapping from this map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set keySet() { Set ks = keySet; return ks != null? ks : (keySet = new KeySet()); } /** * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are reflected * in the collection, and vice-versa. The collection supports element * removal, which removes the corresponding mapping from this map, via the * Iterator.remove, Collection.remove, removeAll, * retainAll, and clear operations. It does not support * the add or addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Collection values() { Collection vs = values; return vs != null? vs : (values = new Values()); } /** * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are reflected in the * set, and vice-versa. The set supports element removal, which removes the * corresponding mapping from the map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set> entrySet() { Set> es = entrySet; return es != null? es : (entrySet = new EntrySet()); } /** * Returns an enumeration of the keys in this table. * * @return an enumeration of the keys in this table * @see #keySet() */ public Enumeration keys() { return new KeyIterator(); } /** * Returns an enumeration of the values in this table. * * @return an enumeration of the values in this table * @see #values() */ public Enumeration elements() { return new ValueIterator(); } /* ---------------- Iterator Support -------------- */ abstract class HashIterator { int nextSegmentIndex; int nextTableIndex; HashEntry[] currentTable; HashEntry nextEntry; HashEntry lastReturned; K currentKey; // Strong reference to weak key (prevents gc) HashIterator() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; advance(); } public void rewind() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; currentTable = null; nextEntry = null; lastReturned = null; currentKey = null; advance(); } public boolean hasMoreElements() { return hasNext(); } final void advance() { if (nextEntry != null && (nextEntry = nextEntry.next) != null) { return; } while (nextTableIndex >= 0) { if ((nextEntry = currentTable[nextTableIndex --]) != null) { return; } } while (nextSegmentIndex >= 0) { Segment seg = segments[nextSegmentIndex --]; if (seg.count != 0) { currentTable = seg.table; for (int j = currentTable.length - 1; j >= 0; -- j) { if ((nextEntry = currentTable[j]) != null) { nextTableIndex = j - 1; return; } } } } } public boolean hasNext() { while (nextEntry != null) { if (nextEntry.key() != null) { return true; } advance(); } return false; } HashEntry nextEntry() { do { if (nextEntry == null) { throw new NoSuchElementException(); } lastReturned = nextEntry; currentKey = lastReturned.key(); advance(); } while (currentKey == null); // Skip GC'd keys return lastReturned; } public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } ConcurrentIdentityHashMap.this.remove(currentKey); lastReturned = null; } } final class KeyIterator extends HashIterator implements ReusableIterator, Enumeration { public K next() { return super.nextEntry().key(); } public K nextElement() { return super.nextEntry().key(); } } final class ValueIterator extends HashIterator implements ReusableIterator, Enumeration { public V next() { return super.nextEntry().value(); } public V nextElement() { return super.nextEntry().value(); } } /* * This class is needed for JDK5 compatibility. */ static class SimpleEntry implements Entry { private static final long serialVersionUID = -8144765946475398746L; private final K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } @SuppressWarnings("unchecked") Map.Entry e = (Map.Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } @Override public int hashCode() { return (key == null? 0 : key.hashCode()) ^ (value == null? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } private static boolean eq(Object o1, Object o2) { return o1 == null? o2 == null : o1.equals(o2); } } /** * Custom Entry class used by EntryIterator.next(), that relays setValue * changes to the underlying map. */ final class WriteThroughEntry extends SimpleEntry { WriteThroughEntry(K k, V v) { super(k, v); } /** * Set our entry's value and write through to the map. The value to * return is somewhat arbitrary here. Since a WriteThroughEntry does not * necessarily track asynchronous changes, the most recent "previous" * value could be different from what we return (or could even have been * removed in which case the put will re-establish). We do not and can * not guarantee more. */ @Override public V setValue(V value) { if (value == null) { throw new NullPointerException(); } V v = super.setValue(value); ConcurrentIdentityHashMap.this.put(getKey(), value); return v; } } final class EntryIterator extends HashIterator implements ReusableIterator> { public Map.Entry next() { HashEntry e = super.nextEntry(); return new WriteThroughEntry(e.key(), e.value()); } } final class KeySet extends AbstractSet { @Override public Iterator iterator() { return new KeyIterator(); } @Override public int size() { return ConcurrentIdentityHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentIdentityHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentIdentityHashMap.this.containsKey(o); } @Override public boolean remove(Object o) { return ConcurrentIdentityHashMap.this.remove(o) != null; } @Override public void clear() { ConcurrentIdentityHashMap.this.clear(); } } final class Values extends AbstractCollection { @Override public Iterator iterator() { return new ValueIterator(); } @Override public int size() { return ConcurrentIdentityHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentIdentityHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentIdentityHashMap.this.containsValue(o); } @Override public void clear() { ConcurrentIdentityHashMap.this.clear(); } } final class EntrySet extends AbstractSet> { @Override public Iterator> iterator() { return new EntryIterator(); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; V v = ConcurrentIdentityHashMap.this.get(e.getKey()); return v != null && v.equals(e.getValue()); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return ConcurrentIdentityHashMap.this.remove(e.getKey(), e.getValue()); } @Override public int size() { return ConcurrentIdentityHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentIdentityHashMap.this.isEmpty(); } @Override public void clear() { ConcurrentIdentityHashMap.this.clear(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ExecutorUtil.java0000644000175000017500000000752411165336702030675 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.TimeUnit; /** * Shuts down a list of {@link Executor}s. {@link #terminate(Executor...)} will * shut down all specified {@link ExecutorService}s immediately and wait for * their termination. An {@link Executor} which is not an {@link ExecutorService} * will be ignored silently. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public class ExecutorUtil { /** * Returns {@code true} if and only if the specified {@code executor} * is an {@link ExecutorService} and is shut down. Please note that this * method returns {@code false} if the specified {@code executor} is not an * {@link ExecutorService}. */ public static boolean isShutdown(Executor executor) { if (executor instanceof ExecutorService) { if (((ExecutorService) executor).isShutdown()) { return true; } } return false; } /** * Shuts down the specified executors. */ public static void terminate(Executor... executors) { Executor[] executorsCopy = new Executor[executors.length]; for (int i = 0; i < executors.length; i ++) { if (executors[i] == null) { throw new NullPointerException("executors[" + i + "]"); } executorsCopy[i] = executors[i]; } for (Executor e: executorsCopy) { if (!(e instanceof ExecutorService)) { continue; } ExecutorService es = (ExecutorService) e; for (;;) { try { es.shutdownNow(); } catch (SecurityException ex) { // Running in a restricted environment - fall back. try { es.shutdown(); } catch (SecurityException ex2) { // Running in a more restricted environment. // Can't shut down this executor - skip to the next. break; } catch (NullPointerException ex2) { // Some JDK throws NPE here, but shouldn't. } } catch (NullPointerException ex) { // Some JDK throws NPE here, but shouldn't. } try { if (es.awaitTermination(100, TimeUnit.MILLISECONDS)) { break; } } catch (InterruptedException ex) { // Ignore. } } } } private ExecutorUtil() { super(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/UnterminatableExecutor.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/UnterminatableExecutor.java0000644000175000017500000000331411165336702032723 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.util.concurrent.Executor; /** * Disables shutdown of an {@link Executor} by wrapping the {@link Executor}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public class UnterminatableExecutor implements Executor { private final Executor executor; public UnterminatableExecutor(Executor executor) { if (executor == null) { throw new NullPointerException("executor"); } this.executor = executor; } public void execute(Runnable command) { executor.execute(command); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConcurrentWeakKeyHashMap.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConcurrentWeakKeyHashMap.ja0000644000175000017500000014552211213433461032552 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.util.internal; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; /** * An alternative weak-key {@link ConcurrentMap} which is similar to * {@link java.util.concurrent.ConcurrentHashMap}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Doug Lea * @author Jason T. Greene * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1336 $, $Date: 2009-06-09 03:19:29 -0700 (Tue, 09 Jun 2009) $ * * @param the type of keys maintained by this map * @param the type of mapped values */ public final class ConcurrentWeakKeyHashMap extends AbstractMap implements ConcurrentMap { /* * The basic strategy is to subdivide the table among Segments, * each of which itself is a concurrently readable hash table. */ /** * The default initial capacity for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The default load factor for this table, used when not otherwise specified * in a constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The default concurrency level for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * The maximum capacity, used if a higher value is implicitly specified by * either of the constructors with arguments. MUST be a power of two * <= 1<<30 to ensure that entries are indexable using integers. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The maximum number of segments to allow; used to bound constructor * arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** * Number of unsynchronized retries in size and containsValue methods before * resorting to locking. This is used to avoid unbounded retries if tables * undergo continuous modification which would make it impossible to obtain * an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** * Mask value for indexing into segments. The upper bits of a key's hash * code are used to choose the segment. */ final int segmentMask; /** * Shift value for indexing within segments. */ final int segmentShift; /** * The segments, each of which is a specialized hash table */ final Segment[] segments; Set keySet; Set> entrySet; Collection values; /* ---------------- Small Utilities -------------- */ /** * Applies a supplemental hash function to a given hashCode, which defends * against poor quality hash functions. This is critical because * ConcurrentReferenceHashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ in lower * or upper bits. */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += h << 15 ^ 0xffffcd7d; h ^= h >>> 10; h += h << 3; h ^= h >>> 6; h += (h << 2) + (h << 14); return h ^ h >>> 16; } /** * Returns the segment that should be used for key with given hash. * * @param hash the hash code for the key * @return the segment */ final Segment segmentFor(int hash) { return segments[hash >>> segmentShift & segmentMask]; } private int hashOf(Object key) { return hash(key.hashCode()); } /* ---------------- Inner Classes -------------- */ /** * A weak-key reference which stores the key hash needed for reclamation. */ static final class WeakKeyReference extends WeakReference { final int hash; WeakKeyReference(K key, int hash, ReferenceQueue refQueue) { super(key, refQueue); this.hash = hash; } public final int keyHash() { return hash; } public final Object keyRef() { return this; } } /** * ConcurrentReferenceHashMap list entry. Note that this is never exported * out as a user-visible Map.Entry. * * Because the value field is volatile, not final, it is legal wrt * the Java Memory Model for an unsynchronized reader to see null * instead of initial value when read via a data race. Although a * reordering leading to this is not likely to ever actually * occur, the Segment.readValueUnderLock method is used as a * backup in case a null (pre-initialized) value is ever seen in * an unsynchronized access method. */ static final class HashEntry { final Object keyRef; final int hash; volatile Object valueRef; final HashEntry next; HashEntry( K key, int hash, HashEntry next, V value, ReferenceQueue refQueue) { this.hash = hash; this.next = next; this.keyRef = new WeakKeyReference(key, hash, refQueue); this.valueRef = value; } @SuppressWarnings("unchecked") final K key() { return ((WeakReference) keyRef).get(); } final V value() { return dereferenceValue(valueRef); } @SuppressWarnings("unchecked") final V dereferenceValue(Object value) { if (value instanceof WeakKeyReference) { return ((Reference) value).get(); } return (V) value; } final void setValue(V value) { this.valueRef = value; } @SuppressWarnings("unchecked") static final HashEntry[] newArray(int i) { return new HashEntry[i]; } } /** * Segments are specialized versions of hash tables. This subclasses from * ReentrantLock opportunistically, just to simplify some locking and avoid * separate construction. */ static final class Segment extends ReentrantLock { /* * Segments maintain a table of entry lists that are ALWAYS kept in a * consistent state, so can be read without locking. Next fields of * nodes are immutable (final). All list additions are performed at the * front of each bin. This makes it easy to check changes, and also fast * to traverse. When nodes would otherwise be changed, new nodes are * created to replace them. This works well for hash tables since the * bin lists tend to be short. (The average length is less than two for * the default load factor threshold.) * * Read operations can thus proceed without locking, but rely on * selected uses of volatiles to ensure that completed write operations * performed by other threads are noticed. For most purposes, the * "count" field, tracking the number of elements, serves as that * volatile variable ensuring visibility. This is convenient because * this field needs to be read in many read operations anyway: * * - All (unsynchronized) read operations must first read the * "count" field, and should not look at table entries if * it is 0. * * - All (synchronized) write operations should write to * the "count" field after structurally changing any bin. * The operations must not take any action that could even * momentarily cause a concurrent read operation to see * inconsistent data. This is made easier by the nature of * the read operations in Map. For example, no operation * can reveal that the table has grown but the threshold * has not yet been updated, so there are no atomicity * requirements for this with respect to reads. * * As a guide, all critical volatile reads and writes to the count field * are marked in code comments. */ private static final long serialVersionUID = -8328104880676891126L; /** * The number of elements in this segment's region. */ transient volatile int count; /** * Number of updates that alter the size of the table. This is used * during bulk-read methods to make sure they see a consistent snapshot: * If modCounts change during a traversal of segments computing size or * checking containsValue, then we might have an inconsistent view of * state so (usually) must retry. */ int modCount; /** * The table is rehashed when its size exceeds this threshold. * (The value of this field is always (capacity * loadFactor).) */ int threshold; /** * The per-segment table. */ transient volatile HashEntry[] table; /** * The load factor for the hash table. Even though this value is same * for all segments, it is replicated to avoid needing links to outer * object. * * @serial */ final float loadFactor; /** * The collected weak-key reference queue for this segment. This should * be (re)initialized whenever table is assigned, */ transient volatile ReferenceQueue refQueue; Segment(int initialCapacity, float lf) { loadFactor = lf; setTable(HashEntry. newArray(initialCapacity)); } @SuppressWarnings("unchecked") static final Segment[] newArray(int i) { return new Segment[i]; } private boolean keyEq(Object src, Object dest) { return src.equals(dest); } /** * Sets table to new HashEntry array. Call only while holding lock or in * constructor. */ void setTable(HashEntry[] newTable) { threshold = (int) (newTable.length * loadFactor); table = newTable; refQueue = new ReferenceQueue(); } /** * Returns properly casted first entry of bin for given hash. */ HashEntry getFirst(int hash) { HashEntry[] tab = table; return tab[hash & tab.length - 1]; } HashEntry newHashEntry( K key, int hash, HashEntry next, V value) { return new HashEntry( key, hash, next, value, refQueue); } /** * Reads value field of an entry under lock. Called if value field ever * appears to be null. This is possible only if a compiler happens to * reorder a HashEntry initialization with its table assignment, which * is legal under memory model but is not known to ever occur. */ V readValueUnderLock(HashEntry e) { lock(); try { removeStale(); return e.value(); } finally { unlock(); } } /* Specialized implementations of map methods */ V get(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { Object opaque = e.valueRef; if (opaque != null) { return e.dereferenceValue(opaque); } return readValueUnderLock(e); // recheck } e = e.next; } } return null; } boolean containsKey(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { return true; } e = e.next; } } return false; } boolean containsValue(Object value) { if (count != 0) { // read-volatile HashEntry[] tab = table; int len = tab.length; for (int i = 0; i < len; i ++) { for (HashEntry e = tab[i]; e != null; e = e.next) { Object opaque = e.valueRef; V v; if (opaque == null) { v = readValueUnderLock(e); // recheck } else { v = e.dereferenceValue(opaque); } if (value.equals(v)) { return true; } } } } return false; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { removeStale(); HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } boolean replaced = false; if (e != null && oldValue.equals(e.value())) { replaced = true; e.setValue(newValue); } return replaced; } finally { unlock(); } } V replace(K key, int hash, V newValue) { lock(); try { removeStale(); HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { oldValue = e.value(); e.setValue(newValue); } return oldValue; } finally { unlock(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { removeStale(); int c = count; if (c ++ > threshold) { // ensure capacity int reduced = rehash(); if (reduced > 0) { count = (c -= reduced) - 1; // write-volatile } } HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue; if (e != null) { oldValue = e.value(); if (!onlyIfAbsent) { e.setValue(value); } } else { oldValue = null; ++ modCount; tab[index] = newHashEntry(key, hash, first, value); count = c; // write-volatile } return oldValue; } finally { unlock(); } } int rehash() { HashEntry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) { return 0; } /* * Reclassify nodes in each list to new Map. Because we are using * power-of-two expansion, the elements from each bin must either * stay at same index, or move with a power of two offset. We * eliminate unnecessary node creation by catching cases where old * nodes can be reused because their next fields won't change. * Statistically, at the default threshold, only about one-sixth of * them need cloning when a table doubles. The nodes they replace * will be garbage collectable as soon as they are no longer * referenced by any reader thread that may be in the midst of * traversing table right now. */ HashEntry[] newTable = HashEntry.newArray(oldCapacity << 1); threshold = (int) (newTable.length * loadFactor); int sizeMask = newTable.length - 1; int reduce = 0; for (int i = 0; i < oldCapacity; i ++) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. HashEntry e = oldTable[i]; if (e != null) { HashEntry next = e.next; int idx = e.hash & sizeMask; // Single node on list if (next == null) { newTable[idx] = e; } else { // Reuse trailing consecutive sequence at same slot HashEntry lastRun = e; int lastIdx = idx; for (HashEntry last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (HashEntry p = e; p != lastRun; p = p.next) { // Skip GC'd weak references K key = p.key(); if (key == null) { reduce ++; continue; } int k = p.hash & sizeMask; HashEntry n = newTable[k]; newTable[k] = newHashEntry(key, p.hash, n, p.value()); } } } } table = newTable; return reduce; } /** * Remove; match on key only if value null, else match both. */ V remove(Object key, int hash, Object value, boolean refRemove) { lock(); try { if (!refRemove) { removeStale(); } int c = count - 1; HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; // a reference remove operation compares the Reference instance while (e != null && key != e.keyRef && (refRemove || hash != e.hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { V v = e.value(); if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay in list, // but all preceding ones need to be cloned. ++ modCount; HashEntry newFirst = e.next; for (HashEntry p = first; p != e; p = p.next) { K pKey = p.key(); if (pKey == null) { // Skip GC'd keys c --; continue; } newFirst = newHashEntry( pKey, p.hash, newFirst, p.value()); } tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } } @SuppressWarnings("unchecked") final void removeStale() { WeakKeyReference ref; while ((ref = (WeakKeyReference) refQueue.poll()) != null) { remove(ref.keyRef(), ref.keyHash(), null, true); } } void clear() { if (count != 0) { lock(); try { HashEntry[] tab = table; for (int i = 0; i < tab.length; i ++) { tab[i] = null; } ++ modCount; // replace the reference queue to avoid unnecessary stale // cleanups refQueue = new ReferenceQueue(); count = 0; // write-volatile } finally { unlock(); } } } } /* ---------------- Public operations -------------- */ /** * Creates a new, empty map with the specified initial capacity, load factor * and concurrency level. * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently updating * threads. The implementation performs internal * sizing to try to accommodate this many threads. * @throws IllegalArgumentException if the initial capacity is negative or * the load factor or concurrencyLevel are * nonpositive. */ public ConcurrentWeakKeyHashMap( int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) { throw new IllegalArgumentException(); } if (concurrencyLevel > MAX_SEGMENTS) { concurrencyLevel = MAX_SEGMENTS; } // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; while (ssize < concurrencyLevel) { ++ sshift; ssize <<= 1; } segmentShift = 32 - sshift; segmentMask = ssize - 1; this.segments = Segment.newArray(ssize); if (initialCapacity > MAXIMUM_CAPACITY) { initialCapacity = MAXIMUM_CAPACITY; } int c = initialCapacity / ssize; if (c * ssize < initialCapacity) { ++ c; } int cap = 1; while (cap < c) { cap <<= 1; } for (int i = 0; i < this.segments.length; ++ i) { this.segments[i] = new Segment(cap, loadFactor); } } /** * Creates a new, empty map with the specified initial capacity and load * factor and with the default reference types (weak keys, strong values), * and concurrencyLevel (16). * * @param initialCapacity The implementation performs internal sizing to * accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @throws IllegalArgumentException if the initial capacity of elements is * negative or the load factor is * nonpositive */ public ConcurrentWeakKeyHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with the specified initial capacity, and with * default reference types (weak keys, strong values), load factor (0.75) * and concurrencyLevel (16). * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @throws IllegalArgumentException if the initial capacity of elements is * negative. */ public ConcurrentWeakKeyHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with a default initial capacity (16), reference * types (weak keys, strong values), default load factor (0.75) and * concurrencyLevel (16). */ public ConcurrentWeakKeyHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new map with the same mappings as the given map. The map is * created with a capacity of 1.5 times the number of mappings in the given * map or 16 (whichever is greater), and a default load factor (0.75) and * concurrencyLevel (16). * * @param m the map */ public ConcurrentWeakKeyHashMap(Map m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); putAll(m); } /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ @Override public boolean isEmpty() { final Segment[] segments = this.segments; /* * We keep track of per-segment modCounts to avoid ABA problems in which * an element in one segment was added and in another removed during * traversal, in which case the table was never actually empty at any * point. Note the similar use of modCounts in the size() and * containsValue() methods, which are the only other methods also * susceptible to ABA problems. */ int[] mc = new int[segments.length]; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0) { return false; } else { mcsum += mc[i] = segments[i].modCount; } } // If mcsum happens to be zero, then we know we got a snapshot before // any modifications at all were made. This is probably common enough // to bother tracking. if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0 || mc[i] != segments[i].modCount) { return false; } } } return true; } /** * Returns the number of key-value mappings in this map. If the map contains * more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ @Override public int size() { final Segment[] segments = this.segments; long sum = 0; long check = 0; int[] mc = new int[segments.length]; // Try a few times to get accurate count. On failure due to continuous // async changes in table, resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { check = 0; sum = 0; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; mcsum += mc[i] = segments[i].modCount; } if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { check += segments[i].count; if (mc[i] != segments[i].modCount) { check = -1; // force retry break; } } } if (check == sum) { break; } } if (check != sum) { // Resort to locking all segments sum = 0; for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; } for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } if (sum > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) sum; } } /** * Returns the value to which the specified key is mapped, or {@code null} * if this map contains no mapping for the key. * *

More formally, if this map contains a mapping from a key {@code k} to * a value {@code v} such that {@code key.equals(k)}, then this method * returns {@code v}; otherwise it returns {@code null}. (There can be at * most one such mapping.) * * @throws NullPointerException if the specified key is null */ @Override public V get(Object key) { int hash = hashOf(key); return segmentFor(hash).get(key, hash); } /** * Tests if the specified object is a key in this table. * * @param key possible key * @return true if and only if the specified object is a key in * this table, as determined by the equals method; * false otherwise. * @throws NullPointerException if the specified key is null */ @Override public boolean containsKey(Object key) { int hash = hashOf(key); return segmentFor(hash).containsKey(key, hash); } /** * Returns true if this map maps one or more keys to the specified * value. Note: This method requires a full internal traversal of the hash * table, and so is much slower than method containsKey. * * @param value value whose presence in this map is to be tested * @return true if this map maps one or more keys to the specified * value * @throws NullPointerException if the specified value is null */ @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } // See explanation of modCount use above final Segment[] segments = this.segments; int[] mc = new int[segments.length]; // Try a few times without locking for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { mcsum += mc[i] = segments[i].modCount; if (segments[i].containsValue(value)) { return true; } } boolean cleanSweep = true; if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (mc[i] != segments[i].modCount) { cleanSweep = false; break; } } } if (cleanSweep) { return false; } } // Resort to locking all segments for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } boolean found = false; try { for (int i = 0; i < segments.length; ++ i) { if (segments[i].containsValue(value)) { found = true; break; } } } finally { for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } return found; } /** * Legacy method testing if some key maps into the specified value in this * table. This method is identical in functionality to * {@link #containsValue}, and exists solely to ensure full compatibility * with class {@link Hashtable}, which supported this method prior to * introduction of the Java Collections framework. * * @param value a value to search for * @return true if and only if some key maps to the value * argument in this table as determined by the equals * method; false otherwise * @throws NullPointerException if the specified value is null */ public boolean contains(Object value) { return containsValue(value); } /** * Maps the specified key to the specified value in this table. Neither the * key nor the value can be null. * *

The value can be retrieved by calling the get method with a * key that is equal to the original key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key or value is null */ @Override public V put(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, false); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V putIfAbsent(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, true); } /** * Copies all of the mappings from the specified map to this one. These * mappings replace any mappings that this map had for any of the keys * currently in the specified map. * * @param m mappings to be stored in this map */ @Override public void putAll(Map m) { for (Map.Entry e: m.entrySet()) { put(e.getKey(), e.getValue()); } } /** * Removes the key (and its corresponding value) from this map. This method * does nothing if the key is not in the map. * * @param key the key that needs to be removed * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key is null */ @Override public V remove(Object key) { int hash = hashOf(key); return segmentFor(hash).remove(key, hash, null, false); } /** * {@inheritDoc} * * @throws NullPointerException if the specified key is null */ public boolean remove(Object key, Object value) { int hash = hashOf(key); if (value == null) { return false; } return segmentFor(hash).remove(key, hash, value, false) != null; } /** * {@inheritDoc} * * @throws NullPointerException if any of the arguments are null */ public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, oldValue, newValue); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V replace(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, value); } /** * Removes all of the mappings from this map. */ @Override public void clear() { for (int i = 0; i < segments.length; ++ i) { segments[i].clear(); } } /** * Removes any stale entries whose keys have been finalized. Use of this * method is normally not necessary since stale entries are automatically * removed lazily, when blocking operations are required. However, there are * some cases where this operation should be performed eagerly, such as * cleaning up old references to a ClassLoader in a multi-classloader * environment. * * Note: this method will acquire locks, one at a time, across all segments * of this table, so if it is to be used, it should be used sparingly. */ public void purgeStaleEntries() { for (int i = 0; i < segments.length; ++ i) { segments[i].removeStale(); } } /** * Returns a {@link Set} view of the keys contained in this map. The set is * backed by the map, so changes to the map are reflected in the set, and * vice-versa. The set supports element removal, which removes the * corresponding mapping from this map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set keySet() { Set ks = keySet; return ks != null? ks : (keySet = new KeySet()); } /** * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are reflected * in the collection, and vice-versa. The collection supports element * removal, which removes the corresponding mapping from this map, via the * Iterator.remove, Collection.remove, removeAll, * retainAll, and clear operations. It does not support * the add or addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Collection values() { Collection vs = values; return vs != null? vs : (values = new Values()); } /** * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are reflected in the * set, and vice-versa. The set supports element removal, which removes the * corresponding mapping from the map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set> entrySet() { Set> es = entrySet; return es != null? es : (entrySet = new EntrySet()); } /** * Returns an enumeration of the keys in this table. * * @return an enumeration of the keys in this table * @see #keySet() */ public Enumeration keys() { return new KeyIterator(); } /** * Returns an enumeration of the values in this table. * * @return an enumeration of the values in this table * @see #values() */ public Enumeration elements() { return new ValueIterator(); } /* ---------------- Iterator Support -------------- */ abstract class HashIterator { int nextSegmentIndex; int nextTableIndex; HashEntry[] currentTable; HashEntry nextEntry; HashEntry lastReturned; K currentKey; // Strong reference to weak key (prevents gc) HashIterator() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; advance(); } public void rewind() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; currentTable = null; nextEntry = null; lastReturned = null; currentKey = null; advance(); } public boolean hasMoreElements() { return hasNext(); } final void advance() { if (nextEntry != null && (nextEntry = nextEntry.next) != null) { return; } while (nextTableIndex >= 0) { if ((nextEntry = currentTable[nextTableIndex --]) != null) { return; } } while (nextSegmentIndex >= 0) { Segment seg = segments[nextSegmentIndex --]; if (seg.count != 0) { currentTable = seg.table; for (int j = currentTable.length - 1; j >= 0; -- j) { if ((nextEntry = currentTable[j]) != null) { nextTableIndex = j - 1; return; } } } } } public boolean hasNext() { while (nextEntry != null) { if (nextEntry.key() != null) { return true; } advance(); } return false; } HashEntry nextEntry() { do { if (nextEntry == null) { throw new NoSuchElementException(); } lastReturned = nextEntry; currentKey = lastReturned.key(); advance(); } while (currentKey == null); // Skip GC'd keys return lastReturned; } public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } ConcurrentWeakKeyHashMap.this.remove(currentKey); lastReturned = null; } } final class KeyIterator extends HashIterator implements ReusableIterator, Enumeration { public K next() { return super.nextEntry().key(); } public K nextElement() { return super.nextEntry().key(); } } final class ValueIterator extends HashIterator implements ReusableIterator, Enumeration { public V next() { return super.nextEntry().value(); } public V nextElement() { return super.nextEntry().value(); } } /* * This class is needed for JDK5 compatibility. */ static class SimpleEntry implements Entry { private final K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } @SuppressWarnings("unchecked") Map.Entry e = (Map.Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } @Override public int hashCode() { return (key == null? 0 : key.hashCode()) ^ (value == null? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } private static boolean eq(Object o1, Object o2) { return o1 == null? o2 == null : o1.equals(o2); } } /** * Custom Entry class used by EntryIterator.next(), that relays setValue * changes to the underlying map. */ final class WriteThroughEntry extends SimpleEntry { WriteThroughEntry(K k, V v) { super(k, v); } /** * Set our entry's value and write through to the map. The value to * return is somewhat arbitrary here. Since a WriteThroughEntry does not * necessarily track asynchronous changes, the most recent "previous" * value could be different from what we return (or could even have been * removed in which case the put will re-establish). We do not and can * not guarantee more. */ @Override public V setValue(V value) { if (value == null) { throw new NullPointerException(); } V v = super.setValue(value); ConcurrentWeakKeyHashMap.this.put(getKey(), value); return v; } } final class EntryIterator extends HashIterator implements ReusableIterator> { public Map.Entry next() { HashEntry e = super.nextEntry(); return new WriteThroughEntry(e.key(), e.value()); } } final class KeySet extends AbstractSet { @Override public Iterator iterator() { return new KeyIterator(); } @Override public int size() { return ConcurrentWeakKeyHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentWeakKeyHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentWeakKeyHashMap.this.containsKey(o); } @Override public boolean remove(Object o) { return ConcurrentWeakKeyHashMap.this.remove(o) != null; } @Override public void clear() { ConcurrentWeakKeyHashMap.this.clear(); } } final class Values extends AbstractCollection { @Override public Iterator iterator() { return new ValueIterator(); } @Override public int size() { return ConcurrentWeakKeyHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentWeakKeyHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentWeakKeyHashMap.this.containsValue(o); } @Override public void clear() { ConcurrentWeakKeyHashMap.this.clear(); } } final class EntrySet extends AbstractSet> { @Override public Iterator> iterator() { return new EntryIterator(); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; V v = ConcurrentWeakKeyHashMap.this.get(e.getKey()); return v != null && v.equals(e.getValue()); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return ConcurrentWeakKeyHashMap.this.remove(e.getKey(), e.getValue()); } @Override public int size() { return ConcurrentWeakKeyHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentWeakKeyHashMap.this.isEmpty(); } @Override public void clear() { ConcurrentWeakKeyHashMap.this.clear(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/CombinedIterator.java0000644000175000017500000000470511165336702031471 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.util.Iterator; import java.util.NoSuchElementException; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public class CombinedIterator implements Iterator { private final Iterator i1; private final Iterator i2; private Iterator currentIterator; public CombinedIterator(Iterator i1, Iterator i2) { if (i1 == null) { throw new NullPointerException("i1"); } if (i2 == null) { throw new NullPointerException("i2"); } this.i1 = i1; this.i2 = i2; currentIterator = i1; } public boolean hasNext() { boolean hasNext = currentIterator.hasNext(); if (hasNext) { return true; } if (currentIterator == i1) { currentIterator = i2; return hasNext(); } else { return false; } } public E next() { try { E e = currentIterator.next(); return e; } catch (NoSuchElementException e) { if (currentIterator == i1) { currentIterator = i2; return next(); } else { throw e; } } } public void remove() { currentIterator.remove(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/StackTraceSimplifier.java0000644000175000017500000000654311213672505032307 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.util.ArrayList; import java.util.List; import java.util.regex.Pattern; import org.jboss.netty.channel.DefaultChannelPipeline; import org.jboss.netty.channel.SimpleChannelHandler; import org.jboss.netty.util.DebugUtil; import org.jboss.netty.util.ThreadRenamingRunnable; /** * Simplifies an exception stack trace by removing unnecessary * {@link StackTraceElement}s. Please note that the stack trace simplification * is disabled if {@linkplain DebugUtil debug mode} is turned on. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1338 $, $Date: 2009-06-10 01:56:37 -0700 (Wed, 10 Jun 2009) $ * */ public class StackTraceSimplifier { private static final boolean SIMPLIFY_STACK_TRACE = !DebugUtil.isDebugEnabled(); private static final Pattern EXCLUDED_STACK_TRACE = Pattern.compile( "^org\\.jboss\\.netty\\." + "(util\\.(ThreadRenamingRunnable)" + "|channel\\.(SimpleChannel(Upstream|Downstream)?Handler|DefaultChannelPipeline.*))$"); /** * Removes unnecessary {@link StackTraceElement}s from the specified * exception. {@link ThreadRenamingRunnable}, {@link SimpleChannelHandler}, * and {@link DefaultChannelPipeline} will be dropped from the trace. */ public static void simplify(Throwable e) { if (!SIMPLIFY_STACK_TRACE) { return; } if (e.getCause() != null) { simplify(e.getCause()); } StackTraceElement[] trace = e.getStackTrace(); if (trace == null || trace.length == 0) { return; } // Perhaps Netty bug. Let us not strip things out. if (EXCLUDED_STACK_TRACE.matcher(trace[0].getClassName()).matches()) { return; } List simpleTrace = new ArrayList(trace.length); simpleTrace.add(trace[0]); // Remove unnecessary stack trace elements. for (int i = 1; i < trace.length; i ++) { if (EXCLUDED_STACK_TRACE.matcher(trace[i].getClassName()).matches()) { continue; } simpleTrace.add(trace[i]); } e.setStackTrace( simpleTrace.toArray(new StackTraceElement[simpleTrace.size()])); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConcurrentHashMap.java0000644000175000017500000013756011213433461031623 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.util.internal; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; /** * An alternative {@link ConcurrentMap} implementation which is similar to * {@link java.util.concurrent.ConcurrentHashMap}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Doug Lea * @author Jason T. Greene * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1336 $, $Date: 2009-06-09 03:19:29 -0700 (Tue, 09 Jun 2009) $ * * @param the type of keys maintained by this map * @param the type of mapped values */ public final class ConcurrentHashMap extends AbstractMap implements ConcurrentMap{ /** * The default initial capacity for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The default load factor for this table, used when not otherwise specified * in a constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The default concurrency level for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * The maximum capacity, used if a higher value is implicitly specified by * either of the constructors with arguments. MUST be a power of two * <= 1<<30 to ensure that entries are indexable using integers. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The maximum number of segments to allow; used to bound constructor * arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** * Number of unsynchronized retries in size and containsValue methods before * resorting to locking. This is used to avoid unbounded retries if tables * undergo continuous modification which would make it impossible to obtain * an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** * Mask value for indexing into segments. The upper bits of a key's hash * code are used to choose the segment. */ final int segmentMask; /** * Shift value for indexing within segments. */ final int segmentShift; /** * The segments, each of which is a specialized hash table */ final Segment[] segments; Set keySet; Set> entrySet; Collection values; /* ---------------- Small Utilities -------------- */ /** * Applies a supplemental hash function to a given hashCode, which defends * against poor quality hash functions. This is critical because * ConcurrentReferenceHashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ in lower * or upper bits. */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += h << 15 ^ 0xffffcd7d; h ^= h >>> 10; h += h << 3; h ^= h >>> 6; h += (h << 2) + (h << 14); return h ^ h >>> 16; } /** * Returns the segment that should be used for key with given hash. * * @param hash the hash code for the key * @return the segment */ final Segment segmentFor(int hash) { return segments[hash >>> segmentShift & segmentMask]; } private int hashOf(Object key) { return hash(key.hashCode()); } /** * ConcurrentReferenceHashMap list entry. Note that this is never exported * out as a user-visible Map.Entry. * * Because the value field is volatile, not final, it is legal wrt * the Java Memory Model for an unsynchronized reader to see null * instead of initial value when read via a data race. Although a * reordering leading to this is not likely to ever actually * occur, the Segment.readValueUnderLock method is used as a * backup in case a null (pre-initialized) value is ever seen in * an unsynchronized access method. */ static final class HashEntry { final Object key; final int hash; volatile Object value; final HashEntry next; HashEntry( K key, int hash, HashEntry next, V value) { this.hash = hash; this.next = next; this.key = key; this.value = value; } @SuppressWarnings("unchecked") final K key() { return (K) key; } @SuppressWarnings("unchecked") final V value() { return (V) value; } final void setValue(V value) { this.value = value; } @SuppressWarnings("unchecked") static final HashEntry[] newArray(int i) { return new HashEntry[i]; } } /** * Segments are specialized versions of hash tables. This subclasses from * ReentrantLock opportunistically, just to simplify some locking and avoid * separate construction. */ static final class Segment extends ReentrantLock { /* * Segments maintain a table of entry lists that are ALWAYS kept in a * consistent state, so can be read without locking. Next fields of * nodes are immutable (final). All list additions are performed at the * front of each bin. This makes it easy to check changes, and also fast * to traverse. When nodes would otherwise be changed, new nodes are * created to replace them. This works well for hash tables since the * bin lists tend to be short. (The average length is less than two for * the default load factor threshold.) * * Read operations can thus proceed without locking, but rely on * selected uses of volatiles to ensure that completed write operations * performed by other threads are noticed. For most purposes, the * "count" field, tracking the number of elements, serves as that * volatile variable ensuring visibility. This is convenient because * this field needs to be read in many read operations anyway: * * - All (unsynchronized) read operations must first read the * "count" field, and should not look at table entries if * it is 0. * * - All (synchronized) write operations should write to * the "count" field after structurally changing any bin. * The operations must not take any action that could even * momentarily cause a concurrent read operation to see * inconsistent data. This is made easier by the nature of * the read operations in Map. For example, no operation * can reveal that the table has grown but the threshold * has not yet been updated, so there are no atomicity * requirements for this with respect to reads. * * As a guide, all critical volatile reads and writes to the count field * are marked in code comments. */ private static final long serialVersionUID = -2001752926705396395L; /** * The number of elements in this segment's region. */ transient volatile int count; /** * Number of updates that alter the size of the table. This is used * during bulk-read methods to make sure they see a consistent snapshot: * If modCounts change during a traversal of segments computing size or * checking containsValue, then we might have an inconsistent view of * state so (usually) must retry. */ int modCount; /** * The table is rehashed when its size exceeds this threshold. * (The value of this field is always (capacity * loadFactor).) */ int threshold; /** * The per-segment table. */ transient volatile HashEntry[] table; /** * The load factor for the hash table. Even though this value is same * for all segments, it is replicated to avoid needing links to outer * object. * * @serial */ final float loadFactor; Segment(int initialCapacity, float lf) { loadFactor = lf; setTable(HashEntry. newArray(initialCapacity)); } @SuppressWarnings("unchecked") static final Segment[] newArray(int i) { return new Segment[i]; } private boolean keyEq(Object src, Object dest) { return src.equals(dest); } /** * Sets table to new HashEntry array. Call only while holding lock or in * constructor. */ void setTable(HashEntry[] newTable) { threshold = (int) (newTable.length * loadFactor); table = newTable; } /** * Returns properly casted first entry of bin for given hash. */ HashEntry getFirst(int hash) { HashEntry[] tab = table; return tab[hash & tab.length - 1]; } HashEntry newHashEntry( K key, int hash, HashEntry next, V value) { return new HashEntry(key, hash, next, value); } /** * Reads value field of an entry under lock. Called if value field ever * appears to be null. This is possible only if a compiler happens to * reorder a HashEntry initialization with its table assignment, which * is legal under memory model but is not known to ever occur. */ V readValueUnderLock(HashEntry e) { lock(); try { return e.value(); } finally { unlock(); } } /* Specialized implementations of map methods */ V get(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { V opaque = e.value(); if (opaque != null) { return opaque; } return readValueUnderLock(e); // recheck } e = e.next; } } return null; } boolean containsKey(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { return true; } e = e.next; } } return false; } boolean containsValue(Object value) { if (count != 0) { // read-volatile HashEntry[] tab = table; int len = tab.length; for (int i = 0; i < len; i ++) { for (HashEntry e = tab[i]; e != null; e = e.next) { V opaque = e.value(); V v; if (opaque == null) { v = readValueUnderLock(e); // recheck } else { v = opaque; } if (value.equals(v)) { return true; } } } } return false; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } boolean replaced = false; if (e != null && oldValue.equals(e.value())) { replaced = true; e.setValue(newValue); } return replaced; } finally { unlock(); } } V replace(K key, int hash, V newValue) { lock(); try { HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { oldValue = e.value(); e.setValue(newValue); } return oldValue; } finally { unlock(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { int c = count; if (c ++ > threshold) { // ensure capacity int reduced = rehash(); if (reduced > 0) { count = (c -= reduced) - 1; // write-volatile } } HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue; if (e != null) { oldValue = e.value(); if (!onlyIfAbsent) { e.setValue(value); } } else { oldValue = null; ++ modCount; tab[index] = newHashEntry(key, hash, first, value); count = c; // write-volatile } return oldValue; } finally { unlock(); } } int rehash() { HashEntry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) { return 0; } /* * Reclassify nodes in each list to new Map. Because we are using * power-of-two expansion, the elements from each bin must either * stay at same index, or move with a power of two offset. We * eliminate unnecessary node creation by catching cases where old * nodes can be reused because their next fields won't change. * Statistically, at the default threshold, only about one-sixth of * them need cloning when a table doubles. The nodes they replace * will be garbage collectable as soon as they are no longer * referenced by any reader thread that may be in the midst of * traversing table right now. */ HashEntry[] newTable = HashEntry.newArray(oldCapacity << 1); threshold = (int) (newTable.length * loadFactor); int sizeMask = newTable.length - 1; int reduce = 0; for (int i = 0; i < oldCapacity; i ++) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. HashEntry e = oldTable[i]; if (e != null) { HashEntry next = e.next; int idx = e.hash & sizeMask; // Single node on list if (next == null) { newTable[idx] = e; } else { // Reuse trailing consecutive sequence at same slot HashEntry lastRun = e; int lastIdx = idx; for (HashEntry last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (HashEntry p = e; p != lastRun; p = p.next) { // Skip GC'd weak references K key = p.key(); if (key == null) { reduce ++; continue; } int k = p.hash & sizeMask; HashEntry n = newTable[k]; newTable[k] = newHashEntry(key, p.hash, n, p.value()); } } } } table = newTable; return reduce; } /** * Remove; match on key only if value null, else match both. */ V remove(Object key, int hash, Object value, boolean refRemove) { lock(); try { int c = count - 1; HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; // a reference remove operation compares the Reference instance while (e != null && key != e.key && (refRemove || hash != e.hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { V v = e.value(); if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay in list, // but all preceding ones need to be cloned. ++ modCount; HashEntry newFirst = e.next; for (HashEntry p = first; p != e; p = p.next) { K pKey = p.key(); if (pKey == null) { // Skip GC'd keys c --; continue; } newFirst = newHashEntry( pKey, p.hash, newFirst, p.value()); } tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } } void clear() { if (count != 0) { lock(); try { HashEntry[] tab = table; for (int i = 0; i < tab.length; i ++) { tab[i] = null; } ++ modCount; count = 0; // write-volatile } finally { unlock(); } } } } /* ---------------- Public operations -------------- */ /** * Creates a new, empty map with the specified initial capacity, load factor * and concurrency level. * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently updating * threads. The implementation performs internal * sizing to try to accommodate this many threads. * @throws IllegalArgumentException if the initial capacity is negative or * the load factor or concurrencyLevel are * nonpositive. */ public ConcurrentHashMap( int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) { throw new IllegalArgumentException(); } if (concurrencyLevel > MAX_SEGMENTS) { concurrencyLevel = MAX_SEGMENTS; } // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; while (ssize < concurrencyLevel) { ++ sshift; ssize <<= 1; } segmentShift = 32 - sshift; segmentMask = ssize - 1; this.segments = Segment.newArray(ssize); if (initialCapacity > MAXIMUM_CAPACITY) { initialCapacity = MAXIMUM_CAPACITY; } int c = initialCapacity / ssize; if (c * ssize < initialCapacity) { ++ c; } int cap = 1; while (cap < c) { cap <<= 1; } for (int i = 0; i < this.segments.length; ++ i) { this.segments[i] = new Segment(cap, loadFactor); } } /** * Creates a new, empty map with the specified initial capacity and load * factor and with the default reference types (weak keys, strong values), * and concurrencyLevel (16). * * @param initialCapacity The implementation performs internal sizing to * accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @throws IllegalArgumentException if the initial capacity of elements is * negative or the load factor is * nonpositive */ public ConcurrentHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with the specified initial capacity, and with * default reference types (weak keys, strong values), load factor (0.75) * and concurrencyLevel (16). * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @throws IllegalArgumentException if the initial capacity of elements is * negative. */ public ConcurrentHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with a default initial capacity (16), reference * types (weak keys, strong values), default load factor (0.75) and * concurrencyLevel (16). */ public ConcurrentHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new map with the same mappings as the given map. The map is * created with a capacity of 1.5 times the number of mappings in the given * map or 16 (whichever is greater), and a default load factor (0.75) and * concurrencyLevel (16). * * @param m the map */ public ConcurrentHashMap(Map m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); putAll(m); } /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ @Override public boolean isEmpty() { final Segment[] segments = this.segments; /* * We keep track of per-segment modCounts to avoid ABA problems in which * an element in one segment was added and in another removed during * traversal, in which case the table was never actually empty at any * point. Note the similar use of modCounts in the size() and * containsValue() methods, which are the only other methods also * susceptible to ABA problems. */ int[] mc = new int[segments.length]; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0) { return false; } else { mcsum += mc[i] = segments[i].modCount; } } // If mcsum happens to be zero, then we know we got a snapshot before // any modifications at all were made. This is probably common enough // to bother tracking. if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0 || mc[i] != segments[i].modCount) { return false; } } } return true; } /** * Returns the number of key-value mappings in this map. If the map contains * more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ @Override public int size() { final Segment[] segments = this.segments; long sum = 0; long check = 0; int[] mc = new int[segments.length]; // Try a few times to get accurate count. On failure due to continuous // async changes in table, resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { check = 0; sum = 0; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; mcsum += mc[i] = segments[i].modCount; } if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { check += segments[i].count; if (mc[i] != segments[i].modCount) { check = -1; // force retry break; } } } if (check == sum) { break; } } if (check != sum) { // Resort to locking all segments sum = 0; for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; } for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } if (sum > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) sum; } } /** * Returns the value to which the specified key is mapped, or {@code null} * if this map contains no mapping for the key. * *

More formally, if this map contains a mapping from a key {@code k} to * a value {@code v} such that {@code key.equals(k)}, then this method * returns {@code v}; otherwise it returns {@code null}. (There can be at * most one such mapping.) * * @throws NullPointerException if the specified key is null */ @Override public V get(Object key) { int hash = hashOf(key); return segmentFor(hash).get(key, hash); } /** * Tests if the specified object is a key in this table. * * @param key possible key * @return true if and only if the specified object is a key in * this table, as determined by the equals method; * false otherwise. * @throws NullPointerException if the specified key is null */ @Override public boolean containsKey(Object key) { int hash = hashOf(key); return segmentFor(hash).containsKey(key, hash); } /** * Returns true if this map maps one or more keys to the specified * value. Note: This method requires a full internal traversal of the hash * table, and so is much slower than method containsKey. * * @param value value whose presence in this map is to be tested * @return true if this map maps one or more keys to the specified * value * @throws NullPointerException if the specified value is null */ @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } // See explanation of modCount use above final Segment[] segments = this.segments; int[] mc = new int[segments.length]; // Try a few times without locking for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { mcsum += mc[i] = segments[i].modCount; if (segments[i].containsValue(value)) { return true; } } boolean cleanSweep = true; if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (mc[i] != segments[i].modCount) { cleanSweep = false; break; } } } if (cleanSweep) { return false; } } // Resort to locking all segments for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } boolean found = false; try { for (int i = 0; i < segments.length; ++ i) { if (segments[i].containsValue(value)) { found = true; break; } } } finally { for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } return found; } /** * Legacy method testing if some key maps into the specified value in this * table. This method is identical in functionality to * {@link #containsValue}, and exists solely to ensure full compatibility * with class {@link Hashtable}, which supported this method prior to * introduction of the Java Collections framework. * * @param value a value to search for * @return true if and only if some key maps to the value * argument in this table as determined by the equals * method; false otherwise * @throws NullPointerException if the specified value is null */ public boolean contains(Object value) { return containsValue(value); } /** * Maps the specified key to the specified value in this table. Neither the * key nor the value can be null. * *

The value can be retrieved by calling the get method with a * key that is equal to the original key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key or value is null */ @Override public V put(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, false); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V putIfAbsent(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, true); } /** * Copies all of the mappings from the specified map to this one. These * mappings replace any mappings that this map had for any of the keys * currently in the specified map. * * @param m mappings to be stored in this map */ @Override public void putAll(Map m) { for (Map.Entry e: m.entrySet()) { put(e.getKey(), e.getValue()); } } /** * Removes the key (and its corresponding value) from this map. This method * does nothing if the key is not in the map. * * @param key the key that needs to be removed * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key is null */ @Override public V remove(Object key) { int hash = hashOf(key); return segmentFor(hash).remove(key, hash, null, false); } /** * {@inheritDoc} * * @throws NullPointerException if the specified key is null */ public boolean remove(Object key, Object value) { int hash = hashOf(key); if (value == null) { return false; } return segmentFor(hash).remove(key, hash, value, false) != null; } /** * {@inheritDoc} * * @throws NullPointerException if any of the arguments are null */ public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, oldValue, newValue); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V replace(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, value); } /** * Removes all of the mappings from this map. */ @Override public void clear() { for (int i = 0; i < segments.length; ++ i) { segments[i].clear(); } } /** * Returns a {@link Set} view of the keys contained in this map. The set is * backed by the map, so changes to the map are reflected in the set, and * vice-versa. The set supports element removal, which removes the * corresponding mapping from this map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set keySet() { Set ks = keySet; return ks != null? ks : (keySet = new KeySet()); } /** * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are reflected * in the collection, and vice-versa. The collection supports element * removal, which removes the corresponding mapping from this map, via the * Iterator.remove, Collection.remove, removeAll, * retainAll, and clear operations. It does not support * the add or addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Collection values() { Collection vs = values; return vs != null? vs : (values = new Values()); } /** * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are reflected in the * set, and vice-versa. The set supports element removal, which removes the * corresponding mapping from the map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set> entrySet() { Set> es = entrySet; return es != null? es : (entrySet = new EntrySet()); } /** * Returns an enumeration of the keys in this table. * * @return an enumeration of the keys in this table * @see #keySet() */ public Enumeration keys() { return new KeyIterator(); } /** * Returns an enumeration of the values in this table. * * @return an enumeration of the values in this table * @see #values() */ public Enumeration elements() { return new ValueIterator(); } /* ---------------- Iterator Support -------------- */ abstract class HashIterator { int nextSegmentIndex; int nextTableIndex; HashEntry[] currentTable; HashEntry nextEntry; HashEntry lastReturned; K currentKey; // Strong reference to weak key (prevents gc) HashIterator() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; advance(); } public void rewind() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; currentTable = null; nextEntry = null; lastReturned = null; currentKey = null; advance(); } public boolean hasMoreElements() { return hasNext(); } final void advance() { if (nextEntry != null && (nextEntry = nextEntry.next) != null) { return; } while (nextTableIndex >= 0) { if ((nextEntry = currentTable[nextTableIndex --]) != null) { return; } } while (nextSegmentIndex >= 0) { Segment seg = segments[nextSegmentIndex --]; if (seg.count != 0) { currentTable = seg.table; for (int j = currentTable.length - 1; j >= 0; -- j) { if ((nextEntry = currentTable[j]) != null) { nextTableIndex = j - 1; return; } } } } } public boolean hasNext() { while (nextEntry != null) { if (nextEntry.key() != null) { return true; } advance(); } return false; } HashEntry nextEntry() { do { if (nextEntry == null) { throw new NoSuchElementException(); } lastReturned = nextEntry; currentKey = lastReturned.key(); advance(); } while (currentKey == null); // Skip GC'd keys return lastReturned; } public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } ConcurrentHashMap.this.remove(currentKey); lastReturned = null; } } final class KeyIterator extends HashIterator implements ReusableIterator, Enumeration { public K next() { return super.nextEntry().key(); } public K nextElement() { return super.nextEntry().key(); } } final class ValueIterator extends HashIterator implements ReusableIterator, Enumeration { public V next() { return super.nextEntry().value(); } public V nextElement() { return super.nextEntry().value(); } } /* * This class is needed for JDK5 compatibility. */ static class SimpleEntry implements Entry { private final K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } @SuppressWarnings("unchecked") Map.Entry e = (Map.Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } @Override public int hashCode() { return (key == null? 0 : key.hashCode()) ^ (value == null? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } private static boolean eq(Object o1, Object o2) { return o1 == null? o2 == null : o1.equals(o2); } } /** * Custom Entry class used by EntryIterator.next(), that relays setValue * changes to the underlying map. */ final class WriteThroughEntry extends SimpleEntry { WriteThroughEntry(K k, V v) { super(k, v); } /** * Set our entry's value and write through to the map. The value to * return is somewhat arbitrary here. Since a WriteThroughEntry does not * necessarily track asynchronous changes, the most recent "previous" * value could be different from what we return (or could even have been * removed in which case the put will re-establish). We do not and can * not guarantee more. */ @Override public V setValue(V value) { if (value == null) { throw new NullPointerException(); } V v = super.setValue(value); ConcurrentHashMap.this.put(getKey(), value); return v; } } final class EntryIterator extends HashIterator implements ReusableIterator> { public Map.Entry next() { HashEntry e = super.nextEntry(); return new WriteThroughEntry(e.key(), e.value()); } } final class KeySet extends AbstractSet { @Override public Iterator iterator() { return new KeyIterator(); } @Override public int size() { return ConcurrentHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentHashMap.this.containsKey(o); } @Override public boolean remove(Object o) { return ConcurrentHashMap.this.remove(o) != null; } @Override public void clear() { ConcurrentHashMap.this.clear(); } } final class Values extends AbstractCollection { @Override public Iterator iterator() { return new ValueIterator(); } @Override public int size() { return ConcurrentHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentHashMap.this.containsValue(o); } @Override public void clear() { ConcurrentHashMap.this.clear(); } } final class EntrySet extends AbstractSet> { @Override public Iterator> iterator() { return new EntryIterator(); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; V v = ConcurrentHashMap.this.get(e.getKey()); return v != null && v.equals(e.getValue()); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return ConcurrentHashMap.this.remove(e.getKey(), e.getValue()); } @Override public int size() { return ConcurrentHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentHashMap.this.isEmpty(); } @Override public void clear() { ConcurrentHashMap.this.clear(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/SystemPropertyUtil.java0000644000175000017500000000456311165336702032130 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; /** * Accesses the system property swallowing a {@link SecurityException}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class SystemPropertyUtil { /** * Returns the value of the Java system property with the specified * {@code key}. * * @return the property value. * {@code null} if there's no such property or if an access to the * specified property is not allowed. */ public static String get(String key) { try { return System.getProperty(key); } catch (Exception e) { return null; } } /** * Returns the value of the Java system property with the specified * {@code key}, while falling back to the specified default value if * the property access fails. * * @return the property value. * {@code def} if there's no such property or if an access to the * specified property is not allowed. */ public static String get(String key, String def) { String value = get(key); if (value == null) { value = def; } return value; } private SystemPropertyUtil() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ReusableIterator.java0000644000175000017500000000250611165336702031510 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.util.Iterator; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public interface ReusableIterator extends Iterator { void rewind(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ThreadLocalBoolean.java0000644000175000017500000000314011165336702031711 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public class ThreadLocalBoolean extends ThreadLocal { private final boolean defaultValue; public ThreadLocalBoolean() { this(false); } public ThreadLocalBoolean(boolean defaultValue) { this.defaultValue = defaultValue; } @Override protected Boolean initialValue() { return defaultValue? Boolean.TRUE : Boolean.FALSE; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/IoWorkerRunnable.java0000644000175000017500000000407111216750342031460 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import org.jboss.netty.channel.ChannelFuture; /** * @author Trustin Heui-seung Lee (trustin@gmail.com) * @version $Rev: 1483 $, $Date: 2009-06-19 10:54:42 -0700 (Fri, 19 Jun 2009) $ */ public class IoWorkerRunnable implements Runnable { /** * An internal use only thread-local variable that determines if * the caller is running on an I/O worker thread, which is the case where * the caller enters a dead lock if the caller calls * {@link ChannelFuture#await()} or {@link ChannelFuture#awaitUninterruptibly()}. */ public static final ThreadLocal IN_IO_THREAD = new ThreadLocalBoolean(); private final Runnable runnable; public IoWorkerRunnable(Runnable runnable) { if (runnable == null) { throw new NullPointerException("runnable"); } this.runnable = runnable; } public void run() { IN_IO_THREAD.set(Boolean.TRUE); try { runnable.run(); } finally { IN_IO_THREAD.remove(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/LinkedTransferQueue.java0000644000175000017500000006403111204743525032154 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.util.internal; import java.util.AbstractQueue; import java.util.Collection; import java.util.Iterator; import java.util.NoSuchElementException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicReference; import java.util.concurrent.atomic.AtomicReferenceFieldUpdater; import java.util.concurrent.locks.LockSupport; /** * An unbounded TransferQueue based on linked nodes. * This queue orders elements FIFO (first-in-first-out) with respect * to any given producer. The head of the queue is that * element that has been on the queue the longest time for some * producer. The tail of the queue is that element that has * been on the queue the shortest time for some producer. * *

Beware that, unlike in most collections, the size * method is NOT a constant-time operation. Because of the * asynchronous nature of these queues, determining the current number * of elements requires a traversal of the elements. * *

This class and its iterator implement all of the * optional methods of the {@link Collection} and {@link * Iterator} interfaces. * *

Memory consistency effects: As with other concurrent * collections, actions in a thread prior to placing an object into a * {@code LinkedTransferQueue} * happen-before * actions subsequent to the access or removal of that element from * the {@code LinkedTransferQueue} in another thread. * * @author Doug Lea * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @param the type of elements held in this collection * */ public class LinkedTransferQueue extends AbstractQueue implements BlockingQueue { /* * This class extends the approach used in FIFO-mode * SynchronousQueues. See the internal documentation, as well as * the PPoPP 2006 paper "Scalable Synchronous Queues" by Scherer, * Lea & Scott * (http://www.cs.rice.edu/~wns1/papers/2006-PPoPP-SQ.pdf) * * The main extension is to provide different Wait modes for the * main "xfer" method that puts or takes items. These don't * impact the basic dual-queue logic, but instead control whether * or how threads block upon insertion of request or data nodes * into the dual queue. It also uses slightly different * conventions for tracking whether nodes are off-list or * cancelled. */ // Wait modes for xfer method private static final int NOWAIT = 0; private static final int TIMEOUT = 1; private static final int WAIT = 2; /** The number of CPUs, for spin control */ private static final int NCPUS = Runtime.getRuntime().availableProcessors(); /** * The number of times to spin before blocking in timed waits. * The value is empirically derived -- it works well across a * variety of processors and OSes. Empirically, the best value * seems not to vary with number of CPUs (beyond 2) so is just * a constant. */ private static final int maxTimedSpins = NCPUS < 2? 0 : 32; /** * The number of times to spin before blocking in untimed waits. * This is greater than timed value because untimed waits spin * faster since they don't need to check times on each spin. */ private static final int maxUntimedSpins = maxTimedSpins * 16; /** * The number of nanoseconds for which it is faster to spin * rather than to use timed park. A rough estimate suffices. */ private static final long spinForTimeoutThreshold = 1000L; /** * Node class for LinkedTransferQueue. Opportunistically * subclasses from AtomicReference to represent item. Uses Object, * not E, to allow setting item to "this" after use, to avoid * garbage retention. Similarly, setting the next field to this is * used as sentinel that node is off list. */ private static final class QNode extends AtomicReference { private static final long serialVersionUID = 5925596372370723938L; transient volatile QNode next; transient volatile Thread waiter; // to control park/unpark final boolean isData; QNode(Object item, boolean isData) { super(item); this.isData = isData; } private static final AtomicReferenceFieldUpdater nextUpdater; static { AtomicReferenceFieldUpdater tmp = null; try { tmp = AtomicReferenceFieldUpdater.newUpdater( QNode.class, QNode.class, "next"); // Test if AtomicReferenceFieldUpdater is really working. QNode testNode = new QNode(null, false); tmp.set(testNode, testNode); if (testNode.next != testNode) { // Not set as expected - fall back to the safe mode. throw new Exception(); } } catch (Throwable t) { // Running in a restricted environment with a security manager. tmp = null; } nextUpdater = tmp; } boolean casNext(QNode cmp, QNode val) { if (nextUpdater != null) { return nextUpdater.compareAndSet(this, cmp, val); } else { return alternativeCasNext(cmp, val); } } private synchronized boolean alternativeCasNext(QNode cmp, QNode val) { if (next == cmp) { next = val; return true; } else { return false; } } } /** * Padded version of AtomicReference used for head, tail and * cleanMe, to alleviate contention across threads CASing one vs * the other. */ private static final class PaddedAtomicReference extends AtomicReference { private static final long serialVersionUID = 4684288940772921317L; // enough padding for 64bytes with 4byte refs @SuppressWarnings("unused") Object p0, p1, p2, p3, p4, p5, p6, p7, p8, p9, pa, pb, pc, pd, pe; PaddedAtomicReference(T r) { super(r); } } /** head of the queue */ private final PaddedAtomicReference head; /** tail of the queue */ private final PaddedAtomicReference tail; /** * Reference to a cancelled node that might not yet have been * unlinked from queue because it was the last inserted node * when it cancelled. */ private final PaddedAtomicReference cleanMe; /** * Tries to cas nh as new head; if successful, unlink * old head's next node to avoid garbage retention. */ private boolean advanceHead(QNode h, QNode nh) { if (h == head.get() && head.compareAndSet(h, nh)) { h.next = h; // forget old next return true; } return false; } /** * Puts or takes an item. Used for most queue operations (except * poll() and tryTransfer()). See the similar code in * SynchronousQueue for detailed explanation. * @param e the item or if null, signifies that this is a take * @param mode the wait mode: NOWAIT, TIMEOUT, WAIT * @param nanos timeout in nanosecs, used only if mode is TIMEOUT * @return an item, or null on failure */ private Object xfer(Object e, int mode, long nanos) { boolean isData = e != null; QNode s = null; final PaddedAtomicReference head = this.head; final PaddedAtomicReference tail = this.tail; for (;;) { QNode t = tail.get(); QNode h = head.get(); if (t != null && (t == h || t.isData == isData)) { if (s == null) { s = new QNode(e, isData); } QNode last = t.next; if (last != null) { if (t == tail.get()) { tail.compareAndSet(t, last); } } else if (t.casNext(null, s)) { tail.compareAndSet(t, s); return awaitFulfill(t, s, e, mode, nanos); } } else if (h != null) { QNode first = h.next; if (t == tail.get() && first != null && advanceHead(h, first)) { Object x = first.get(); if (x != first && first.compareAndSet(x, e)) { LockSupport.unpark(first.waiter); return isData? e : x; } } } } } /** * Version of xfer for poll() and tryTransfer, which * simplifies control paths both here and in xfer */ private Object fulfill(Object e) { boolean isData = e != null; final PaddedAtomicReference head = this.head; final PaddedAtomicReference tail = this.tail; for (;;) { QNode t = tail.get(); QNode h = head.get(); if (t != null && (t == h || t.isData == isData)) { QNode last = t.next; if (t == tail.get()) { if (last != null) { tail.compareAndSet(t, last); } else { return null; } } } else if (h != null) { QNode first = h.next; if (t == tail.get() && first != null && advanceHead(h, first)) { Object x = first.get(); if (x != first && first.compareAndSet(x, e)) { LockSupport.unpark(first.waiter); return isData? e : x; } } } } } /** * Spins/blocks until node s is fulfilled or caller gives up, * depending on wait mode. * * @param pred the predecessor of waiting node * @param s the waiting node * @param e the comparison value for checking match * @param mode mode * @param nanos timeout value * @return matched item, or s if cancelled */ private Object awaitFulfill(QNode pred, QNode s, Object e, int mode, long nanos) { if (mode == NOWAIT) { return null; } long lastTime = mode == TIMEOUT? System.nanoTime() : 0; Thread w = Thread.currentThread(); int spins = -1; // set to desired spin count below for (;;) { if (w.isInterrupted()) { s.compareAndSet(e, s); } Object x = s.get(); if (x != e) { // Node was matched or cancelled advanceHead(pred, s); // unlink if head if (x == s) { // was cancelled clean(pred, s); return null; } else if (x != null) { s.set(s); // avoid garbage retention return x; } else { return e; } } if (mode == TIMEOUT) { long now = System.nanoTime(); nanos -= now - lastTime; lastTime = now; if (nanos <= 0) { s.compareAndSet(e, s); // try to cancel continue; } } if (spins < 0) { QNode h = head.get(); // only spin if at head spins = h != null && h.next == s ? (mode == TIMEOUT? maxTimedSpins : maxUntimedSpins) : 0; } if (spins > 0) { --spins; } else if (s.waiter == null) { s.waiter = w; } else if (mode != TIMEOUT) { // LockSupport.park(this); LockSupport.park(); // allows run on java5 s.waiter = null; spins = -1; } else if (nanos > spinForTimeoutThreshold) { // LockSupport.parkNanos(this, nanos); LockSupport.parkNanos(nanos); s.waiter = null; spins = -1; } } } /** * Returns validated tail for use in cleaning methods */ private QNode getValidatedTail() { for (;;) { QNode h = head.get(); QNode first = h.next; if (first != null && first.next == first) { // help advance advanceHead(h, first); continue; } QNode t = tail.get(); QNode last = t.next; if (t == tail.get()) { if (last != null) { tail.compareAndSet(t, last); // help advance } else { return t; } } } } /** * Gets rid of cancelled node s with original predecessor pred. * @param pred predecessor of cancelled node * @param s the cancelled node */ void clean(QNode pred, QNode s) { Thread w = s.waiter; if (w != null) { // Wake up thread s.waiter = null; if (w != Thread.currentThread()) { LockSupport.unpark(w); } } /* * At any given time, exactly one node on list cannot be * deleted -- the last inserted node. To accommodate this, if * we cannot delete s, we save its predecessor as "cleanMe", * processing the previously saved version first. At least one * of node s or the node previously saved can always be * processed, so this always terminates. */ while (pred.next == s) { QNode oldpred = reclean(); // First, help get rid of cleanMe QNode t = getValidatedTail(); if (s != t) { // If not tail, try to unsplice QNode sn = s.next; // s.next == s means s already off list if (sn == s || pred.casNext(s, sn)) { break; } } else if (oldpred == pred || // Already saved oldpred == null && cleanMe.compareAndSet(null, pred)) { break; // Postpone cleaning } } } /** * Tries to unsplice the cancelled node held in cleanMe that was * previously uncleanable because it was at tail. * @return current cleanMe node (or null) */ private QNode reclean() { /* * cleanMe is, or at one time was, predecessor of cancelled * node s that was the tail so could not be unspliced. If s * is no longer the tail, try to unsplice if necessary and * make cleanMe slot available. This differs from similar * code in clean() because we must check that pred still * points to a cancelled node that must be unspliced -- if * not, we can (must) clear cleanMe without unsplicing. * This can loop only due to contention on casNext or * clearing cleanMe. */ QNode pred; while ((pred = cleanMe.get()) != null) { QNode t = getValidatedTail(); QNode s = pred.next; if (s != t) { QNode sn; if (s == null || s == pred || s.get() != s || (sn = s.next) == s || pred.casNext(s, sn)) { cleanMe.compareAndSet(pred, null); } } else { break; } } return pred; } @SuppressWarnings("unchecked") E cast(Object e) { return (E)e; } /** * Creates an initially empty LinkedTransferQueue. */ public LinkedTransferQueue() { QNode dummy = new QNode(null, false); head = new PaddedAtomicReference(dummy); tail = new PaddedAtomicReference(dummy); cleanMe = new PaddedAtomicReference(null); } /** * Creates a LinkedTransferQueue * initially containing the elements of the given collection, * added in traversal order of the collection's iterator. * @param c the collection of elements to initially contain * @throws NullPointerException if the specified collection or any * of its elements are null */ public LinkedTransferQueue(Collection c) { this(); addAll(c); } public void put(E e) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (Thread.interrupted()) { throw new InterruptedException(); } xfer(e, NOWAIT, 0); } public boolean offer(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (Thread.interrupted()) { throw new InterruptedException(); } xfer(e, NOWAIT, 0); return true; } public boolean offer(E e) { if (e == null) { throw new NullPointerException(); } xfer(e, NOWAIT, 0); return true; } public void transfer(E e) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (xfer(e, WAIT, 0) == null) { Thread.interrupted(); throw new InterruptedException(); } } public boolean tryTransfer(E e, long timeout, TimeUnit unit) throws InterruptedException { if (e == null) { throw new NullPointerException(); } if (xfer(e, TIMEOUT, unit.toNanos(timeout)) != null) { return true; } if (!Thread.interrupted()) { return false; } throw new InterruptedException(); } public boolean tryTransfer(E e) { if (e == null) { throw new NullPointerException(); } return fulfill(e) != null; } public E take() throws InterruptedException { Object e = xfer(null, WAIT, 0); if (e != null) { return cast(e); } Thread.interrupted(); throw new InterruptedException(); } public E poll(long timeout, TimeUnit unit) throws InterruptedException { Object e = xfer(null, TIMEOUT, unit.toNanos(timeout)); if (e != null || !Thread.interrupted()) { return cast(e); } throw new InterruptedException(); } public E poll() { return cast(fulfill(null)); } public int drainTo(Collection c) { if (c == null) { throw new NullPointerException(); } if (c == this) { throw new IllegalArgumentException(); } int n = 0; E e; while ( (e = poll()) != null) { c.add(e); ++n; } return n; } public int drainTo(Collection c, int maxElements) { if (c == null) { throw new NullPointerException(); } if (c == this) { throw new IllegalArgumentException(); } int n = 0; E e; while (n < maxElements && (e = poll()) != null) { c.add(e); ++n; } return n; } // Traversal-based methods /** * Return head after performing any outstanding helping steps */ QNode traversalHead() { for (;;) { QNode t = tail.get(); QNode h = head.get(); if (h != null && t != null) { QNode last = t.next; QNode first = h.next; if (t == tail.get()) { if (last != null) { tail.compareAndSet(t, last); } else if (first != null) { Object x = first.get(); if (x == first) { advanceHead(h, first); } else { return h; } } else { return h; } } } } } @Override public Iterator iterator() { return new Itr(); } /** * Iterators. Basic strategy is to traverse list, treating * non-data (i.e., request) nodes as terminating list. * Once a valid data node is found, the item is cached * so that the next call to next() will return it even * if subsequently removed. */ class Itr implements Iterator { QNode nextNode; // Next node to return next QNode currentNode; // last returned node, for remove() QNode prevNode; // predecessor of last returned node E nextItem; // Cache of next item, once commited to in next Itr() { nextNode = traversalHead(); advance(); } E advance() { prevNode = currentNode; currentNode = nextNode; E x = nextItem; QNode p = nextNode.next; for (;;) { if (p == null || !p.isData) { nextNode = null; nextItem = null; return x; } Object item = p.get(); if (item != p && item != null) { nextNode = p; nextItem = cast(item); return x; } prevNode = p; p = p.next; } } public boolean hasNext() { return nextNode != null; } public E next() { if (nextNode == null) { throw new NoSuchElementException(); } return advance(); } public void remove() { QNode p = currentNode; QNode prev = prevNode; if (prev == null || p == null) { throw new IllegalStateException(); } Object x = p.get(); if (x != null && x != p && p.compareAndSet(x, p)) { clean(prev, p); } } } public E peek() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return null; } Object x = p.get(); if (p != x) { if (!p.isData) { return null; } if (x != null) { return cast(x); } } } } @Override public boolean isEmpty() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return true; } Object x = p.get(); if (p != x) { if (!p.isData) { return true; } if (x != null) { return false; } } } } public boolean hasWaitingConsumer() { for (;;) { QNode h = traversalHead(); QNode p = h.next; if (p == null) { return false; } Object x = p.get(); if (p != x) { return !p.isData; } } } /** * Returns the number of elements in this queue. If this queue * contains more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * *

Beware that, unlike in most collections, this method is * NOT a constant-time operation. Because of the * asynchronous nature of these queues, determining the current * number of elements requires an O(n) traversal. * * @return the number of elements in this queue */ @Override public int size() { int count = 0; QNode h = traversalHead(); for (QNode p = h.next; p != null && p.isData; p = p.next) { Object x = p.get(); if (x != null && x != p) { if (++count == Integer.MAX_VALUE) { break; } } } return count; } public int getWaitingConsumerCount() { int count = 0; QNode h = traversalHead(); for (QNode p = h.next; p != null && !p.isData; p = p.next) { if (p.get() == null) { if (++count == Integer.MAX_VALUE) { break; } } } return count; } public int remainingCapacity() { return Integer.MAX_VALUE; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/package-info.java0000644000175000017500000000220111165336702030550 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Internal-use-only utilities which is not allowed to be used * outside Netty. */ package org.jboss.netty.util.internal;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/SwitchableInputStream.java0000644000175000017500000000345511165336702032521 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.io.FilterInputStream; import java.io.InputStream; /** * {@link FilterInputStream} which allows a user to change the underlying * stream at any time. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class SwitchableInputStream extends FilterInputStream { /** * Creates a new instance without initializing the reference to the * underlying stream. */ public SwitchableInputStream() { super(null); } /** * Creates a new instance with the initial reference to the underlying * stream. */ public void switchStream(InputStream in) { this.in = in; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/MapUtil.java0000644000175000017500000002261111165336702027606 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; /** * A set of utility methods related with a {@link Map}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public class MapUtil { /** * Returns {@code true} if and only if the specified {@code map} is an * ordered map, like {@link LinkedHashMap} is. */ @SuppressWarnings("unchecked") public static boolean isOrderedMap(Map map) { Class mapType = map.getClass(); if (LinkedHashMap.class.isAssignableFrom(mapType)) { // LinkedHashMap is an ordered map. return true; } // Not a LinkedHashMap - start autodetection. // Detect Apache Commons Collections OrderedMap implementations. Class type = mapType; while (type != null) { for (Class i: type.getInterfaces()) { if (i.getName().endsWith("OrderedMap")) { // Seems like it's an ordered map - guessed from that // it implements OrderedMap interface. return true; } } type = type.getSuperclass(); } // Does not implement OrderedMap interface. As a last resort, try to // create a new instance and test if the insertion order is maintained. Map newMap; try { newMap = (Map) mapType.newInstance(); } catch (Exception e) { // No default constructor - cannot proceed anymore. return false; } // Run some tests. List expectedKeys = new ArrayList(); String dummyValue = "dummyValue"; for (short element: ORDER_TEST_SAMPLES) { String key = String.valueOf(element); newMap.put(key, dummyValue); expectedKeys.add(key); Iterator it = expectedKeys.iterator(); for (Object actualKey: newMap.keySet()) { if (!it.next().equals(actualKey)) { // Did not pass the test. return false; } } } // The specified map passed the insertion order test. return true; } private MapUtil() { // Unused } private static final short[] ORDER_TEST_SAMPLES = { 682, 807, 637, 358, 570, 828, 407, 319, 105, 41, 563, 544, 518, 298, 418, 50, 156, 769, 984, 503, 191, 578, 309, 710, 327, 720, 591, 939, 374, 707, 43, 463, 227, 174, 30, 531, 135, 930, 190, 823, 925, 835, 328, 239, 415, 500, 144, 460, 83, 774, 921, 4, 95, 468, 687, 493, 991, 436, 245, 742, 149, 821, 142, 782, 297, 918, 917, 424, 978, 992, 79, 906, 535, 515, 850, 80, 125, 378, 307, 883, 836, 160, 27, 630, 668, 226, 560, 698, 467, 829, 476, 163, 977, 367, 325, 184, 204, 312, 486, 53, 179, 592, 252, 750, 893, 517, 937, 124, 148, 719, 973, 566, 405, 449, 452, 777, 349, 761, 167, 783, 220, 802, 117, 604, 216, 363, 120, 621, 219, 182, 817, 244, 438, 465, 934, 888, 628, 209, 631, 17, 870, 679, 826, 945, 680, 848, 974, 573, 626, 865, 109, 317, 91, 494, 965, 473, 725, 388, 302, 936, 660, 150, 122, 949, 295, 392, 63, 634, 772, 143, 990, 895, 538, 59, 541, 32, 669, 321, 811, 756, 82, 955, 953, 636, 390, 162, 688, 444, 70, 590, 183, 745, 543, 666, 951, 642, 747, 765, 98, 469, 884, 929, 178, 721, 994, 840, 353, 726, 940, 759, 624, 919, 667, 629, 272, 979, 326, 608, 453, 11, 322, 347, 647, 354, 381, 746, 472, 890, 249, 536, 733, 404, 170, 959, 34, 899, 195, 651, 140, 856, 201, 237, 51, 933, 268, 849, 294, 115, 157, 14, 854, 373, 186, 872, 71, 523, 931, 952, 655, 561, 607, 862, 554, 661, 313, 909, 511, 752, 986, 311, 287, 775, 505, 878, 422, 103, 299, 119, 107, 344, 487, 776, 445, 218, 549, 697, 454, 6, 462, 455, 52, 481, 594, 126, 112, 66, 877, 172, 153, 912, 834, 741, 610, 915, 964, 831, 575, 714, 250, 461, 814, 913, 369, 542, 882, 851, 427, 838, 867, 507, 434, 569, 20, 950, 792, 605, 798, 962, 923, 258, 972, 762, 809, 843, 674, 448, 280, 495, 285, 822, 283, 147, 451, 993, 794, 982, 748, 189, 274, 96, 73, 810, 401, 261, 277, 346, 527, 645, 601, 868, 248, 879, 371, 428, 559, 278, 265, 62, 225, 853, 483, 771, 9, 8, 339, 653, 263, 28, 477, 995, 208, 880, 292, 480, 516, 457, 286, 897, 21, 852, 971, 658, 623, 528, 316, 471, 860, 306, 638, 711, 875, 671, 108, 158, 646, 24, 257, 724, 193, 341, 902, 599, 565, 334, 506, 684, 960, 780, 429, 801, 910, 308, 383, 901, 489, 81, 512, 164, 755, 514, 723, 141, 296, 958, 686, 15, 799, 579, 598, 558, 414, 64, 420, 730, 256, 131, 45, 129, 259, 338, 999, 175, 740, 790, 324, 985, 896, 482, 841, 606, 377, 111, 372, 699, 988, 233, 243, 203, 781, 969, 903, 662, 632, 301, 44, 981, 36, 412, 946, 816, 284, 447, 214, 672, 758, 954, 804, 2, 928, 886, 421, 596, 574, 16, 892, 68, 546, 522, 490, 873, 656, 696, 864, 130, 40, 393, 926, 394, 932, 876, 664, 293, 154, 916, 55, 196, 842, 498, 177, 948, 540, 127, 271, 113, 844, 576, 132, 943, 12, 123, 291, 31, 212, 529, 547, 171, 582, 609, 793, 830, 221, 440, 568, 118, 406, 194, 827, 360, 622, 389, 800, 571, 213, 262, 403, 408, 881, 289, 635, 967, 432, 376, 649, 832, 857, 717, 145, 510, 159, 980, 683, 580, 484, 379, 246, 88, 567, 320, 643, 7, 924, 397, 10, 787, 845, 779, 670, 716, 19, 600, 382, 0, 210, 665, 228, 97, 266, 90, 304, 456, 180, 152, 425, 310, 768, 223, 702, 997, 577, 663, 290, 537, 416, 426, 914, 691, 23, 281, 497, 508, 48, 681, 581, 728, 99, 795, 530, 871, 957, 889, 206, 813, 839, 709, 805, 253, 151, 613, 65, 654, 93, 639, 784, 891, 352, 67, 430, 754, 76, 187, 443, 676, 362, 961, 874, 330, 331, 384, 85, 217, 855, 818, 738, 361, 314, 3, 615, 520, 355, 920, 689, 22, 188, 49, 904, 935, 136, 475, 693, 749, 519, 812, 100, 207, 963, 364, 464, 572, 731, 230, 833, 385, 499, 545, 273, 232, 398, 478, 975, 564, 399, 504, 35, 562, 938, 211, 26, 337, 54, 614, 586, 433, 450, 763, 238, 305, 941, 370, 885, 837, 234, 110, 137, 395, 368, 695, 342, 907, 396, 474, 176, 737, 796, 446, 37, 894, 727, 648, 431, 1, 366, 525, 553, 704, 329, 627, 479, 33, 492, 260, 241, 86, 185, 491, 966, 247, 13, 587, 602, 409, 335, 650, 235, 611, 470, 442, 597, 254, 343, 539, 146, 585, 593, 641, 770, 94, 976, 705, 181, 255, 315, 718, 526, 987, 692, 983, 595, 898, 282, 133, 439, 633, 534, 861, 269, 619, 677, 502, 375, 224, 806, 869, 417, 584, 612, 803, 58, 84, 788, 797, 38, 700, 751, 603, 652, 57, 240, 947, 350, 270, 333, 116, 736, 69, 74, 104, 767, 318, 735, 859, 357, 555, 411, 267, 712, 675, 532, 825, 496, 927, 942, 102, 46, 192, 114, 744, 138, 998, 72, 617, 134, 846, 166, 77, 900, 5, 303, 387, 400, 47, 729, 922, 222, 197, 351, 509, 524, 165, 485, 300, 944, 380, 625, 778, 685, 29, 589, 766, 161, 391, 423, 42, 734, 552, 215, 824, 908, 229, 89, 251, 199, 616, 78, 644, 242, 722, 25, 437, 732, 956, 275, 200, 970, 753, 791, 336, 556, 847, 703, 236, 715, 75, 863, 713, 785, 911, 786, 620, 551, 413, 39, 739, 820, 808, 764, 701, 819, 173, 989, 345, 690, 459, 60, 106, 887, 996, 365, 673, 968, 513, 18, 419, 550, 588, 435, 264, 789, 340, 659, 466, 356, 288, 56, 708, 557, 488, 760, 332, 402, 168, 202, 521, 757, 205, 706, 441, 773, 231, 583, 386, 678, 618, 815, 279, 87, 533, 61, 548, 92, 169, 694, 905, 198, 121, 410, 139, 657, 640, 743, 128, 458, 866, 501, 348, 155, 276, 101, 858, 323, 359, }; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConversionUtil.java0000644000175000017500000000472311165336702031222 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; /** * Conversion utility class to parse a property represented as a string or * an object. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class ConversionUtil { /** * Converts the specified object into an integer. */ public static int toInt(Object value) { if (value instanceof Number) { return ((Number) value).intValue(); } else { return Integer.parseInt(String.valueOf(value)); } } /** * Converts the specified object into a boolean. */ public static boolean toBoolean(Object value) { if (value instanceof Boolean) { return ((Boolean) value).booleanValue(); } if (value instanceof Number) { return ((Number) value).intValue() != 0; } else { String s = String.valueOf(value); if (s.length() == 0) { return false; } try { return Integer.parseInt(s) != 0; } catch (NumberFormatException e) { // Proceed } switch (Character.toUpperCase(s.charAt(0))) { case 'T': case 'Y': return true; } return false; } } private ConversionUtil() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/MapBackedSet.java0000644000175000017500000000437611165336702030526 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.io.Serializable; import java.util.AbstractSet; import java.util.Iterator; import java.util.Map; import java.util.Set; /** * A {@link Map}-backed {@link Set}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ */ public class MapBackedSet extends AbstractSet implements Serializable { private static final long serialVersionUID = -6761513279741915432L; private final Map map; /** * Creates a new instance which wraps the specified {@code map}. */ public MapBackedSet(Map map) { this.map = map; } @Override public int size() { return map.size(); } @Override public boolean contains(Object o) { return map.containsKey(o); } @Override public boolean add(E o) { return map.put(o, Boolean.TRUE) == null; } @Override public boolean remove(Object o) { return map.remove(o) != null; } @Override public void clear() { map.clear(); } @Override public Iterator iterator() { return map.keySet().iterator(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/StringUtil.java0000644000175000017500000000736211216366422030344 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; /** * String utility class. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1410 $, $Date: 2009-06-18 00:30:26 -0700 (Thu, 18 Jun 2009) $ */ public class StringUtil { private StringUtil() { // Unused. } /** * Strip an Object of it's ISO control characters. * * @param value * The Object that should be stripped. This objects toString method will * called and the result passed to {@link #stripControlCharacters(String)}. * @return {@code String} * A new String instance with its hexadecimal control characters replaced * by a space. Or the unmodified String if it does not contain any ISO * control characters. */ public static String stripControlCharacters(Object value) { if (value == null) { return null; } return stripControlCharacters(value.toString()); } /** * Strip a String of it's ISO control characters. * * @param value * The String that should be stripped. * @return {@code String} * A new String instance with its hexadecimal control characters replaced * by a space. Or the unmodified String if it does not contain any ISO * control characters. */ public static String stripControlCharacters(String value) { if (value == null) { return null; } boolean hasControlChars = false; for (int i = value.length() - 1; i >= 0; i --) { if (Character.isISOControl(value.charAt(i))) { hasControlChars = true; break; } } if (!hasControlChars) { return value; } StringBuilder buf = new StringBuilder(value.length()); int i = 0; // Skip initial control characters (i.e. left trim) for (; i < value.length(); i ++) { if (!Character.isISOControl(value.charAt(i))) { break; } } // Copy non control characters and substitute control characters with // a space. The last control characters are trimmed. boolean suppressingControlChars = false; for (; i < value.length(); i ++) { if (Character.isISOControl(value.charAt(i))) { suppressingControlChars = true; continue; } else { if (suppressingControlChars) { suppressingControlChars = false; buf.append(' '); } buf.append(value.charAt(i)); } } return buf.toString(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConcurrentIdentityWeakKeyHashMap.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ConcurrentIdentityWeakKeyHa0000644000175000017500000014603511213433461032702 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Doug Lea with assistance from members of JCP JSR-166 * Expert Group and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.util.internal; import java.lang.ref.Reference; import java.lang.ref.ReferenceQueue; import java.lang.ref.WeakReference; import java.util.AbstractCollection; import java.util.AbstractMap; import java.util.AbstractSet; import java.util.Collection; import java.util.ConcurrentModificationException; import java.util.Enumeration; import java.util.Hashtable; import java.util.Iterator; import java.util.Map; import java.util.NoSuchElementException; import java.util.Set; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.locks.ReentrantLock; /** * An alternative weak-key identity-comparing {@link ConcurrentMap} which is * similar to {@link java.util.concurrent.ConcurrentHashMap}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Doug Lea * @author Jason T. Greene * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1336 $, $Date: 2009-06-09 03:19:29 -0700 (Tue, 09 Jun 2009) $ * * @param the type of keys maintained by this map * @param the type of mapped values */ public final class ConcurrentIdentityWeakKeyHashMap extends AbstractMap implements ConcurrentMap { /* * The basic strategy is to subdivide the table among Segments, * each of which itself is a concurrently readable hash table. */ /** * The default initial capacity for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_INITIAL_CAPACITY = 16; /** * The default load factor for this table, used when not otherwise specified * in a constructor. */ static final float DEFAULT_LOAD_FACTOR = 0.75f; /** * The default concurrency level for this table, used when not otherwise * specified in a constructor. */ static final int DEFAULT_CONCURRENCY_LEVEL = 16; /** * The maximum capacity, used if a higher value is implicitly specified by * either of the constructors with arguments. MUST be a power of two * <= 1<<30 to ensure that entries are indexable using integers. */ static final int MAXIMUM_CAPACITY = 1 << 30; /** * The maximum number of segments to allow; used to bound constructor * arguments. */ static final int MAX_SEGMENTS = 1 << 16; // slightly conservative /** * Number of unsynchronized retries in size and containsValue methods before * resorting to locking. This is used to avoid unbounded retries if tables * undergo continuous modification which would make it impossible to obtain * an accurate result. */ static final int RETRIES_BEFORE_LOCK = 2; /* ---------------- Fields -------------- */ /** * Mask value for indexing into segments. The upper bits of a key's hash * code are used to choose the segment. */ final int segmentMask; /** * Shift value for indexing within segments. */ final int segmentShift; /** * The segments, each of which is a specialized hash table */ final Segment[] segments; Set keySet; Set> entrySet; Collection values; /* ---------------- Small Utilities -------------- */ /** * Applies a supplemental hash function to a given hashCode, which defends * against poor quality hash functions. This is critical because * ConcurrentReferenceHashMap uses power-of-two length hash tables, that * otherwise encounter collisions for hashCodes that do not differ in lower * or upper bits. */ private static int hash(int h) { // Spread bits to regularize both segment and index locations, // using variant of single-word Wang/Jenkins hash. h += h << 15 ^ 0xffffcd7d; h ^= h >>> 10; h += h << 3; h ^= h >>> 6; h += (h << 2) + (h << 14); return h ^ h >>> 16; } /** * Returns the segment that should be used for key with given hash. * * @param hash the hash code for the key * @return the segment */ final Segment segmentFor(int hash) { return segments[hash >>> segmentShift & segmentMask]; } private int hashOf(Object key) { return hash(System.identityHashCode(key)); } /* ---------------- Inner Classes -------------- */ /** * A weak-key reference which stores the key hash needed for reclamation. */ static final class WeakKeyReference extends WeakReference { final int hash; WeakKeyReference(K key, int hash, ReferenceQueue refQueue) { super(key, refQueue); this.hash = hash; } public final int keyHash() { return hash; } public final Object keyRef() { return this; } } /** * ConcurrentReferenceHashMap list entry. Note that this is never exported * out as a user-visible Map.Entry. * * Because the value field is volatile, not final, it is legal wrt * the Java Memory Model for an unsynchronized reader to see null * instead of initial value when read via a data race. Although a * reordering leading to this is not likely to ever actually * occur, the Segment.readValueUnderLock method is used as a * backup in case a null (pre-initialized) value is ever seen in * an unsynchronized access method. */ static final class HashEntry { final Object keyRef; final int hash; volatile Object valueRef; final HashEntry next; HashEntry( K key, int hash, HashEntry next, V value, ReferenceQueue refQueue) { this.hash = hash; this.next = next; this.keyRef = new WeakKeyReference(key, hash, refQueue); this.valueRef = value; } @SuppressWarnings("unchecked") final K key() { return ((WeakReference) keyRef).get(); } final V value() { return dereferenceValue(valueRef); } @SuppressWarnings("unchecked") final V dereferenceValue(Object value) { if (value instanceof WeakKeyReference) { return ((Reference) value).get(); } return (V) value; } final void setValue(V value) { this.valueRef = value; } @SuppressWarnings("unchecked") static final HashEntry[] newArray(int i) { return new HashEntry[i]; } } /** * Segments are specialized versions of hash tables. This subclasses from * ReentrantLock opportunistically, just to simplify some locking and avoid * separate construction. */ static final class Segment extends ReentrantLock { /* * Segments maintain a table of entry lists that are ALWAYS kept in a * consistent state, so can be read without locking. Next fields of * nodes are immutable (final). All list additions are performed at the * front of each bin. This makes it easy to check changes, and also fast * to traverse. When nodes would otherwise be changed, new nodes are * created to replace them. This works well for hash tables since the * bin lists tend to be short. (The average length is less than two for * the default load factor threshold.) * * Read operations can thus proceed without locking, but rely on * selected uses of volatiles to ensure that completed write operations * performed by other threads are noticed. For most purposes, the * "count" field, tracking the number of elements, serves as that * volatile variable ensuring visibility. This is convenient because * this field needs to be read in many read operations anyway: * * - All (unsynchronized) read operations must first read the * "count" field, and should not look at table entries if * it is 0. * * - All (synchronized) write operations should write to * the "count" field after structurally changing any bin. * The operations must not take any action that could even * momentarily cause a concurrent read operation to see * inconsistent data. This is made easier by the nature of * the read operations in Map. For example, no operation * can reveal that the table has grown but the threshold * has not yet been updated, so there are no atomicity * requirements for this with respect to reads. * * As a guide, all critical volatile reads and writes to the count field * are marked in code comments. */ private static final long serialVersionUID = 5571906852696599096L; /** * The number of elements in this segment's region. */ transient volatile int count; /** * Number of updates that alter the size of the table. This is used * during bulk-read methods to make sure they see a consistent snapshot: * If modCounts change during a traversal of segments computing size or * checking containsValue, then we might have an inconsistent view of * state so (usually) must retry. */ int modCount; /** * The table is rehashed when its size exceeds this threshold. * (The value of this field is always (capacity * loadFactor).) */ int threshold; /** * The per-segment table. */ transient volatile HashEntry[] table; /** * The load factor for the hash table. Even though this value is same * for all segments, it is replicated to avoid needing links to outer * object. * * @serial */ final float loadFactor; /** * The collected weak-key reference queue for this segment. This should * be (re)initialized whenever table is assigned, */ transient volatile ReferenceQueue refQueue; Segment(int initialCapacity, float lf) { loadFactor = lf; setTable(HashEntry. newArray(initialCapacity)); } @SuppressWarnings("unchecked") static final Segment[] newArray(int i) { return new Segment[i]; } private boolean keyEq(Object src, Object dest) { return src == dest; } /** * Sets table to new HashEntry array. Call only while holding lock or in * constructor. */ void setTable(HashEntry[] newTable) { threshold = (int) (newTable.length * loadFactor); table = newTable; refQueue = new ReferenceQueue(); } /** * Returns properly casted first entry of bin for given hash. */ HashEntry getFirst(int hash) { HashEntry[] tab = table; return tab[hash & tab.length - 1]; } HashEntry newHashEntry( K key, int hash, HashEntry next, V value) { return new HashEntry( key, hash, next, value, refQueue); } /** * Reads value field of an entry under lock. Called if value field ever * appears to be null. This is possible only if a compiler happens to * reorder a HashEntry initialization with its table assignment, which * is legal under memory model but is not known to ever occur. */ V readValueUnderLock(HashEntry e) { lock(); try { removeStale(); return e.value(); } finally { unlock(); } } /* Specialized implementations of map methods */ V get(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { Object opaque = e.valueRef; if (opaque != null) { return e.dereferenceValue(opaque); } return readValueUnderLock(e); // recheck } e = e.next; } } return null; } boolean containsKey(Object key, int hash) { if (count != 0) { // read-volatile HashEntry e = getFirst(hash); while (e != null) { if (e.hash == hash && keyEq(key, e.key())) { return true; } e = e.next; } } return false; } boolean containsValue(Object value) { if (count != 0) { // read-volatile HashEntry[] tab = table; int len = tab.length; for (int i = 0; i < len; i ++) { for (HashEntry e = tab[i]; e != null; e = e.next) { Object opaque = e.valueRef; V v; if (opaque == null) { v = readValueUnderLock(e); // recheck } else { v = e.dereferenceValue(opaque); } if (value.equals(v)) { return true; } } } } return false; } boolean replace(K key, int hash, V oldValue, V newValue) { lock(); try { removeStale(); HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } boolean replaced = false; if (e != null && oldValue.equals(e.value())) { replaced = true; e.setValue(newValue); } return replaced; } finally { unlock(); } } V replace(K key, int hash, V newValue) { lock(); try { removeStale(); HashEntry e = getFirst(hash); while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { oldValue = e.value(); e.setValue(newValue); } return oldValue; } finally { unlock(); } } V put(K key, int hash, V value, boolean onlyIfAbsent) { lock(); try { removeStale(); int c = count; if (c ++ > threshold) { // ensure capacity int reduced = rehash(); if (reduced > 0) { count = (c -= reduced) - 1; // write-volatile } } HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; while (e != null && (e.hash != hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue; if (e != null) { oldValue = e.value(); if (!onlyIfAbsent) { e.setValue(value); } } else { oldValue = null; ++ modCount; tab[index] = newHashEntry(key, hash, first, value); count = c; // write-volatile } return oldValue; } finally { unlock(); } } int rehash() { HashEntry[] oldTable = table; int oldCapacity = oldTable.length; if (oldCapacity >= MAXIMUM_CAPACITY) { return 0; } /* * Reclassify nodes in each list to new Map. Because we are using * power-of-two expansion, the elements from each bin must either * stay at same index, or move with a power of two offset. We * eliminate unnecessary node creation by catching cases where old * nodes can be reused because their next fields won't change. * Statistically, at the default threshold, only about one-sixth of * them need cloning when a table doubles. The nodes they replace * will be garbage collectable as soon as they are no longer * referenced by any reader thread that may be in the midst of * traversing table right now. */ HashEntry[] newTable = HashEntry.newArray(oldCapacity << 1); threshold = (int) (newTable.length * loadFactor); int sizeMask = newTable.length - 1; int reduce = 0; for (int i = 0; i < oldCapacity; i ++) { // We need to guarantee that any existing reads of old Map can // proceed. So we cannot yet null out each bin. HashEntry e = oldTable[i]; if (e != null) { HashEntry next = e.next; int idx = e.hash & sizeMask; // Single node on list if (next == null) { newTable[idx] = e; } else { // Reuse trailing consecutive sequence at same slot HashEntry lastRun = e; int lastIdx = idx; for (HashEntry last = next; last != null; last = last.next) { int k = last.hash & sizeMask; if (k != lastIdx) { lastIdx = k; lastRun = last; } } newTable[lastIdx] = lastRun; // Clone all remaining nodes for (HashEntry p = e; p != lastRun; p = p.next) { // Skip GC'd weak references K key = p.key(); if (key == null) { reduce ++; continue; } int k = p.hash & sizeMask; HashEntry n = newTable[k]; newTable[k] = newHashEntry(key, p.hash, n, p.value()); } } } } table = newTable; return reduce; } /** * Remove; match on key only if value null, else match both. */ V remove(Object key, int hash, Object value, boolean refRemove) { lock(); try { if (!refRemove) { removeStale(); } int c = count - 1; HashEntry[] tab = table; int index = hash & tab.length - 1; HashEntry first = tab[index]; HashEntry e = first; // a reference remove operation compares the Reference instance while (e != null && key != e.keyRef && (refRemove || hash != e.hash || !keyEq(key, e.key()))) { e = e.next; } V oldValue = null; if (e != null) { V v = e.value(); if (value == null || value.equals(v)) { oldValue = v; // All entries following removed node can stay in list, // but all preceding ones need to be cloned. ++ modCount; HashEntry newFirst = e.next; for (HashEntry p = first; p != e; p = p.next) { K pKey = p.key(); if (pKey == null) { // Skip GC'd keys c --; continue; } newFirst = newHashEntry( pKey, p.hash, newFirst, p.value()); } tab[index] = newFirst; count = c; // write-volatile } } return oldValue; } finally { unlock(); } } @SuppressWarnings("unchecked") final void removeStale() { WeakKeyReference ref; while ((ref = (WeakKeyReference) refQueue.poll()) != null) { remove(ref.keyRef(), ref.keyHash(), null, true); } } void clear() { if (count != 0) { lock(); try { HashEntry[] tab = table; for (int i = 0; i < tab.length; i ++) { tab[i] = null; } ++ modCount; // replace the reference queue to avoid unnecessary stale // cleanups refQueue = new ReferenceQueue(); count = 0; // write-volatile } finally { unlock(); } } } } /* ---------------- Public operations -------------- */ /** * Creates a new, empty map with the specified initial capacity, load factor * and concurrency level. * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @param concurrencyLevel the estimated number of concurrently updating * threads. The implementation performs internal * sizing to try to accommodate this many threads. * @throws IllegalArgumentException if the initial capacity is negative or * the load factor or concurrencyLevel are * nonpositive. */ public ConcurrentIdentityWeakKeyHashMap( int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0) || initialCapacity < 0 || concurrencyLevel <= 0) { throw new IllegalArgumentException(); } if (concurrencyLevel > MAX_SEGMENTS) { concurrencyLevel = MAX_SEGMENTS; } // Find power-of-two sizes best matching arguments int sshift = 0; int ssize = 1; while (ssize < concurrencyLevel) { ++ sshift; ssize <<= 1; } segmentShift = 32 - sshift; segmentMask = ssize - 1; this.segments = Segment.newArray(ssize); if (initialCapacity > MAXIMUM_CAPACITY) { initialCapacity = MAXIMUM_CAPACITY; } int c = initialCapacity / ssize; if (c * ssize < initialCapacity) { ++ c; } int cap = 1; while (cap < c) { cap <<= 1; } for (int i = 0; i < this.segments.length; ++ i) { this.segments[i] = new Segment(cap, loadFactor); } } /** * Creates a new, empty map with the specified initial capacity and load * factor and with the default reference types (weak keys, strong values), * and concurrencyLevel (16). * * @param initialCapacity The implementation performs internal sizing to * accommodate this many elements. * @param loadFactor the load factor threshold, used to control resizing. * Resizing may be performed when the average number of * elements per bin exceeds this threshold. * @throws IllegalArgumentException if the initial capacity of elements is * negative or the load factor is * nonpositive */ public ConcurrentIdentityWeakKeyHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with the specified initial capacity, and with * default reference types (weak keys, strong values), load factor (0.75) * and concurrencyLevel (16). * * @param initialCapacity the initial capacity. The implementation performs * internal sizing to accommodate this many elements. * @throws IllegalArgumentException if the initial capacity of elements is * negative. */ public ConcurrentIdentityWeakKeyHashMap(int initialCapacity) { this(initialCapacity, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new, empty map with a default initial capacity (16), reference * types (weak keys, strong values), default load factor (0.75) and * concurrencyLevel (16). */ public ConcurrentIdentityWeakKeyHashMap() { this(DEFAULT_INITIAL_CAPACITY, DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); } /** * Creates a new map with the same mappings as the given map. The map is * created with a capacity of 1.5 times the number of mappings in the given * map or 16 (whichever is greater), and a default load factor (0.75) and * concurrencyLevel (16). * * @param m the map */ public ConcurrentIdentityWeakKeyHashMap(Map m) { this(Math.max((int) (m.size() / DEFAULT_LOAD_FACTOR) + 1, DEFAULT_INITIAL_CAPACITY), DEFAULT_LOAD_FACTOR, DEFAULT_CONCURRENCY_LEVEL); putAll(m); } /** * Returns true if this map contains no key-value mappings. * * @return true if this map contains no key-value mappings */ @Override public boolean isEmpty() { final Segment[] segments = this.segments; /* * We keep track of per-segment modCounts to avoid ABA problems in which * an element in one segment was added and in another removed during * traversal, in which case the table was never actually empty at any * point. Note the similar use of modCounts in the size() and * containsValue() methods, which are the only other methods also * susceptible to ABA problems. */ int[] mc = new int[segments.length]; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0) { return false; } else { mcsum += mc[i] = segments[i].modCount; } } // If mcsum happens to be zero, then we know we got a snapshot before // any modifications at all were made. This is probably common enough // to bother tracking. if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (segments[i].count != 0 || mc[i] != segments[i].modCount) { return false; } } } return true; } /** * Returns the number of key-value mappings in this map. If the map contains * more than Integer.MAX_VALUE elements, returns * Integer.MAX_VALUE. * * @return the number of key-value mappings in this map */ @Override public int size() { final Segment[] segments = this.segments; long sum = 0; long check = 0; int[] mc = new int[segments.length]; // Try a few times to get accurate count. On failure due to continuous // async changes in table, resort to locking. for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { check = 0; sum = 0; int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; mcsum += mc[i] = segments[i].modCount; } if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { check += segments[i].count; if (mc[i] != segments[i].modCount) { check = -1; // force retry break; } } } if (check == sum) { break; } } if (check != sum) { // Resort to locking all segments sum = 0; for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } for (int i = 0; i < segments.length; ++ i) { sum += segments[i].count; } for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } if (sum > Integer.MAX_VALUE) { return Integer.MAX_VALUE; } else { return (int) sum; } } /** * Returns the value to which the specified key is mapped, or {@code null} * if this map contains no mapping for the key. * *

More formally, if this map contains a mapping from a key {@code k} to * a value {@code v} such that {@code key.equals(k)}, then this method * returns {@code v}; otherwise it returns {@code null}. (There can be at * most one such mapping.) * * @throws NullPointerException if the specified key is null */ @Override public V get(Object key) { int hash = hashOf(key); return segmentFor(hash).get(key, hash); } /** * Tests if the specified object is a key in this table. * * @param key possible key * @return true if and only if the specified object is a key in * this table, as determined by the equals method; * false otherwise. * @throws NullPointerException if the specified key is null */ @Override public boolean containsKey(Object key) { int hash = hashOf(key); return segmentFor(hash).containsKey(key, hash); } /** * Returns true if this map maps one or more keys to the specified * value. Note: This method requires a full internal traversal of the hash * table, and so is much slower than method containsKey. * * @param value value whose presence in this map is to be tested * @return true if this map maps one or more keys to the specified * value * @throws NullPointerException if the specified value is null */ @Override public boolean containsValue(Object value) { if (value == null) { throw new NullPointerException(); } // See explanation of modCount use above final Segment[] segments = this.segments; int[] mc = new int[segments.length]; // Try a few times without locking for (int k = 0; k < RETRIES_BEFORE_LOCK; ++ k) { int mcsum = 0; for (int i = 0; i < segments.length; ++ i) { mcsum += mc[i] = segments[i].modCount; if (segments[i].containsValue(value)) { return true; } } boolean cleanSweep = true; if (mcsum != 0) { for (int i = 0; i < segments.length; ++ i) { if (mc[i] != segments[i].modCount) { cleanSweep = false; break; } } } if (cleanSweep) { return false; } } // Resort to locking all segments for (int i = 0; i < segments.length; ++ i) { segments[i].lock(); } boolean found = false; try { for (int i = 0; i < segments.length; ++ i) { if (segments[i].containsValue(value)) { found = true; break; } } } finally { for (int i = 0; i < segments.length; ++ i) { segments[i].unlock(); } } return found; } /** * Legacy method testing if some key maps into the specified value in this * table. This method is identical in functionality to * {@link #containsValue}, and exists solely to ensure full compatibility * with class {@link Hashtable}, which supported this method prior to * introduction of the Java Collections framework. * * @param value a value to search for * @return true if and only if some key maps to the value * argument in this table as determined by the equals * method; false otherwise * @throws NullPointerException if the specified value is null */ public boolean contains(Object value) { return containsValue(value); } /** * Maps the specified key to the specified value in this table. Neither the * key nor the value can be null. * *

The value can be retrieved by calling the get method with a * key that is equal to the original key. * * @param key key with which the specified value is to be associated * @param value value to be associated with the specified key * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key or value is null */ @Override public V put(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, false); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V putIfAbsent(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).put(key, hash, value, true); } /** * Copies all of the mappings from the specified map to this one. These * mappings replace any mappings that this map had for any of the keys * currently in the specified map. * * @param m mappings to be stored in this map */ @Override public void putAll(Map m) { for (Map.Entry e: m.entrySet()) { put(e.getKey(), e.getValue()); } } /** * Removes the key (and its corresponding value) from this map. This method * does nothing if the key is not in the map. * * @param key the key that needs to be removed * @return the previous value associated with key, or null * if there was no mapping for key * @throws NullPointerException if the specified key is null */ @Override public V remove(Object key) { int hash = hashOf(key); return segmentFor(hash).remove(key, hash, null, false); } /** * {@inheritDoc} * * @throws NullPointerException if the specified key is null */ public boolean remove(Object key, Object value) { int hash = hashOf(key); if (value == null) { return false; } return segmentFor(hash).remove(key, hash, value, false) != null; } /** * {@inheritDoc} * * @throws NullPointerException if any of the arguments are null */ public boolean replace(K key, V oldValue, V newValue) { if (oldValue == null || newValue == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, oldValue, newValue); } /** * {@inheritDoc} * * @return the previous value associated with the specified key, or * null if there was no mapping for the key * @throws NullPointerException if the specified key or value is null */ public V replace(K key, V value) { if (value == null) { throw new NullPointerException(); } int hash = hashOf(key); return segmentFor(hash).replace(key, hash, value); } /** * Removes all of the mappings from this map. */ @Override public void clear() { for (int i = 0; i < segments.length; ++ i) { segments[i].clear(); } } /** * Removes any stale entries whose keys have been finalized. Use of this * method is normally not necessary since stale entries are automatically * removed lazily, when blocking operations are required. However, there are * some cases where this operation should be performed eagerly, such as * cleaning up old references to a ClassLoader in a multi-classloader * environment. * * Note: this method will acquire locks, one at a time, across all segments * of this table, so if it is to be used, it should be used sparingly. */ public void purgeStaleEntries() { for (int i = 0; i < segments.length; ++ i) { segments[i].removeStale(); } } /** * Returns a {@link Set} view of the keys contained in this map. The set is * backed by the map, so changes to the map are reflected in the set, and * vice-versa. The set supports element removal, which removes the * corresponding mapping from this map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set keySet() { Set ks = keySet; return ks != null? ks : (keySet = new KeySet()); } /** * Returns a {@link Collection} view of the values contained in this map. * The collection is backed by the map, so changes to the map are reflected * in the collection, and vice-versa. The collection supports element * removal, which removes the corresponding mapping from this map, via the * Iterator.remove, Collection.remove, removeAll, * retainAll, and clear operations. It does not support * the add or addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Collection values() { Collection vs = values; return vs != null? vs : (values = new Values()); } /** * Returns a {@link Set} view of the mappings contained in this map. * The set is backed by the map, so changes to the map are reflected in the * set, and vice-versa. The set supports element removal, which removes the * corresponding mapping from the map, via the Iterator.remove, * Set.remove, removeAll, retainAll, and * clear operations. It does not support the add or * addAll operations. * *

The view's iterator is a "weakly consistent" iterator that * will never throw {@link ConcurrentModificationException}, and guarantees * to traverse elements as they existed upon construction of the iterator, * and may (but is not guaranteed to) reflect any modifications subsequent * to construction. */ @Override public Set> entrySet() { Set> es = entrySet; return es != null? es : (entrySet = new EntrySet()); } /** * Returns an enumeration of the keys in this table. * * @return an enumeration of the keys in this table * @see #keySet() */ public Enumeration keys() { return new KeyIterator(); } /** * Returns an enumeration of the values in this table. * * @return an enumeration of the values in this table * @see #values() */ public Enumeration elements() { return new ValueIterator(); } /* ---------------- Iterator Support -------------- */ abstract class HashIterator { int nextSegmentIndex; int nextTableIndex; HashEntry[] currentTable; HashEntry nextEntry; HashEntry lastReturned; K currentKey; // Strong reference to weak key (prevents gc) HashIterator() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; advance(); } public void rewind() { nextSegmentIndex = segments.length - 1; nextTableIndex = -1; currentTable = null; nextEntry = null; lastReturned = null; currentKey = null; advance(); } public boolean hasMoreElements() { return hasNext(); } final void advance() { if (nextEntry != null && (nextEntry = nextEntry.next) != null) { return; } while (nextTableIndex >= 0) { if ((nextEntry = currentTable[nextTableIndex --]) != null) { return; } } while (nextSegmentIndex >= 0) { Segment seg = segments[nextSegmentIndex --]; if (seg.count != 0) { currentTable = seg.table; for (int j = currentTable.length - 1; j >= 0; -- j) { if ((nextEntry = currentTable[j]) != null) { nextTableIndex = j - 1; return; } } } } } public boolean hasNext() { while (nextEntry != null) { if (nextEntry.key() != null) { return true; } advance(); } return false; } HashEntry nextEntry() { do { if (nextEntry == null) { throw new NoSuchElementException(); } lastReturned = nextEntry; currentKey = lastReturned.key(); advance(); } while (currentKey == null); // Skip GC'd keys return lastReturned; } public void remove() { if (lastReturned == null) { throw new IllegalStateException(); } ConcurrentIdentityWeakKeyHashMap.this.remove(currentKey); lastReturned = null; } } final class KeyIterator extends HashIterator implements ReusableIterator, Enumeration { public K next() { return super.nextEntry().key(); } public K nextElement() { return super.nextEntry().key(); } } final class ValueIterator extends HashIterator implements ReusableIterator, Enumeration { public V next() { return super.nextEntry().value(); } public V nextElement() { return super.nextEntry().value(); } } /* * This class is needed for JDK5 compatibility. */ static class SimpleEntry implements Entry { private final K key; private V value; public SimpleEntry(K key, V value) { this.key = key; this.value = value; } public SimpleEntry(Entry entry) { this.key = entry.getKey(); this.value = entry.getValue(); } public K getKey() { return key; } public V getValue() { return value; } public V setValue(V value) { V oldValue = this.value; this.value = value; return oldValue; } @Override public boolean equals(Object o) { if (!(o instanceof Map.Entry)) { return false; } @SuppressWarnings("unchecked") Map.Entry e = (Map.Entry) o; return eq(key, e.getKey()) && eq(value, e.getValue()); } @Override public int hashCode() { return (key == null? 0 : key.hashCode()) ^ (value == null? 0 : value.hashCode()); } @Override public String toString() { return key + "=" + value; } private static boolean eq(Object o1, Object o2) { return o1 == null? o2 == null : o1.equals(o2); } } /** * Custom Entry class used by EntryIterator.next(), that relays setValue * changes to the underlying map. */ final class WriteThroughEntry extends SimpleEntry { WriteThroughEntry(K k, V v) { super(k, v); } /** * Set our entry's value and write through to the map. The value to * return is somewhat arbitrary here. Since a WriteThroughEntry does not * necessarily track asynchronous changes, the most recent "previous" * value could be different from what we return (or could even have been * removed in which case the put will re-establish). We do not and can * not guarantee more. */ @Override public V setValue(V value) { if (value == null) { throw new NullPointerException(); } V v = super.setValue(value); ConcurrentIdentityWeakKeyHashMap.this.put(getKey(), value); return v; } } final class EntryIterator extends HashIterator implements ReusableIterator> { public Map.Entry next() { HashEntry e = super.nextEntry(); return new WriteThroughEntry(e.key(), e.value()); } } final class KeySet extends AbstractSet { @Override public Iterator iterator() { return new KeyIterator(); } @Override public int size() { return ConcurrentIdentityWeakKeyHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentIdentityWeakKeyHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentIdentityWeakKeyHashMap.this.containsKey(o); } @Override public boolean remove(Object o) { return ConcurrentIdentityWeakKeyHashMap.this.remove(o) != null; } @Override public void clear() { ConcurrentIdentityWeakKeyHashMap.this.clear(); } } final class Values extends AbstractCollection { @Override public Iterator iterator() { return new ValueIterator(); } @Override public int size() { return ConcurrentIdentityWeakKeyHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentIdentityWeakKeyHashMap.this.isEmpty(); } @Override public boolean contains(Object o) { return ConcurrentIdentityWeakKeyHashMap.this.containsValue(o); } @Override public void clear() { ConcurrentIdentityWeakKeyHashMap.this.clear(); } } final class EntrySet extends AbstractSet> { @Override public Iterator> iterator() { return new EntryIterator(); } @Override public boolean contains(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; V v = ConcurrentIdentityWeakKeyHashMap.this.get(e.getKey()); return v != null && v.equals(e.getValue()); } @Override public boolean remove(Object o) { if (!(o instanceof Map.Entry)) { return false; } Map.Entry e = (Map.Entry) o; return ConcurrentIdentityWeakKeyHashMap.this.remove(e.getKey(), e.getValue()); } @Override public int size() { return ConcurrentIdentityWeakKeyHashMap.this.size(); } @Override public boolean isEmpty() { return ConcurrentIdentityWeakKeyHashMap.this.isEmpty(); } @Override public void clear() { ConcurrentIdentityWeakKeyHashMap.this.clear(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/internal/ImmediateExecutor.java0000644000175000017500000000311411165336702031645 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util.internal; import java.util.concurrent.Executor; /** * {@link Executor} which executes the command in the caller thread. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * */ public class ImmediateExecutor implements Executor { /** * The default instance. */ public static final ImmediateExecutor INSTANCE = new ImmediateExecutor(); public void execute(Runnable command) { command.run(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/Timer.java0000644000175000017500000000407011216107460025470 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import java.util.Set; import java.util.concurrent.TimeUnit; /** * Schedules {@link TimerTask}s for one-time future execution in a background * thread. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1397 $, $Date: 2009-06-16 23:37:36 -0700 (Tue, 16 Jun 2009) $ */ public interface Timer { /** * Schedules the specified {@link TimerTask} for one-time execution after * the specified delay. * * @return a handle which is associated with the specified task * * @throws IllegalStateException if this timer has been * {@linkplain #stop() stopped} already */ Timeout newTimeout(TimerTask task, long delay, TimeUnit unit); /** * Releases all resources acquired by this {@link Timer} and cancels all * tasks which were scheduled but not executed yet. * * @return the handles associated with the tasks which were canceled by * this method */ Set stop(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/EstimatableObjectWrapper.java0000644000175000017500000000315111216723540031334 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; /** * Represents an object which contains another object that needs to be taken * into account by {@link ObjectSizeEstimator} for more accurate object size * estimation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1471 $, $Date: 2009-06-19 07:57:36 -0700 (Fri, 19 Jun 2009) $ */ public interface EstimatableObjectWrapper { /** * Returns the underlying object that needs to be taken into account * by {@link ObjectSizeEstimator} for more accurate object size estimation. */ Object unwrap(); }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/Timeout.java0000644000175000017500000000406111216107460026036 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; /** * A handle associated with a {@link TimerTask} that is returned by a * {@link Timer}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1397 $, $Date: 2009-06-16 23:37:36 -0700 (Tue, 16 Jun 2009) $ */ public interface Timeout { /** * Returns the {@link Timer} that created this handle. */ Timer getTimer(); /** * Returns the {@link TimerTask} which is associated with this handle. */ TimerTask getTask(); /** * Returns {@code true} if and only if the {@link TimerTask} associated * with this handle has been expired. */ boolean isExpired(); /** * Returns {@code true} if and only if the {@link TimerTask} associated * with this handle has been cancelled. */ boolean isCancelled(); /** * Cancels the {@link TimerTask} associated with this handle. It the * task has been executed or cancelled already, it will return with no * side effect. */ void cancel(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/VirtualExecutorService.java0000644000175000017500000001466611211425307031110 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import java.util.Collections; import java.util.IdentityHashMap; import java.util.List; import java.util.Set; import java.util.concurrent.AbstractExecutorService; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.TimeUnit; import org.jboss.netty.util.internal.MapBackedSet; /** * A delegating {@link ExecutorService} with its own termination management. *

* {@link VirtualExecutorService} is used when you want to inject an * {@link ExecutorService} but you do not want to allow the explicit termination * of threads on shutdown request. It is particularly useful when the * {@link ExecutorService} to inject is shared by different components and * the life cycle of the components depend on the termination of the injected * {@link ExecutorService}. * *

 * ExecutorService globalExecutor = ...;
 * ExecutorService virtualExecutor = new VirtualExecutorService(globalExecutor);
 *
 * ChannelFactory factory =
 *         new NioServerSocketChannelFactory(virtualExecutor, virtualExecutor);
 * ...
 *
 * // ChannelFactory.releaseExternalResources() shuts down the executor and
 * // interrupts the I/O threads to terminate all I/O tasks and to release all
 * // resources acquired by ChannelFactory.
 * factory.releaseExternalResources();
 *
 * // Note that globalExecutor is not shut down because VirtualExecutorService
 * // implements its own termination management. All threads which were acquired
 * // by ChannelFactory via VirtualExecutorService are returned to the pool.
 * assert !globalExecutor.isShutdown();
 * 
* *

The differences from an ordinary {@link ExecutorService}

* * A shutdown request ({@link #shutdown()} or {@link #shutdownNow()}) does not * shut down its parent {@link Executor} but simply sets its internal flag to * reject further execution request. *

* {@link #shutdownNow()} interrupts only the thread which is executing the * task executed via {@link VirtualExecutorService}. *

* {@link #awaitTermination(long, TimeUnit)} does not wait for real thread * termination but wait until {@link VirtualExecutorService} is shut down and * its active tasks are finished and the threads are returned to the parent * {@link Executor}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1315 $, $Date: 2009-06-03 00:48:23 -0700 (Wed, 03 Jun 2009) $ */ public class VirtualExecutorService extends AbstractExecutorService { private final Executor e; private final ExecutorService s; final Object startStopLock = new Object(); volatile boolean shutdown; Set activeThreads = new MapBackedSet(new IdentityHashMap()); /** * Creates a new instance with the specified parent {@link Executor}. */ public VirtualExecutorService(Executor parent) { if (parent == null) { throw new NullPointerException("parent"); } if (parent instanceof ExecutorService) { e = null; s = (ExecutorService) parent; } else { e = parent; s = null; } } public boolean isShutdown() { synchronized (startStopLock) { return shutdown; } } public boolean isTerminated() { synchronized (startStopLock) { return shutdown && activeThreads.isEmpty(); } } public void shutdown() { synchronized (startStopLock) { if (shutdown) { return; } shutdown = true; } } public List shutdownNow() { synchronized (startStopLock) { if (!isTerminated()) { shutdown(); for (Thread t: activeThreads) { t.interrupt(); } } } return Collections.emptyList(); } public boolean awaitTermination(long timeout, TimeUnit unit) throws InterruptedException { synchronized (startStopLock) { while (!isTerminated()) { startStopLock.wait(TimeUnit.MILLISECONDS.convert(timeout, unit)); } return isTerminated(); } } public void execute(Runnable command) { if (command == null) { throw new NullPointerException("command"); } if (shutdown) { throw new RejectedExecutionException(); } if (s != null) { s.execute(new ChildExecutorRunnable(command)); } else { e.execute(new ChildExecutorRunnable(command)); } } private class ChildExecutorRunnable implements Runnable { private final Runnable runnable; ChildExecutorRunnable(Runnable runnable) { this.runnable = runnable; } public void run() { Thread thread = Thread.currentThread(); synchronized (startStopLock) { activeThreads.add(thread); } try { runnable.run(); } finally { synchronized (startStopLock) { boolean removed = activeThreads.remove(thread); assert removed; if (isTerminated()) { startStopLock.notifyAll(); } } } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/ExternalResourceReleasable.java0000644000175000017500000000315011216073761031666 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; /** * A common interface for a class which depends on external resources that * need explicit release or shutdown. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1390 $, $Date: 2009-06-16 21:58:25 -0700 (Tue, 16 Jun 2009) $ */ public interface ExternalResourceReleasable { /** * Releases the external resources that this object depends on. You should * not call this method if the external resources (e.g. thread pool) are * in use by other objects. */ void releaseExternalResources(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/ExternalResourceUtil.java0000644000175000017500000000404111216100607030532 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; /** * A utility class that provides the convenient shutdown of * {@link ExternalResourceReleasable}s. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1396 $, $Date: 2009-06-16 22:39:19 -0700 (Tue, 16 Jun 2009) $ */ public class ExternalResourceUtil { /** * Releases the specified {@link ExternalResourceReleasable}s. */ public static void release(ExternalResourceReleasable... releasables) { ExternalResourceReleasable[] releasablesCopy = new ExternalResourceReleasable[releasables.length]; for (int i = 0; i < releasables.length; i ++) { if (releasables[i] == null) { throw new NullPointerException("releasables[" + i + "]"); } releasablesCopy[i] = releasables[i]; } for (ExternalResourceReleasable e: releasablesCopy) { e.releaseExternalResources(); } } private ExternalResourceUtil() { super(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/DebugUtil.java0000644000175000017500000000503411216077425026304 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.util.internal.SystemPropertyUtil; /** * Determines if Netty is running in a debug mode or not. Please note that * this is not a Java debug mode. You can enable Netty debug mode by * specifying the {@code "org.jboss.netty.debug"} system property (e.g. * {@code java -Dorg.jboss.netty.debug ...}) *

* If debug mode is disabled (default), the stack trace of the exceptions are * compressed to help debugging a user application. *

* If debug mode is enabled, the stack trace of the exceptions raised in * {@link ChannelPipeline} or {@link ChannelSink} are retained as it is to help * debugging Netty. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1395 $, $Date: 2009-06-16 22:28:53 -0700 (Tue, 16 Jun 2009) $ */ public class DebugUtil { /** * Returns {@code true} if and only if Netty debug mode is enabled. */ public static boolean isDebugEnabled() { String value; try { value = SystemPropertyUtil.get("org.jboss.netty.debug"); } catch (Exception e) { value = null; } if (value == null) { return false; } value = value.trim().toUpperCase(); return !value.startsWith("N") && !value.startsWith("F") && !value.equals("0"); } private DebugUtil() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/ThreadNameDeterminer.java0000644000175000017500000000345111216100607030435 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; /** * Overrides the thread name proposed by {@link ThreadRenamingRunnable}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1396 $, $Date: 2009-06-16 22:39:19 -0700 (Tue, 16 Jun 2009) $ */ public interface ThreadNameDeterminer { /** * Overrides the thread name proposed by {@link ThreadRenamingRunnable}. * * @param currentThreadName the current thread name * @param proposedThreadName the proposed new thread name * @return the actual new thread name. * If {@code null} is returned, the proposed thread name is * discarded (i.e. no rename). */ String determineThreadName(String currentThreadName, String proposedThreadName) throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/HashedWheelTimer.java0000644000175000017500000004555711216107460027611 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import java.util.ArrayList; import java.util.Collections; import java.util.HashSet; import java.util.List; import java.util.Set; import java.util.concurrent.Executors; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.locks.ReadWriteLock; import java.util.concurrent.locks.ReentrantReadWriteLock; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.ConcurrentIdentityHashMap; import org.jboss.netty.util.internal.MapBackedSet; import org.jboss.netty.util.internal.ReusableIterator; /** * A {@link Timer} optimized for approximated I/O timeout scheduling. * *

Tick Duration

* * As described with 'approximated', this timer does not execute the scheduled * {@link TimerTask} on time. {@link HashedWheelTimer}, on every tick, will * check if there are any {@link TimerTask}s behind the schedule and execute * them. *

* You can increase or decrease the accuracy of the execution timing by * specifying smaller or larger tick duration in the constructor. In most * network applications, I/O timeout does not need to be accurate. Therefore, * the default tick duration is 100 milliseconds and you will not need to try * different configurations in most cases. * *

Ticks per Wheel (Wheel Size)

* * {@link HashedWheelTimer} maintains a data structure called 'wheel'. * To put simply, a wheel is a hash table of {@link TimerTask}s whose hash * function is 'dead line of the task'. The default number of ticks per wheel * (i.e. the size of the wheel) is 512. You could specify a larger value * if you are going to schedule a lot of timeouts. * *

Implementation Details

* * {@link HashedWheelTimer} is based on * 'Hashed * and Hierarchical Timing Wheels: data structures to efficiently implement a * timer facility'. More comprehensive slides are located * here. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1397 $, $Date: 2009-06-16 23:37:36 -0700 (Tue, 16 Jun 2009) $ */ public class HashedWheelTimer implements Timer { static final InternalLogger logger = InternalLoggerFactory.getInstance(HashedWheelTimer.class); private static final AtomicInteger id = new AtomicInteger(); // I'd say 64 active timer threads are obvious misuse. private static final int MISUSE_WARNING_THRESHOLD = 64; private static final AtomicInteger activeInstances = new AtomicInteger(); private static final AtomicBoolean loggedMisuseWarning = new AtomicBoolean(); private final Worker worker = new Worker(); final Thread workerThread; final AtomicBoolean shutdown = new AtomicBoolean(); private final long roundDuration; final long tickDuration; final Set[] wheel; final ReusableIterator[] iterators; final int mask; final ReadWriteLock lock = new ReentrantReadWriteLock(); volatile int wheelCursor; /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}), default tick duration, and * default number of ticks per wheel. */ public HashedWheelTimer() { this(Executors.defaultThreadFactory()); } /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}) and default number of ticks * per wheel. * * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} */ public HashedWheelTimer(long tickDuration, TimeUnit unit) { this(Executors.defaultThreadFactory(), tickDuration, unit); } /** * Creates a new timer with the default thread factory * ({@link Executors#defaultThreadFactory()}). * * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel */ public HashedWheelTimer(long tickDuration, TimeUnit unit, int ticksPerWheel) { this(Executors.defaultThreadFactory(), tickDuration, unit, ticksPerWheel); } /** * Creates a new timer with the default tick duration and default number of * ticks per wheel. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. */ public HashedWheelTimer(ThreadFactory threadFactory) { this(threadFactory, 100, TimeUnit.MILLISECONDS); } /** * Creates a new timer with the default number of ticks per wheel. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit) { this(threadFactory, tickDuration, unit, 512); } /** * Creates a new timer. * * @param threadFactory a {@link ThreadFactory} that creates a * background {@link Thread} which is dedicated to * {@link TimerTask} execution. * @param tickDuration the duration between tick * @param unit the time unit of the {@code tickDuration} * @param ticksPerWheel the size of the wheel */ public HashedWheelTimer( ThreadFactory threadFactory, long tickDuration, TimeUnit unit, int ticksPerWheel) { if (threadFactory == null) { throw new NullPointerException("threadFactory"); } if (unit == null) { throw new NullPointerException("unit"); } if (tickDuration <= 0) { throw new IllegalArgumentException( "tickDuration must be greater than 0: " + tickDuration); } if (ticksPerWheel <= 0) { throw new IllegalArgumentException( "ticksPerWheel must be greater than 0: " + ticksPerWheel); } // Normalize ticksPerWheel to power of two and initialize the wheel. wheel = createWheel(ticksPerWheel); iterators = createIterators(wheel); mask = wheel.length - 1; // Convert tickDuration to milliseconds. this.tickDuration = tickDuration = unit.toMillis(tickDuration); // Prevent overflow. if (tickDuration == Long.MAX_VALUE || tickDuration >= Long.MAX_VALUE / wheel.length) { throw new IllegalArgumentException( "tickDuration is too long: " + tickDuration + ' ' + unit); } roundDuration = tickDuration * wheel.length; workerThread = threadFactory.newThread(new ThreadRenamingRunnable( worker, "Hashed wheel timer #" + id.incrementAndGet())); // Misuse check int activeInstances = HashedWheelTimer.activeInstances.incrementAndGet(); if (activeInstances >= MISUSE_WARNING_THRESHOLD && loggedMisuseWarning.compareAndSet(false, true)) { logger.debug( "There are too many active " + HashedWheelTimer.class.getSimpleName() + " instances (" + activeInstances + ") - you should share the small number " + "of instances to avoid excessive resource consumption."); } } @SuppressWarnings("unchecked") private static Set[] createWheel(int ticksPerWheel) { if (ticksPerWheel <= 0) { throw new IllegalArgumentException( "ticksPerWheel must be greater than 0: " + ticksPerWheel); } if (ticksPerWheel > 1073741824) { throw new IllegalArgumentException( "ticksPerWheel may not be greater than 2^30: " + ticksPerWheel); } ticksPerWheel = normalizeTicksPerWheel(ticksPerWheel); Set[] wheel = new Set[ticksPerWheel]; for (int i = 0; i < wheel.length; i ++) { wheel[i] = new MapBackedSet( new ConcurrentIdentityHashMap(16, 0.95f, 4)); } return wheel; } @SuppressWarnings("unchecked") private static ReusableIterator[] createIterators(Set[] wheel) { ReusableIterator[] iterators = new ReusableIterator[wheel.length]; for (int i = 0; i < wheel.length; i ++) { iterators[i] = (ReusableIterator) wheel[i].iterator(); } return iterators; } private static int normalizeTicksPerWheel(int ticksPerWheel) { int normalizedTicksPerWheel = 1; while (normalizedTicksPerWheel < ticksPerWheel) { normalizedTicksPerWheel <<= 1; } return normalizedTicksPerWheel; } /** * Starts the background thread explicitly. The background thread will * start automatically on demand even if you did not call this method. * * @throws IllegalStateException if this timer has been * {@linkplain #stop() stopped} already */ public synchronized void start() { if (shutdown.get()) { throw new IllegalStateException("cannot be started once stopped"); } if (!workerThread.isAlive()) { workerThread.start(); } } public synchronized Set stop() { if (!shutdown.compareAndSet(false, true)) { return Collections.emptySet(); } while (workerThread.isAlive()) { workerThread.interrupt(); try { workerThread.join(100); } catch (InterruptedException e) { // Ignore } } activeInstances.decrementAndGet(); Set unprocessedTimeouts = new HashSet(); for (Set bucket: wheel) { unprocessedTimeouts.addAll(bucket); bucket.clear(); } return Collections.unmodifiableSet(unprocessedTimeouts); } public Timeout newTimeout(TimerTask task, long delay, TimeUnit unit) { final long currentTime = System.currentTimeMillis(); if (task == null) { throw new NullPointerException("task"); } if (unit == null) { throw new NullPointerException("unit"); } delay = unit.toMillis(delay); if (delay < tickDuration) { delay = tickDuration; } if (!workerThread.isAlive()) { start(); } // Prepare the required parameters to create the timeout object. HashedWheelTimeout timeout; final long lastRoundDelay = delay % roundDuration; final long lastTickDelay = delay % tickDuration; final long relativeIndex = lastRoundDelay / tickDuration + (lastTickDelay != 0? 1 : 0); final long deadline = currentTime + delay; final long remainingRounds = delay / roundDuration - (delay % roundDuration == 0? 1 : 0); // Add the timeout to the wheel. lock.readLock().lock(); try { timeout = new HashedWheelTimeout( task, deadline, (int) (wheelCursor + relativeIndex & mask), remainingRounds); wheel[timeout.stopIndex].add(timeout); } finally { lock.readLock().unlock(); } return timeout; } private final class Worker implements Runnable { private long startTime; private long tick; Worker() { super(); } public void run() { List expiredTimeouts = new ArrayList(); startTime = System.currentTimeMillis(); tick = 1; while (!shutdown.get()) { waitForNextTick(); fetchExpiredTimeouts(expiredTimeouts); notifyExpiredTimeouts(expiredTimeouts); } } private void fetchExpiredTimeouts( List expiredTimeouts) { // Find the expired timeouts and decrease the round counter // if necessary. Note that we don't send the notification // immediately to make sure the listeners are called without // an exclusive lock. lock.writeLock().lock(); try { int oldBucketHead = wheelCursor; int newBucketHead = oldBucketHead + 1 & mask; wheelCursor = newBucketHead; ReusableIterator i = iterators[oldBucketHead]; fetchExpiredTimeouts(expiredTimeouts, i); } finally { lock.writeLock().unlock(); } } private void fetchExpiredTimeouts( List expiredTimeouts, ReusableIterator i) { long currentDeadline = System.currentTimeMillis() + tickDuration; i.rewind(); while (i.hasNext()) { HashedWheelTimeout timeout = i.next(); if (timeout.remainingRounds <= 0) { if (timeout.deadline < currentDeadline) { i.remove(); expiredTimeouts.add(timeout); } else { // A rare case where a timeout is put for the next // round: just wait for the next round. } } else { timeout.remainingRounds --; } } } private void notifyExpiredTimeouts( List expiredTimeouts) { // Notify the expired timeouts. for (int i = expiredTimeouts.size() - 1; i >= 0; i --) { expiredTimeouts.get(i).expire(); } // Clean up the temporary list. expiredTimeouts.clear(); } private void waitForNextTick() { for (;;) { final long currentTime = System.currentTimeMillis(); final long sleepTime = tickDuration * tick - (currentTime - startTime); if (sleepTime <= 0) { break; } try { Thread.sleep(sleepTime); } catch (InterruptedException e) { if (shutdown.get()) { return; } } } // Reset the tick if overflow is expected. if (tickDuration * tick > Long.MAX_VALUE - tickDuration) { startTime = System.currentTimeMillis(); tick = 1; } else { // Increase the tick if overflow is not likely to happen. tick ++; } } } private final class HashedWheelTimeout implements Timeout { private final TimerTask task; final int stopIndex; final long deadline; volatile long remainingRounds; private volatile boolean cancelled; HashedWheelTimeout( TimerTask task, long deadline, int stopIndex, long remainingRounds) { this.task = task; this.deadline = deadline; this.stopIndex = stopIndex; this.remainingRounds = remainingRounds; } public Timer getTimer() { return HashedWheelTimer.this; } public TimerTask getTask() { return task; } public void cancel() { if (isExpired()) { return; } cancelled = true; // Might be called more than once, but doesn't matter. wheel[stopIndex].remove(this); } public boolean isCancelled() { return cancelled; } public boolean isExpired() { return cancelled || System.currentTimeMillis() > deadline; } public void expire() { if (cancelled) { return; } try { task.run(this); } catch (Throwable t) { logger.warn( "An exception was thrown by " + TimerTask.class.getSimpleName() + ".", t); } } @Override public String toString() { long currentTime = System.currentTimeMillis(); long remaining = deadline - currentTime; StringBuilder buf = new StringBuilder(192); buf.append(getClass().getSimpleName()); buf.append('('); buf.append("deadline: "); if (remaining > 0) { buf.append(remaining); buf.append(" ms later, "); } else if (remaining < 0) { buf.append(-remaining); buf.append(" ms ago, "); } else { buf.append("now, "); } if (isCancelled()) { buf.append (", cancelled"); } return buf.append(')').toString(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/ObjectSizeEstimator.java0000644000175000017500000000302611216100607030335 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; /** * Estimates the size of an object in bytes. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1396 $, $Date: 2009-06-16 22:39:19 -0700 (Tue, 16 Jun 2009) $ */ public interface ObjectSizeEstimator { /** * Returns the estimated size of the specified object in bytes. * * @return a positive integer which represents the size of the specified * object in bytes */ int estimateSize(Object o); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/package-info.java0000644000175000017500000000214611165342601026737 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Utility classes used across multiple packages. * * @apiviz.exclude */ package org.jboss.netty.util;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/util/ThreadRenamingRunnable.java0000644000175000017500000001132111216100607030760 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.util; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * A {@link Runnable} that changes the current thread name and reverts it back * when its execution ends. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1396 $, $Date: 2009-06-16 22:39:19 -0700 (Tue, 16 Jun 2009) $ * */ public class ThreadRenamingRunnable implements Runnable { private static final InternalLogger logger = InternalLoggerFactory.getInstance(ThreadRenamingRunnable.class); private static volatile ThreadNameDeterminer threadNameDeterminer = new ThreadNameDeterminer() { public String determineThreadName( String oldThreadName, String newThreadName) throws Exception { return newThreadName; } }; /** * Returns the {@link ThreadNameDeterminer} which overrides the proposed * new thread name. */ public static ThreadNameDeterminer getThreadNameDeterminer() { return threadNameDeterminer; } /** * Sets the {@link ThreadNameDeterminer} which overrides the proposed new * thread name. */ public static void setThreadNameDeterminer(ThreadNameDeterminer threadNameDeterminer) { if (threadNameDeterminer == null) { throw new NullPointerException("threadNameDeterminer"); } ThreadRenamingRunnable.threadNameDeterminer = threadNameDeterminer; } private final Runnable runnable; private final String proposedThreadName; /** * Creates a new instance which wraps the specified {@code runnable} * and changes the thread name to the specified thread name when the * specified {@code runnable} is running. */ public ThreadRenamingRunnable(Runnable runnable, String proposedThreadName) { if (runnable == null) { throw new NullPointerException("runnable"); } if (proposedThreadName == null) { throw new NullPointerException("proposedThreadName"); } this.runnable = runnable; this.proposedThreadName = proposedThreadName; } public void run() { final Thread currentThread = Thread.currentThread(); final String oldThreadName = currentThread.getName(); final String newThreadName = getNewThreadName(oldThreadName); // Change the thread name before starting the actual runnable. boolean renamed = false; if (!oldThreadName.equals(newThreadName)) { try { currentThread.setName(newThreadName); renamed = true; } catch (SecurityException e) { logger.debug( "Failed to rename a thread " + "due to security restriction.", e); } } // Run the actual runnable and revert the name back when it ends. try { runnable.run(); } finally { if (renamed) { // Revert the name back if the current thread was renamed. // We do not check the exception here because we know it works. currentThread.setName(oldThreadName); } } } private String getNewThreadName(String currentThreadName) { String newThreadName = null; try { newThreadName = getThreadNameDeterminer().determineThreadName( currentThreadName, proposedThreadName); } catch (Throwable t) { logger.warn("Failed to determine the thread name", t); } return newThreadName == null? currentThreadName : newThreadName; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/bootstrap/0000755000175000017500000000000011316313144024603 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/bootstrap/ClientBootstrap.java0000644000175000017500000002733611216075231030576 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import static org.jboss.netty.channel.Channels.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.nio.channels.NotYetConnectedException; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelPipelineException; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * A helper class which creates a new client-side {@link Channel} and makes a * connection attempt. * *

Configuring a channel

* * {@link #setOption(String, Object) Options} are used to configure a channel: * *
 * ClientBootstrap b = ...;
 *
 * // Options for a new channel
 * b.setOption("remoteAddress", new {@link InetSocketAddress}("example.com", 8080));
 * b.setOption("tcpNoDelay", true);
 * b.setOption("receiveBufferSize", 1048576);
 * 
* * For the detailed list of available options, please refer to * {@link ChannelConfig} and its sub-types * *

Configuring a channel pipeline

* * Every channel has its own {@link ChannelPipeline} and you can configure it * in two ways. *

* {@linkplain #setPipeline(ChannelPipeline) The first approach} is to use * the default pipeline and let the bootstrap to shallow-copy the default * pipeline for each new channel: * *

 * ClientBootstrap b = ...;
 * {@link ChannelPipeline} p = b.getPipeline();
 *
 * // Add handlers to the pipeline.
 * p.addLast("encoder", new EncodingHandler());
 * p.addLast("decoder", new DecodingHandler());
 * p.addLast("logic",   new LogicHandler());
 * 
* * Please note 'shallow-copy' here means that the added {@link ChannelHandler}s * are not cloned but only their references are added to the new pipeline. * Therefore, you have to choose the second approach if you are going to open * more than one {@link Channel} whose {@link ChannelPipeline} contains any * {@link ChannelHandler} whose {@link ChannelPipelineCoverage} is {@code "one"}. * *

* {@linkplain #setPipelineFactory(ChannelPipelineFactory) The second approach} * is to specify a {@link ChannelPipelineFactory} by yourself and have full * control over how a new pipeline is created. This approach is more complex * than the first approach while it is much more flexible: * *

 * ClientBootstrap b = ...;
 * b.setPipelineFactory(new MyPipelineFactory());
 *
 * public class MyPipelineFactory implements {@link ChannelPipelineFactory} {
 *   // Create a new pipeline for a new channel and configure it here ...
 * }
 * 
* *

Applying different settings for different {@link Channel}s

* * {@link ClientBootstrap} is just a helper class. It neither allocates nor * manages any resources. What manages the resources is the * {@link ChannelFactory} implementation you specified in the constructor of * {@link ClientBootstrap}. Therefore, it is OK to create as many * {@link ClientBootstrap} instances as you want to apply different settings * for different {@link Channel}s. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1393 $, $Date: 2009-06-16 22:09:45 -0700 (Tue, 16 Jun 2009) $ * * @apiviz.landmark */ public class ClientBootstrap extends Bootstrap { /** * Creates a new instance with no {@link ChannelFactory} set. * {@link #setFactory(ChannelFactory)} must be called before any I/O * operation is requested. */ public ClientBootstrap() { super(); } /** * Creates a new instance with the specified initial {@link ChannelFactory}. */ public ClientBootstrap(ChannelFactory channelFactory) { super(channelFactory); } /** * Attempts a new connection with the current {@code "remoteAddress"} and * {@code "localAddress"} option. If the {@code "localAddress"} option is * not set, the local address of a new channel is determined automatically. * This method is similar to the following code: * *
     * ClientBootstrap b = ...;
     * b.connect(b.getOption("remoteAddress"), b.getOption("localAddress"));
     * 
* * @return a future object which notifies when this connection attempt * succeeds or fails * * @throws IllegalStateException * if {@code "remoteAddress"} option was not set * @throws ClassCastException * if {@code "remoteAddress"} or {@code "localAddress"} option's * value is neither a {@link SocketAddress} nor {@code null} * @throws ChannelPipelineException * if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory} * failed to create a new {@link ChannelPipeline} */ public ChannelFuture connect() { SocketAddress remoteAddress = (SocketAddress) getOption("remoteAddress"); if (remoteAddress == null) { throw new IllegalStateException("remoteAddress option is not set."); } return connect(remoteAddress); } /** * Attempts a new connection with the specified {@code remoteAddress} and * the current {@code "localAddress"} option. If the {@code "localAddress"} * option is not set, the local address of a new channel is determined * automatically. This method is identical with the following code: * *
     * ClientBootstrap b = ...;
     * b.connect(remoteAddress, b.getOption("localAddress"));
     * 
* * @return a future object which notifies when this connection attempt * succeeds or fails * * @throws ClassCastException * if {@code "localAddress"} option's value is * neither a {@link SocketAddress} nor {@code null} * @throws ChannelPipelineException * if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory} * failed to create a new {@link ChannelPipeline} */ public ChannelFuture connect(SocketAddress remoteAddress) { if (remoteAddress == null) { throw new NullPointerException("remotedAddress"); } SocketAddress localAddress = (SocketAddress) getOption("localAddress"); return connect(remoteAddress, localAddress); } /** * Attempts a new connection with the specified {@code remoteAddress} and * the specified {@code localAddress}. If the specified local address is * {@code null}, the local address of a new channel is determined * automatically. * * @return a future object which notifies when this connection attempt * succeeds or fails * * @throws ChannelPipelineException * if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory} * failed to create a new {@link ChannelPipeline} */ public ChannelFuture connect(final SocketAddress remoteAddress, final SocketAddress localAddress) { if (remoteAddress == null) { throw new NullPointerException("remoteAddress"); } final BlockingQueue futureQueue = new LinkedBlockingQueue(); ChannelPipeline pipeline; try { pipeline = getPipelineFactory().getPipeline(); } catch (Exception e) { throw new ChannelPipelineException("Failed to initialize a pipeline.", e); } pipeline.addFirst( "connector", new Connector( this, remoteAddress, localAddress, futureQueue)); getFactory().newChannel(pipeline); // Wait until the future is available. ChannelFuture future = null; do { try { future = futureQueue.poll(Integer.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException e) { // Ignore } } while (future == null); pipeline.remove("connector"); return future; } @ChannelPipelineCoverage("one") static final class Connector extends SimpleChannelUpstreamHandler { private final Bootstrap bootstrap; private final SocketAddress localAddress; private final BlockingQueue futureQueue; private final SocketAddress remoteAddress; private volatile boolean finished = false; Connector( Bootstrap bootstrap, SocketAddress remoteAddress, SocketAddress localAddress, BlockingQueue futureQueue) { this.bootstrap = bootstrap; this.localAddress = localAddress; this.futureQueue = futureQueue; this.remoteAddress = remoteAddress; } @Override public void channelOpen( ChannelHandlerContext context, ChannelStateEvent event) { try { // Apply options. event.getChannel().getConfig().setOptions(bootstrap.getOptions()); } finally { context.sendUpstream(event); } // Bind or connect. if (localAddress != null) { event.getChannel().bind(localAddress); } else { finished = futureQueue.offer(event.getChannel().connect(remoteAddress)); assert finished; } } @Override public void channelBound( ChannelHandlerContext context, ChannelStateEvent event) { context.sendUpstream(event); // Connect if not connected yet. if (localAddress != null) { finished = futureQueue.offer(event.getChannel().connect(remoteAddress)); assert finished; } } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { ctx.sendUpstream(e); Throwable cause = e.getCause(); if (!(cause instanceof NotYetConnectedException) && !finished) { e.getChannel().close(); finished = futureQueue.offer(failedFuture(e.getChannel(), cause)); assert finished; } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/bootstrap/Bootstrap.java0000644000175000017500000002643011216074225027433 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import static org.jboss.netty.channel.Channels.*; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.TreeMap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.util.ExternalResourceReleasable; import org.jboss.netty.util.internal.MapUtil; /** * A helper class which initializes a {@link Channel}. This class provides * the common data structure for its subclasses which actually initialize * {@link Channel}s and their child {@link Channel}s using the common data * structure. Please refer to {@link ClientBootstrap}, {@link ServerBootstrap}, * and {@link ConnectionlessBootstrap} for client side, server-side, and * connectionless (e.g. UDP) channel initialization respectively. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1392 $, $Date: 2009-06-16 22:01:09 -0700 (Tue, 16 Jun 2009) $ * * @apiviz.uses org.jboss.netty.channel.ChannelFactory */ public class Bootstrap implements ExternalResourceReleasable { private volatile ChannelFactory factory; private volatile ChannelPipeline pipeline = pipeline(); private volatile ChannelPipelineFactory pipelineFactory = pipelineFactory(pipeline); private volatile Map options = new HashMap(); /** * Creates a new instance with no {@link ChannelFactory} set. * {@link #setFactory(ChannelFactory)} must be called at once before any * I/O operation is requested. */ protected Bootstrap() { super(); } /** * Creates a new instance with the specified initial {@link ChannelFactory}. */ protected Bootstrap(ChannelFactory channelFactory) { setFactory(channelFactory); } /** * Returns the {@link ChannelFactory} that will be used to perform an * I/O operation. * * @throws IllegalStateException * if the factory is not set for this bootstrap yet. * The factory can be set in the constructor or * {@link #setFactory(ChannelFactory)}. */ public ChannelFactory getFactory() { ChannelFactory factory = this.factory; if (factory == null) { throw new IllegalStateException( "factory is not set yet."); } return factory; } /** * Sets the {@link ChannelFactory} that will be used to perform an I/O * operation. This method can be called only once and can't be called at * all if the factory was specified in the constructor. * * @throws IllegalStateException * if the factory is already set */ public void setFactory(ChannelFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } if (this.factory != null) { throw new IllegalStateException( "factory can't change once set."); } this.factory = factory; } /** * Returns the default {@link ChannelPipeline} which is cloned when a new * {@link Channel} is created. {@link Bootstrap} creates a new pipeline * which has the same entries with the returned pipeline for a new * {@link Channel}. * * @return the default {@link ChannelPipeline} * * @throws IllegalStateException * if {@link #setPipelineFactory(ChannelPipelineFactory)} was * called by a user last time. */ public ChannelPipeline getPipeline() { ChannelPipeline pipeline = this.pipeline; if (pipeline == null) { throw new IllegalStateException( "getPipeline() cannot be called " + "if setPipelineFactory() was called."); } return pipeline; } /** * Sets the default {@link ChannelPipeline} which is cloned when a new * {@link Channel} is created. {@link Bootstrap} creates a new pipeline * which has the same entries with the specified pipeline for a new channel. *

* Calling this method also sets the {@code pipelineFactory} property to an * internal {@link ChannelPipelineFactory} implementation which returns * a shallow copy of the specified pipeline. *

* Please note that this method is a convenience method that works only * when 1) you create only one channel from this bootstrap (e.g. * one-time client-side or connectionless channel) or 2) the * {@link ChannelPipelineCoverage} of all handlers in the pipeline is * {@code "all"}. You have to use * {@link #setPipelineFactory(ChannelPipelineFactory)} if 1) your * pipeline contains a {@link ChannelHandler} whose * {@link ChannelPipelineCoverage} is {@code "one"} and 2) one or * more channels are going to be created by this bootstrap (e.g. server-side * channels). */ public void setPipeline(ChannelPipeline pipeline) { if (pipeline == null) { throw new NullPointerException("pipeline"); } this.pipeline = pipeline; pipelineFactory = pipelineFactory(pipeline); } /** * Dependency injection friendly convenience method for * {@link #getPipeline()} which returns the default pipeline of this * bootstrap as an ordered map. * * @throws IllegalStateException * if {@link #setPipelineFactory(ChannelPipelineFactory)} was * called by a user last time. */ public Map getPipelineAsMap() { ChannelPipeline pipeline = this.pipeline; if (pipeline == null) { throw new IllegalStateException("pipelineFactory in use"); } return pipeline.toMap(); } /** * Dependency injection friendly convenience method for * {@link #setPipeline(ChannelPipeline)} which sets the default pipeline of * this bootstrap from an ordered map. * * @throws IllegalArgumentException * if the specified map is not an ordered map */ public void setPipelineAsMap(Map pipelineMap) { if (pipelineMap == null) { throw new NullPointerException("pipelineMap"); } if (!MapUtil.isOrderedMap(pipelineMap)) { throw new IllegalArgumentException( "pipelineMap is not an ordered map. " + "Please use " + LinkedHashMap.class.getName() + "."); } ChannelPipeline pipeline = pipeline(); for(Map.Entry e: pipelineMap.entrySet()) { pipeline.addLast(e.getKey(), e.getValue()); } setPipeline(pipeline); } /** * Returns the {@link ChannelPipelineFactory} which creates a new * {@link ChannelPipeline} for a new {@link Channel}. * * @see #getPipeline() */ public ChannelPipelineFactory getPipelineFactory() { return pipelineFactory; } /** * Sets the {@link ChannelPipelineFactory} which creates a new * {@link ChannelPipeline} for a new {@link Channel}. Calling this method * invalidates the current {@code pipeline} property of this bootstrap. * Subsequent {@link #getPipeline()} and {@link #getPipelineAsMap()} calls * will raise {@link IllegalStateException}. * * @see #setPipeline(ChannelPipeline) * @see #setPipelineAsMap(Map) */ public void setPipelineFactory(ChannelPipelineFactory pipelineFactory) { if (pipelineFactory == null) { throw new NullPointerException("pipelineFactory"); } pipeline = null; this.pipelineFactory = pipelineFactory; } /** * Returns the options which configures a new {@link Channel} and its * child {@link Channel}s. The names of the child {@link Channel} options * are prepended with {@code "child."} (e.g. {@code "child.keepAlive"}). */ public Map getOptions() { return new TreeMap(options); } /** * Sets the options which configures a new {@link Channel} and its child * {@link Channel}s. To set the options of a child {@link Channel}, prepend * {@code "child."} to the option name (e.g. {@code "child.keepAlive"}). */ public void setOptions(Map options) { if (options == null) { throw new NullPointerException("options"); } this.options = new HashMap(options); } /** * Returns the value of the option with the specified key. To retrieve * the option value of a child {@link Channel}, prepend {@code "child."} * to the option name (e.g. {@code "child.keepAlive"}). * * @param key the option name * * @return the option value if the option is found. * {@code null} otherwise. */ public Object getOption(String key) { if (key == null) { throw new NullPointerException("key"); } return options.get(key); } /** * Sets an option with the specified key and value. If there's already * an option with the same key, it is replaced with the new value. If the * specified value is {@code null}, an existing option with the specified * key is removed. To set the option value of a child {@link Channel}, * prepend {@code "child."} to the option name (e.g. {@code "child.keepAlive"}). * * @param key the option name * @param value the option value */ public void setOption(String key, Object value) { if (key == null) { throw new NullPointerException("key"); } if (value == null) { options.remove(key); } else { options.put(key, value); } } /** * {@inheritDoc} This method simply delegates the call to * {@link ChannelFactory#releaseExternalResources()}. */ public void releaseExternalResources() { ChannelFactory factory = this.factory; if (factory != null) { factory.releaseExternalResources(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/bootstrap/ServerBootstrap.java0000644000175000017500000003270311216075462030626 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import static org.jboss.netty.channel.Channels.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChildChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.ServerChannelFactory; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * A helper class which creates a new server-side {@link Channel} and accepts * incoming connections. * *

Only for connection oriented transports

* * This bootstrap is for connection oriented transports only such as TCP/IP * and local transport. Use {@link ConnectionlessBootstrap} instead for * connectionless transports. Do not use this helper if you are using a * connectionless transport such as UDP/IP which does not accept an incoming * connection but receives messages by itself without creating a child channel. * *

Parent channel and its children

* * A parent channel is a channel which is supposed to accept incoming * connections. It is created by this bootstrap's {@link ChannelFactory} via * {@link #bind()} and {@link #bind(SocketAddress)}. *

* Once successfully bound, the parent channel starts to accept incoming * connections, and the accepted connections become the children of the * parent channel. * *

Configuring channels

* * {@link #setOption(String, Object) Options} are used to configure both a * parent channel and its child channels. To configure the child channels, * prepend {@code "child."} prefix to the actual option names of a child * channel: * *
 * ServerBootstrap b = ...;
 *
 * // Options for a parent channel
 * b.setOption("localAddress", new {@link InetSocketAddress}(8080));
 * b.setOption("reuseAddress", true);
 *
 * // Options for its children
 * b.setOption("child.tcpNoDelay", true);
 * b.setOption("child.receiveBufferSize", 1048576);
 * 
* * For the detailed list of available options, please refer to * {@link ChannelConfig} and its sub-types. * *

Configuring a parent channel pipeline

* * It is rare to customize the pipeline of a parent channel because what it is * supposed to do is very typical. However, you might want to add a handler * to deal with some special needs such as degrading the process * UID from * a superuser to a * normal user and changing the current VM security manager for better * security. To support such a case, * the {@link #setParentHandler(ChannelHandler) parentHandler} property is * provided. * *

Configuring a child channel pipeline

* * Every child channel has its own {@link ChannelPipeline} and you can * configure it in two ways. * * {@linkplain #setPipeline(ChannelPipeline) The first approach} is to use * the default pipeline and let the bootstrap to shallow copy the default * pipeline for each new child channel: * *
 * ServerBootstrap b = ...;
 * {@link ChannelPipeline} p = b.getPipeline();
 *
 * // Add handlers to the pipeline.
 * p.addLast("encoder", new EncodingHandler());
 * p.addLast("decoder", new DecodingHandler());
 * p.addLast("logic",   new LogicHandler());
 * 
* * Please note 'shallow-copy' here means that the added {@link ChannelHandler}s * are not cloned but only their references are added to the new pipeline. * Therefore, you have to choose the second approach if you are going to accept * more than one child {@link Channel} whose {@link ChannelPipeline} contains * any {@link ChannelHandler} whose {@link ChannelPipelineCoverage} is * {@code "one"}. *

* {@linkplain #setPipelineFactory(ChannelPipelineFactory) The second approach} * is to specify a {@link ChannelPipelineFactory} by yourself and have full * control over how a new pipeline is created. This approach is more complex * than the first approach while it is much more flexible: * *

 * ServerBootstrap b = ...;
 * b.setPipelineFactory(new MyPipelineFactory());
 *
 * public class MyPipelineFactory implements {@link ChannelPipelineFactory} {
 *   // Create a new pipeline for a new child channel and configure it here ...
 * }
 * 
* *

Applying different settings for different {@link Channel}s

* * {@link ServerBootstrap} is just a helper class. It neither allocates nor * manages any resources. What manages the resources is the * {@link ChannelFactory} implementation you specified in the constructor of * {@link ServerBootstrap}. Therefore, it is OK to create as many * {@link ServerBootstrap} instances as you want to apply different settings * for different {@link Channel}s. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1394 $, $Date: 2009-06-16 22:12:18 -0700 (Tue, 16 Jun 2009) $ * * @apiviz.landmark */ public class ServerBootstrap extends Bootstrap { private volatile ChannelHandler parentHandler; /** * Creates a new instance with no {@link ChannelFactory} set. * {@link #setFactory(ChannelFactory)} must be called before any I/O * operation is requested. */ public ServerBootstrap() { super(); } /** * Creates a new instance with the specified initial {@link ChannelFactory}. */ public ServerBootstrap(ChannelFactory channelFactory) { super(channelFactory); } /** * {@inheritDoc} * * @throws IllegalArgumentException * if the specified {@code factory} is not a * {@link ServerChannelFactory} */ @Override public void setFactory(ChannelFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } if (!(factory instanceof ServerChannelFactory)) { throw new IllegalArgumentException( "factory must be a " + ServerChannelFactory.class.getSimpleName() + ": " + factory.getClass()); } super.setFactory(factory); } /** * Returns an optional {@link ChannelHandler} which intercepts an event * of a newly bound server-side channel which accepts incoming connections. * * @return the parent channel handler. * {@code null} if no parent channel handler is set. */ public ChannelHandler getParentHandler() { return parentHandler; } /** * Sets an optional {@link ChannelHandler} which intercepts an event of * a newly bound server-side channel which accepts incoming connections. * * @param parentHandler * the parent channel handler. * {@code null} to unset the current parent channel handler. */ public void setParentHandler(ChannelHandler parentHandler) { this.parentHandler = parentHandler; } /** * Creates a new channel which is bound to the local address which was * specified in the current {@code "localAddress"} option. This method is * similar to the following code: * *
     * ServerBootstrap b = ...;
     * b.connect(b.getOption("localAddress"));
     * 
* * @return a new bound channel which accepts incoming connections * * @throws IllegalStateException * if {@code "localAddress"} option was not set * @throws ClassCastException * if {@code "localAddress"} option's value is * neither a {@link SocketAddress} nor {@code null} * @throws ChannelException * if failed to create a new channel and * bind it to the local address */ public Channel bind() { SocketAddress localAddress = (SocketAddress) getOption("localAddress"); if (localAddress == null) { throw new IllegalStateException("localAddress option is not set."); } return bind(localAddress); } /** * Creates a new channel which is bound to the specified local address. * * @return a new bound channel which accepts incoming connections * * @throws ChannelException * if failed to create a new channel and * bind it to the local address */ public Channel bind(final SocketAddress localAddress) { if (localAddress == null) { throw new NullPointerException("localAddress"); } final BlockingQueue futureQueue = new LinkedBlockingQueue(); ChannelPipeline bossPipeline = pipeline(); bossPipeline.addLast("binder", new Binder(localAddress, futureQueue)); ChannelHandler parentHandler = getParentHandler(); if (parentHandler != null) { bossPipeline.addLast("userHandler", parentHandler); } Channel channel = getFactory().newChannel(bossPipeline); // Wait until the future is available. ChannelFuture future = null; do { try { future = futureQueue.poll(Integer.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException e) { // Ignore } } while (future == null); // Wait for the future. future.awaitUninterruptibly(); if (!future.isSuccess()) { future.getChannel().close().awaitUninterruptibly(); throw new ChannelException("Failed to bind to: " + localAddress, future.getCause()); } return channel; } @ChannelPipelineCoverage("one") private final class Binder extends SimpleChannelUpstreamHandler { private final SocketAddress localAddress; private final BlockingQueue futureQueue; private final Map childOptions = new HashMap(); Binder(SocketAddress localAddress, BlockingQueue futureQueue) { this.localAddress = localAddress; this.futureQueue = futureQueue; } @Override public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent evt) { try { evt.getChannel().getConfig().setPipelineFactory(getPipelineFactory()); // Split options into two categories: parent and child. Map allOptions = getOptions(); Map parentOptions = new HashMap(); for (Entry e: allOptions.entrySet()) { if (e.getKey().startsWith("child.")) { childOptions.put( e.getKey().substring(6), e.getValue()); } else if (!e.getKey().equals("pipelineFactory")) { parentOptions.put(e.getKey(), e.getValue()); } } // Apply parent options. evt.getChannel().getConfig().setOptions(parentOptions); } finally { ctx.sendUpstream(evt); } boolean finished = futureQueue.offer(evt.getChannel().bind(localAddress)); assert finished; } @Override public void childChannelOpen( ChannelHandlerContext ctx, ChildChannelStateEvent e) throws Exception { // Apply child options. e.getChildChannel().getConfig().setOptions(childOptions); ctx.sendUpstream(e); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { boolean finished = futureQueue.offer(failedFuture(e.getChannel(), e.getCause())); assert finished; ctx.sendUpstream(e); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/bootstrap/package-info.java0000644000175000017500000000230311175556210027776 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * IoC/DI friendly helper classes which enable an easy implementation of * typical client side and server side channel initialization. * * @apiviz.landmark */ package org.jboss.netty.bootstrap; libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/bootstrap/ConnectionlessBootstrap.java0000644000175000017500000003370411216075231032342 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.bootstrap; import static org.jboss.netty.channel.Channels.*; import java.net.InetSocketAddress; import java.net.SocketAddress; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelException; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelPipelineException; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * A helper class which creates a new server-side {@link Channel} for a * connectionless transport. * *

Only for connectionless transports

* * This bootstrap is for connectionless transports only such as UDP/IP. * Use {@link ServerBootstrap} instead for connection oriented transports. * Do not use this helper if you are using a connection oriented transport such * as TCP/IP and local transport which accepts an incoming connection and lets * the accepted child channels handle received messages. * *

Configuring channels

* * {@link #setOption(String, Object) Options} are used to configure a channel: * *
 * ConnectionlessBootstrap b = ...;
 *
 * // Options for a new channel
 * b.setOption("localAddress", new {@link InetSocketAddress}(8080));
 * b.setOption("tcpNoDelay", true);
 * b.setOption("receiveBufferSize", 1048576);
 * 
* * For the detailed list of available options, please refer to * {@link ChannelConfig} and its sub-types * *

Configuring a channel pipeline

* * Every channel has its own {@link ChannelPipeline} and you can configure it * in two ways. *

* {@linkplain #setPipeline(ChannelPipeline) The first approach} is to use * the default pipeline and let the bootstrap to shallow-copy the default * pipeline for each new channel: * *

 * ConnectionlessBootstrap b = ...;
 * {@link ChannelPipeline} p = b.getPipeline();
 *
 * // Add handlers to the pipeline.
 * p.addLast("encoder", new EncodingHandler());
 * p.addLast("decoder", new DecodingHandler());
 * p.addLast("logic",   new LogicHandler());
 * 
* * Please note 'shallow-copy' here means that the added {@link ChannelHandler}s * are not cloned but only their references are added to the new pipeline. * Therefore, you have to choose the second approach if you are going to open * more than one {@link Channel} whose {@link ChannelPipeline} contains any * {@link ChannelHandler} whose {@link ChannelPipelineCoverage} is {@code "one"}. * *

* {@linkplain #setPipelineFactory(ChannelPipelineFactory) The second approach} * is to specify a {@link ChannelPipelineFactory} by yourself and have full * control over how a new pipeline is created. This approach is more complex * than the first approach while it is much more flexible: * *

 * ConnectionlessBootstrap b = ...;
 * b.setPipelineFactory(new MyPipelineFactory());
 *
 * public class MyPipelineFactory implements {@link ChannelPipelineFactory} {
 *   // Create a new pipeline for a new channel and configure it here ...
 * }
 * 
* *

Applying different settings for different {@link Channel}s

* * {@link ConnectionlessBootstrap} is just a helper class. It neither * allocates nor manages any resources. What manages the resources is the * {@link ChannelFactory} implementation you specified in the constructor of * {@link ConnectionlessBootstrap}. Therefore, it is OK to create as * many {@link ConnectionlessBootstrap} instances as you want to apply * different settings for different {@link Channel}s. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1393 $, $Date: 2009-06-16 22:09:45 -0700 (Tue, 16 Jun 2009) $ * * @apiviz.landmark */ public class ConnectionlessBootstrap extends Bootstrap { /** * Creates a new instance with no {@link ChannelFactory} set. * {@link #setFactory(ChannelFactory)} must be called before any I/O * operation is requested. */ public ConnectionlessBootstrap() { super(); } /** * Creates a new instance with the specified initial {@link ChannelFactory}. */ public ConnectionlessBootstrap(ChannelFactory channelFactory) { super(channelFactory); } /** * Creates a new channel which is bound to the local address which was * specified in the current {@code "localAddress"} option. This method is * similar to the following code: * *
     * ServerBootstrap b = ...;
     * b.connect(b.getOption("localAddress"));
     * 
* * @return a new bound channel which accepts incoming connections * * @throws IllegalStateException * if {@code "localAddress"} option was not set * @throws ClassCastException * if {@code "localAddress"} option's value is * neither a {@link SocketAddress} nor {@code null} * @throws ChannelException * if failed to create a new channel and * bind it to the local address */ public Channel bind() { SocketAddress localAddress = (SocketAddress) getOption("localAddress"); if (localAddress == null) { throw new IllegalStateException("localAddress option is not set."); } return bind(localAddress); } /** * Creates a new channel which is bound to the specified local address. * * @return a new bound channel which accepts incoming connections * * @throws ChannelException * if failed to create a new channel and * bind it to the local address */ public Channel bind(final SocketAddress localAddress) { if (localAddress == null) { throw new NullPointerException("localAddress"); } final BlockingQueue futureQueue = new LinkedBlockingQueue(); ChannelPipeline pipeline; try { pipeline = getPipelineFactory().getPipeline(); } catch (Exception e) { throw new ChannelPipelineException("Failed to initialize a pipeline.", e); } pipeline.addFirst("binder", new ConnectionlessBinder(localAddress, futureQueue)); Channel channel = getFactory().newChannel(pipeline); // Wait until the future is available. ChannelFuture future = null; do { try { future = futureQueue.poll(Integer.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException e) { // Ignore } } while (future == null); pipeline.remove("binder"); // Wait for the future. future.awaitUninterruptibly(); if (!future.isSuccess()) { future.getChannel().close().awaitUninterruptibly(); throw new ChannelException("Failed to bind to: " + localAddress, future.getCause()); } return channel; } /** * Creates a new connected channel with the current {@code "remoteAddress"} * and {@code "localAddress"} option. If the {@code "localAddress"} option * is not set, the local address of a new channel is determined * automatically. This method is similar to the following code: * *
     * ConnectionlessBootstrap b = ...;
     * b.connect(b.getOption("remoteAddress"), b.getOption("localAddress"));
     * 
* * @return a future object which notifies when the creation of the connected * channel succeeds or fails * * @throws IllegalStateException * if {@code "remoteAddress"} option was not set * @throws ClassCastException * if {@code "remoteAddress"} or {@code "localAddress"} option's * value is neither a {@link SocketAddress} nor {@code null} * @throws ChannelPipelineException * if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory} * failed to create a new {@link ChannelPipeline} */ public ChannelFuture connect() { SocketAddress remoteAddress = (SocketAddress) getOption("remoteAddress"); if (remoteAddress == null) { throw new IllegalStateException("remoteAddress option is not set."); } return connect(remoteAddress); } /** * Creates a new connected channel with the specified * {@code "remoteAddress"} and the current {@code "localAddress"} option. * If the {@code "localAddress"} option is not set, the local address of * a new channel is determined automatically. This method is identical * with the following code: * *
     * ClientBootstrap b = ...;
     * b.connect(remoteAddress, b.getOption("localAddress"));
     * 
* * @return a future object which notifies when the creation of the connected * channel succeeds or fails * * @throws ClassCastException * if {@code "localAddress"} option's value is * neither a {@link SocketAddress} nor {@code null} * @throws ChannelPipelineException * if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory} * failed to create a new {@link ChannelPipeline} */ public ChannelFuture connect(SocketAddress remoteAddress) { if (remoteAddress == null) { throw new NullPointerException("remotedAddress"); } SocketAddress localAddress = (SocketAddress) getOption("localAddress"); return connect(remoteAddress, localAddress); } /** * Creates a new connected channel with the specified * {@code "remoteAddress"} and the specified {@code "localAddress"}. * If the specified local address is {@code null}, the local address of a * new channel is determined automatically. * * @return a future object which notifies when the creation of the connected * channel succeeds or fails * * @throws ChannelPipelineException * if this bootstrap's {@link #setPipelineFactory(ChannelPipelineFactory) pipelineFactory} * failed to create a new {@link ChannelPipeline} */ public ChannelFuture connect(final SocketAddress remoteAddress, final SocketAddress localAddress) { if (remoteAddress == null) { throw new NullPointerException("remoteAddress"); } final BlockingQueue futureQueue = new LinkedBlockingQueue(); ChannelPipeline pipeline; try { pipeline = getPipelineFactory().getPipeline(); } catch (Exception e) { throw new ChannelPipelineException("Failed to initialize a pipeline.", e); } pipeline.addFirst( "connector", new ClientBootstrap.Connector( this, remoteAddress, localAddress, futureQueue)); getFactory().newChannel(pipeline); // Wait until the future is available. ChannelFuture future = null; do { try { future = futureQueue.poll(Integer.MAX_VALUE, TimeUnit.SECONDS); } catch (InterruptedException e) { // Ignore } } while (future == null); pipeline.remove("connector"); return future; } @ChannelPipelineCoverage("one") private final class ConnectionlessBinder extends SimpleChannelUpstreamHandler { private final SocketAddress localAddress; private final BlockingQueue futureQueue; ConnectionlessBinder(SocketAddress localAddress, BlockingQueue futureQueue) { this.localAddress = localAddress; this.futureQueue = futureQueue; } @Override public void channelOpen( ChannelHandlerContext ctx, ChannelStateEvent evt) { try { evt.getChannel().getConfig().setPipelineFactory(getPipelineFactory()); // Apply options. evt.getChannel().getConfig().setOptions(getOptions()); } finally { ctx.sendUpstream(evt); } boolean finished = futureQueue.offer(evt.getChannel().bind(localAddress)); assert finished; } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { boolean finished = futureQueue.offer(failedFuture(e.getChannel(), e.getCause())); assert finished; ctx.sendUpstream(e); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/0000755000175000017500000000000011316313141024034 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/HeapChannelBuffer.java0000644000175000017500000001523211216122153030202 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.UnsupportedCharsetException; /** * A skeletal implementation for Java heap buffers. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1399 $, $Date: 2009-06-17 01:08:11 -0700 (Wed, 17 Jun 2009) $ */ public abstract class HeapChannelBuffer extends AbstractChannelBuffer { /** * The underlying heap byte array that this buffer is wrapping. */ protected final byte[] array; /** * Creates a new heap buffer with a newly allocated byte array. * * @param length the length of the new byte array */ public HeapChannelBuffer(int length) { this(new byte[length], 0, 0); } /** * Creates a new heap buffer with an existing byte array. * * @param array the byte array to wrap */ public HeapChannelBuffer(byte[] array) { this(array, 0, array.length); } /** * Creates a new heap buffer with an existing byte array. * * @param array the byte array to wrap * @param readerIndex the initial reader index of this buffer * @param writerIndex the initial writer index of this buffer */ protected HeapChannelBuffer(byte[] array, int readerIndex, int writerIndex) { if (array == null) { throw new NullPointerException("array"); } this.array = array; setIndex(readerIndex, writerIndex); } public int capacity() { return array.length; } public byte getByte(int index) { return array[index]; } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { if (dst instanceof HeapChannelBuffer) { getBytes(index, ((HeapChannelBuffer) dst).array, dstIndex, length); } else { dst.setBytes(dstIndex, array, index, length); } } public void getBytes(int index, byte[] dst, int dstIndex, int length) { System.arraycopy(array, index, dst, dstIndex, length); } public void getBytes(int index, ByteBuffer dst) { dst.put(array, index, Math.min(capacity() - index, dst.remaining())); } public void getBytes(int index, OutputStream out, int length) throws IOException { out.write(array, index, length); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return out.write(ByteBuffer.wrap(array, index, length)); } public void setByte(int index, byte value) { array[index] = value; } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (src instanceof HeapChannelBuffer) { setBytes(index, ((HeapChannelBuffer) src).array, srcIndex, length); } else { src.getBytes(srcIndex, array, index, length); } } public void setBytes(int index, byte[] src, int srcIndex, int length) { System.arraycopy(src, srcIndex, array, index, length); } public void setBytes(int index, ByteBuffer src) { src.get(array, index, src.remaining()); } public int setBytes(int index, InputStream in, int length) throws IOException { int readBytes = 0; do { int localReadBytes = in.read(array, index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); return readBytes; } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { ByteBuffer buf = ByteBuffer.wrap(array, index, length); int readBytes = 0; do { int localReadBytes; try { localReadBytes = in.read(buf); } catch (ClosedChannelException e) { localReadBytes = -1; } if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } else if (localReadBytes == 0) { break; } readBytes += localReadBytes; } while (readBytes < length); return readBytes; } public ChannelBuffer slice(int index, int length) { if (index == 0) { if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } if (length == array.length) { return duplicate(); } else { return new TruncatedChannelBuffer(this, length); } } else { if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } return new SlicedChannelBuffer(this, index, length); } } public ByteBuffer toByteBuffer(int index, int length) { return ByteBuffer.wrap(array, index, length).order(order()); } public String toString(int index, int length, String charsetName) { try { return new String(array, index, length, charsetName); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(charsetName); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ChannelBufferInputStream.java0000644000175000017500000001542411057163620031612 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.DataInput; import java.io.DataInputStream; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; /** * An {@link InputStream} which reads data from a {@link ChannelBuffer}. *

* A read operation against this stream will occur at the {@code readerIndex} * of its underlying buffer and the {@code readerIndex} will increase during * the read operation. *

* This stream implements {@link DataInput} for your convenience. * The endianness of the stream is not always big endian but depends on * the endianness of the underlying buffer. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 181 $, $Date: 2008-09-02 00:13:20 -0700 (Tue, 02 Sep 2008) $ * * @see ChannelBufferOutputStream * @apiviz.uses org.jboss.netty.buffer.ChannelBuffer */ public class ChannelBufferInputStream extends InputStream implements DataInput { private final ChannelBuffer buffer; private final int startIndex; private final int endIndex; /** * Creates a new stream which reads data from the specified {@code buffer} * starting at the current {@code readerIndex} and ending at the current * {@code writerIndex}. */ public ChannelBufferInputStream(ChannelBuffer buffer) { this(buffer, buffer.readableBytes()); } /** * Creates a new stream which reads data from the specified {@code buffer} * starting at the current {@code readerIndex} and ending at * {@code readerIndex + length}. * * @throws IndexOutOfBoundsException * if {@code readerIndex + length} is greater than * {@code writerIndex} */ public ChannelBufferInputStream(ChannelBuffer buffer, int length) { if (buffer == null) { throw new NullPointerException("buffer"); } if (length < 0) { throw new IllegalArgumentException("length: " + length); } if (length > buffer.readableBytes()) { throw new IndexOutOfBoundsException(); } this.buffer = buffer; startIndex = buffer.readerIndex(); endIndex = startIndex + length; buffer.markReaderIndex(); } /** * Returns the number of read bytes by this stream so far. */ public int readBytes() { return buffer.readerIndex() - startIndex; } @Override public int available() throws IOException { return endIndex - buffer.readerIndex(); } @Override public void mark(int readlimit) { buffer.markReaderIndex(); } @Override public boolean markSupported() { return true; } @Override public int read() throws IOException { if (!buffer.readable()) { return -1; } return buffer.readByte() & 0xff; } @Override public int read(byte[] b, int off, int len) throws IOException { int available = available(); if (available == 0) { return -1; } len = Math.min(available, len); buffer.readBytes(b, off, len); return len; } @Override public void reset() throws IOException { buffer.resetReaderIndex(); } @Override public long skip(long n) throws IOException { if (n > Integer.MAX_VALUE) { return skipBytes(Integer.MAX_VALUE); } else { return skipBytes((int) n); } } public boolean readBoolean() throws IOException { checkAvailable(1); return read() != 0; } public byte readByte() throws IOException { if (!buffer.readable()) { throw new EOFException(); } return buffer.readByte(); } public char readChar() throws IOException { return (char) readShort(); } public double readDouble() throws IOException { return Double.longBitsToDouble(readLong()); } public float readFloat() throws IOException { return Float.intBitsToFloat(readInt()); } public void readFully(byte[] b) throws IOException { readFully(b, 0, b.length); } public void readFully(byte[] b, int off, int len) throws IOException { checkAvailable(len); buffer.readBytes(b, off, len); } public int readInt() throws IOException { checkAvailable(4); return buffer.readInt(); } private final StringBuilder lineBuf = new StringBuilder(); public String readLine() throws IOException { lineBuf.setLength(0); for (;;) { int b = read(); if (b < 0 || b == '\n') { break; } lineBuf.append((char) b); } while (lineBuf.charAt(lineBuf.length() - 1) == '\r') { lineBuf.setLength(lineBuf.length() - 1); } return lineBuf.toString(); } public long readLong() throws IOException { checkAvailable(8); return buffer.readLong(); } public short readShort() throws IOException { checkAvailable(2); return buffer.readShort(); } public String readUTF() throws IOException { return DataInputStream.readUTF(this); } public int readUnsignedByte() throws IOException { return readByte() & 0xff; } public int readUnsignedShort() throws IOException { return readShort() & 0xffff; } public int skipBytes(int n) throws IOException { int nBytes = Math.min(available(), n); buffer.skipBytes(nBytes); return nBytes; } private void checkAvailable(int fieldSize) throws IOException { if (fieldSize < 0) { throw new IndexOutOfBoundsException(); } if (fieldSize > available()) { throw new EOFException(); } } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ReadOnlyChannelBuffer.java0000644000175000017500000001336211145244650031054 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.ReadOnlyBufferException; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; /** * A derived buffer which forbids any write requests to its parent. It is * recommended to use {@link ChannelBuffers#unmodifiableBuffer(ChannelBuffer)} * instead of calling the constructor explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 887 $, $Date: 2009-02-13 02:21:28 -0800 (Fri, 13 Feb 2009) $ * */ public class ReadOnlyChannelBuffer extends AbstractChannelBuffer implements WrappedChannelBuffer { private final ChannelBuffer buffer; public ReadOnlyChannelBuffer(ChannelBuffer buffer) { if (buffer == null) { throw new NullPointerException("buffer"); } this.buffer = buffer; setIndex(buffer.readerIndex(), buffer.writerIndex()); } private ReadOnlyChannelBuffer(ReadOnlyChannelBuffer buffer) { this.buffer = buffer.buffer; setIndex(buffer.readerIndex(), buffer.writerIndex()); } public ChannelBuffer unwrap() { return buffer; } public ChannelBufferFactory factory() { return buffer.factory(); } public ByteOrder order() { return buffer.order(); } @Override public void discardReadBytes() { throw new ReadOnlyBufferException(); } public void setByte(int index, byte value) { throw new ReadOnlyBufferException(); } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { throw new ReadOnlyBufferException(); } public void setBytes(int index, byte[] src, int srcIndex, int length) { throw new ReadOnlyBufferException(); } public void setBytes(int index, ByteBuffer src) { throw new ReadOnlyBufferException(); } public void setShort(int index, short value) { throw new ReadOnlyBufferException(); } public void setMedium(int index, int value) { throw new ReadOnlyBufferException(); } public void setInt(int index, int value) { throw new ReadOnlyBufferException(); } public void setLong(int index, long value) { throw new ReadOnlyBufferException(); } public int setBytes(int index, InputStream in, int length) throws IOException { throw new ReadOnlyBufferException(); } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { throw new ReadOnlyBufferException(); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return buffer.getBytes(index, out, length); } public void getBytes(int index, OutputStream out, int length) throws IOException { buffer.getBytes(index, out, length); } public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } public ChannelBuffer duplicate() { return new ReadOnlyChannelBuffer(this); } public ChannelBuffer copy(int index, int length) { return buffer.copy(index, length); } public ChannelBuffer slice(int index, int length) { return new ReadOnlyChannelBuffer(buffer.slice(index, length)); } public byte getByte(int index) { return buffer.getByte(index); } public short getShort(int index) { return buffer.getShort(index); } public int getUnsignedMedium(int index) { return buffer.getUnsignedMedium(index); } public int getInt(int index) { return buffer.getInt(index); } public long getLong(int index) { return buffer.getLong(index); } public ByteBuffer toByteBuffer(int index, int length) { return buffer.toByteBuffer(index, length).asReadOnlyBuffer(); } @Override public ByteBuffer[] toByteBuffers(int index, int length) { ByteBuffer[] bufs = buffer.toByteBuffers(index, length); for (int i = 0; i < bufs.length; i ++) { bufs[i] = bufs[i].asReadOnlyBuffer(); } return bufs; } public String toString(int index, int length, String charsetName) { return buffer.toString(index, length, charsetName); } public int capacity() { return buffer.capacity(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ByteBufferBackedChannelBuffer.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ByteBufferBackedChannelBuffer.java0000644000175000017500000002650411216120732032461 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.ClosedChannelException; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.UnsupportedCharsetException; /** * A NIO {@link ByteBuffer} based buffer. It is recommended to use {@link ChannelBuffers#directBuffer(int)} * and {@link ChannelBuffers#wrappedBuffer(ByteBuffer)} instead of calling the * constructor explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1398 $, $Date: 2009-06-17 00:57:14 -0700 (Wed, 17 Jun 2009) $ * */ public class ByteBufferBackedChannelBuffer extends AbstractChannelBuffer { private final ByteBuffer buffer; private final int capacity; /** * Creates a new buffer which wraps the specified buffer's slice. */ public ByteBufferBackedChannelBuffer(ByteBuffer buffer) { if (buffer == null) { throw new NullPointerException("buffer"); } this.buffer = buffer.slice().order(buffer.order()); capacity = buffer.remaining(); writerIndex(capacity); } private ByteBufferBackedChannelBuffer(ByteBufferBackedChannelBuffer buffer) { this.buffer = buffer.buffer; capacity = buffer.capacity; setIndex(buffer.readerIndex(), buffer.writerIndex()); } public ChannelBufferFactory factory() { if (buffer.isDirect()) { return DirectChannelBufferFactory.getInstance(order()); } else { return HeapChannelBufferFactory.getInstance(order()); } } public ByteOrder order() { return buffer.order(); } public int capacity() { return capacity; } public byte getByte(int index) { return buffer.get(index); } public short getShort(int index) { return buffer.getShort(index); } public int getUnsignedMedium(int index) { return (getByte(index) & 0xff) << 16 | (getByte(index+1) & 0xff) << 8 | (getByte(index+2) & 0xff) << 0; } public int getInt(int index) { return buffer.getInt(index); } public long getLong(int index) { return buffer.getLong(index); } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { if (dst instanceof ByteBufferBackedChannelBuffer) { ByteBufferBackedChannelBuffer bbdst = (ByteBufferBackedChannelBuffer) dst; ByteBuffer data = bbdst.buffer.duplicate(); data.limit(dstIndex + length).position(dstIndex); getBytes(index, data); } else if (buffer.hasArray()) { dst.setBytes(dstIndex, buffer.array(), index + buffer.arrayOffset(), length); } else { dst.setBytes(dstIndex, this, index, length); } } public void getBytes(int index, byte[] dst, int dstIndex, int length) { ByteBuffer data = buffer.duplicate(); try { data.limit(index + length).position(index); } catch (IllegalArgumentException e) { throw new IndexOutOfBoundsException(); } data.get(dst, dstIndex, length); } public void getBytes(int index, ByteBuffer dst) { ByteBuffer data = buffer.duplicate(); int bytesToCopy = Math.min(capacity() - index, dst.remaining()); try { data.limit(index + bytesToCopy).position(index); } catch (IllegalArgumentException e) { throw new IndexOutOfBoundsException(); } dst.put(data); } public void setByte(int index, byte value) { buffer.put(index, value); } public void setShort(int index, short value) { buffer.putShort(index, value); } public void setMedium(int index, int value) { setByte(index, (byte) (value >>> 16)); setByte(index+1, (byte) (value >>> 8)); setByte(index+2, (byte) (value >>> 0)); } public void setInt(int index, int value) { buffer.putInt(index, value); } public void setLong(int index, long value) { buffer.putLong(index, value); } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { if (src instanceof ByteBufferBackedChannelBuffer) { ByteBufferBackedChannelBuffer bbsrc = (ByteBufferBackedChannelBuffer) src; ByteBuffer data = bbsrc.buffer.duplicate(); data.limit(srcIndex + length).position(srcIndex); setBytes(index, data); } else if (buffer.hasArray()) { src.getBytes(srcIndex, buffer.array(), index + buffer.arrayOffset(), length); } else { src.getBytes(srcIndex, this, index, length); } } public void setBytes(int index, byte[] src, int srcIndex, int length) { ByteBuffer data = buffer.duplicate(); data.limit(index + length).position(index); data.put(src, srcIndex, length); } public void setBytes(int index, ByteBuffer src) { ByteBuffer data = buffer.duplicate(); data.limit(index + src.remaining()).position(index); data.put(src); } public void getBytes(int index, OutputStream out, int length) throws IOException { if (length == 0) { return; } if (!buffer.isReadOnly() && buffer.hasArray()) { out.write( buffer.array(), index + buffer.arrayOffset(), length); } else { byte[] tmp = new byte[length]; ((ByteBuffer) buffer.duplicate().position(index)).get(tmp); out.write(tmp); } } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { if (length == 0) { return 0; } return out.write((ByteBuffer) buffer.duplicate().position(index).limit(index + length)); } public int setBytes(int index, InputStream in, int length) throws IOException { int readBytes = 0; if (!buffer.isReadOnly() && buffer.hasArray()) { index += buffer.arrayOffset(); do { int localReadBytes = in.read(buffer.array(), index, length); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; index += localReadBytes; length -= localReadBytes; } while (length > 0); } else { byte[] tmp = new byte[length]; int i = 0; do { int localReadBytes = in.read(tmp, i, tmp.length - i); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } readBytes += localReadBytes; i += readBytes; } while (i < tmp.length); ((ByteBuffer) buffer.duplicate().position(index)).put(tmp); } return readBytes; } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { ByteBuffer slice = (ByteBuffer) buffer.duplicate().limit(index + length).position(index); int readBytes = 0; while (readBytes < length) { int localReadBytes; try { localReadBytes = in.read(slice); } catch (ClosedChannelException e) { localReadBytes = -1; } if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { return readBytes; } } else if (localReadBytes == 0) { break; } readBytes += localReadBytes; } return readBytes; } public ByteBuffer toByteBuffer(int index, int length) { if (index == 0 && length == capacity()) { return buffer.duplicate().order(order()); } else { return ((ByteBuffer) buffer.duplicate().position( index).limit(index + length)).slice().order(order()); } } public String toString(int index, int length, String charsetName) { if (!buffer.isReadOnly() && buffer.hasArray()) { try { return new String( buffer.array(), index + buffer.arrayOffset(), length, charsetName); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(charsetName); } } else { byte[] tmp = new byte[length]; ((ByteBuffer) buffer.duplicate().position(index)).get(tmp); try { return new String(tmp, charsetName); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(charsetName); } } } public ChannelBuffer slice(int index, int length) { if (index == 0 && length == capacity()) { return duplicate(); } else { if (index >= 0 && length == 0) { return ChannelBuffers.EMPTY_BUFFER; } return new ByteBufferBackedChannelBuffer( ((ByteBuffer) buffer.duplicate().position( index).limit(index + length)).order(order())); } } public ChannelBuffer duplicate() { return new ByteBufferBackedChannelBuffer(this); } public ChannelBuffer copy(int index, int length) { ByteBuffer src; try { src = (ByteBuffer) buffer.duplicate().position(index).limit(index + length); } catch (IllegalArgumentException e) { throw new IndexOutOfBoundsException(); } ByteBuffer dst = buffer.isDirect() ? ByteBuffer.allocateDirect(length) : ByteBuffer.allocate(length); dst.put(src); dst.order(order()); dst.clear(); return new ByteBufferBackedChannelBuffer(dst); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/DuplicatedChannelBuffer.java0000644000175000017500000001242611117154322031410 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; /** * A derived buffer which simply forwards all data access requests to its * parent. It is recommended to use {@link ChannelBuffer#duplicate()} instead * of calling the constructor explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 592 $, $Date: 2008-12-08 00:20:34 -0800 (Mon, 08 Dec 2008) $ * */ public class DuplicatedChannelBuffer extends AbstractChannelBuffer implements WrappedChannelBuffer { private final ChannelBuffer buffer; public DuplicatedChannelBuffer(ChannelBuffer buffer) { if (buffer == null) { throw new NullPointerException("buffer"); } this.buffer = buffer; setIndex(buffer.readerIndex(), buffer.writerIndex()); } private DuplicatedChannelBuffer(DuplicatedChannelBuffer buffer) { this.buffer = buffer.buffer; setIndex(buffer.readerIndex(), buffer.writerIndex()); } public ChannelBuffer unwrap() { return buffer; } public ChannelBufferFactory factory() { return buffer.factory(); } public ByteOrder order() { return buffer.order(); } public int capacity() { return buffer.capacity(); } public byte getByte(int index) { return buffer.getByte(index); } public short getShort(int index) { return buffer.getShort(index); } public int getUnsignedMedium(int index) { return buffer.getUnsignedMedium(index); } public int getInt(int index) { return buffer.getInt(index); } public long getLong(int index) { return buffer.getLong(index); } public ChannelBuffer duplicate() { return new DuplicatedChannelBuffer(this); } public ChannelBuffer copy(int index, int length) { return buffer.copy(index, length); } public ChannelBuffer slice(int index, int length) { return buffer.slice(index, length); } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } public void setByte(int index, byte value) { buffer.setByte(index, value); } public void setShort(int index, short value) { buffer.setShort(index, value); } public void setMedium(int index, int value) { buffer.setMedium(index, value); } public void setInt(int index, int value) { buffer.setInt(index, value); } public void setLong(int index, long value) { buffer.setLong(index, value); } public void setBytes(int index, byte[] src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } public void setBytes(int index, ByteBuffer src) { buffer.setBytes(index, src); } public void getBytes(int index, OutputStream out, int length) throws IOException { buffer.getBytes(index, out, length); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return buffer.getBytes(index, out, length); } public int setBytes(int index, InputStream in, int length) throws IOException { return buffer.setBytes(index, in, length); } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { return buffer.setBytes(index, in, length); } public ByteBuffer toByteBuffer(int index, int length) { return buffer.toByteBuffer(index, length); } public String toString(int index, int length, String charsetName) { return buffer.toString(index, length, charsetName); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ChannelBufferIndexFinder.java0000644000175000017500000001274611216124124031533 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; /** * Locates an index of data in a {@link ChannelBuffer}. *

* This interface enables the sequential search for the data which meets more * complex and dynamic condition than just a simple value matching. Please * refer to {@link ChannelBuffer#indexOf(int, int, ChannelBufferIndexFinder)}, * {@link ChannelBuffer#readBytes(ChannelBufferIndexFinder)}, * {@link ChannelBuffer#readSlice(ChannelBufferIndexFinder)}, and * {@link ChannelBuffer#skipBytes(ChannelBufferIndexFinder)} * for more explanation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1401 $, $Date: 2009-06-17 01:24:52 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.uses org.jboss.netty.buffer.ChannelBuffer */ public interface ChannelBufferIndexFinder { /** * Returns {@code true} if and only if the data is found at the specified * {@code guessedIndex} of the specified {@code buffer}. *

* The implementation should not perform an operation which raises an * exception such as {@link IndexOutOfBoundsException} nor perform * an operation which modifies the content of the buffer. */ boolean find(ChannelBuffer buffer, int guessedIndex); /** * Index finder which locates a {@code NUL (0x00)} byte. */ static ChannelBufferIndexFinder NUL = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { return buffer.getByte(guessedIndex) == 0; } }; /** * Index finder which locates a non-{@code NUL (0x00)} byte. */ static ChannelBufferIndexFinder NOT_NUL = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { return buffer.getByte(guessedIndex) != 0; } }; /** * Index finder which locates a {@code CR ('\r')} byte. */ static ChannelBufferIndexFinder CR = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { return buffer.getByte(guessedIndex) == '\r'; } }; /** * Index finder which locates a non-{@code CR ('\r')} byte. */ static ChannelBufferIndexFinder NOT_CR = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { return buffer.getByte(guessedIndex) != '\r'; } }; /** * Index finder which locates a {@code LF ('\n')} byte. */ static ChannelBufferIndexFinder LF = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { return buffer.getByte(guessedIndex) == '\n'; } }; /** * Index finder which locates a non-{@code LF ('\n')} byte. */ static ChannelBufferIndexFinder NOT_LF = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { return buffer.getByte(guessedIndex) != '\n'; } }; /** * Index finder which locates a {@code CR ('\r')} or {@code LF ('\n')}. */ static ChannelBufferIndexFinder CRLF = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { byte b = buffer.getByte(guessedIndex); return b == '\r' || b == '\n'; } }; /** * Index finder which locates a byte which is neither a {@code CR ('\r')} * nor a {@code LF ('\n')}. */ static ChannelBufferIndexFinder NOT_CRLF = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { byte b = buffer.getByte(guessedIndex); return b != '\r' && b != '\n'; } }; /** * Index finder which locates a linear whitespace * ({@code ' '} and {@code '\t'}). */ static ChannelBufferIndexFinder LINEAR_WHITESPACE = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { byte b = buffer.getByte(guessedIndex); return b == ' ' || b == '\t'; } }; /** * Index finder which locates a byte which is not a linear whitespace * (neither {@code ' '} nor {@code '\t'}). */ static ChannelBufferIndexFinder NOT_LINEAR_WHITESPACE = new ChannelBufferIndexFinder() { public boolean find(ChannelBuffer buffer, int guessedIndex) { byte b = buffer.getByte(guessedIndex); return b != ' ' && b != '\t'; } }; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/DynamicChannelBuffer.java0000644000175000017500000002101611156127144030716 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; /** * A dynamic capacity buffer which increases its capacity as needed. It is * recommended to use {@link ChannelBuffers#dynamicBuffer(int)} instead of * calling the constructor explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1017 $, $Date: 2009-03-11 23:40:36 -0700 (Wed, 11 Mar 2009) $ * */ public class DynamicChannelBuffer extends AbstractChannelBuffer { private final ChannelBufferFactory factory; private final int initialCapacity; private final ByteOrder endianness; private ChannelBuffer buffer = ChannelBuffers.EMPTY_BUFFER; public DynamicChannelBuffer(int estimatedLength) { this(ByteOrder.BIG_ENDIAN, estimatedLength); } public DynamicChannelBuffer(ByteOrder endianness, int estimatedLength) { this(endianness, estimatedLength, HeapChannelBufferFactory.getInstance(endianness)); } public DynamicChannelBuffer(ByteOrder endianness, int estimatedLength, ChannelBufferFactory factory) { if (estimatedLength < 0) { throw new IllegalArgumentException("estimatedLength: " + estimatedLength); } if (endianness == null) { throw new NullPointerException("endianness"); } if (factory == null) { throw new NullPointerException("factory"); } this.factory = factory; initialCapacity = estimatedLength; this.endianness = endianness; } public ChannelBufferFactory factory() { return factory; } public ByteOrder order() { return endianness; } public int capacity() { return buffer.capacity(); } public byte getByte(int index) { return buffer.getByte(index); } public short getShort(int index) { return buffer.getShort(index); } public int getUnsignedMedium(int index) { return buffer.getUnsignedMedium(index); } public int getInt(int index) { return buffer.getInt(index); } public long getLong(int index) { return buffer.getLong(index); } public void getBytes(int index, byte[] dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, ByteBuffer dst) { buffer.getBytes(index, dst); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { return buffer.getBytes(index, out, length); } public void getBytes(int index, OutputStream out, int length) throws IOException { buffer.getBytes(index, out, length); } public void setByte(int index, byte value) { buffer.setByte(index, value); } public void setShort(int index, short value) { buffer.setShort(index, value); } public void setMedium(int index, int value) { buffer.setMedium(index, value); } public void setInt(int index, int value) { buffer.setInt(index, value); } public void setLong(int index, long value) { buffer.setLong(index, value); } public void setBytes(int index, byte[] src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { buffer.setBytes(index, src, srcIndex, length); } public void setBytes(int index, ByteBuffer src) { buffer.setBytes(index, src); } public int setBytes(int index, InputStream in, int length) throws IOException { return buffer.setBytes(index, in, length); } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { return buffer.setBytes(index, in, length); } @Override public void writeByte(byte value) { ensureWritableBytes(1); super.writeByte(value); } @Override public void writeShort(short value) { ensureWritableBytes(2); super.writeShort(value); } @Override public void writeMedium(int value) { ensureWritableBytes(3); super.writeMedium(value); } @Override public void writeInt(int value) { ensureWritableBytes(4); super.writeInt(value); } @Override public void writeLong(long value) { ensureWritableBytes(8); super.writeLong(value); } @Override public void writeBytes(byte[] src, int srcIndex, int length) { ensureWritableBytes(length); super.writeBytes(src, srcIndex, length); } @Override public void writeBytes(ChannelBuffer src, int srcIndex, int length) { ensureWritableBytes(length); super.writeBytes(src, srcIndex, length); } @Override public void writeBytes(ByteBuffer src) { ensureWritableBytes(src.remaining()); super.writeBytes(src); } @Override public int writeBytes(InputStream in, int length) throws IOException { ensureWritableBytes(length); return super.writeBytes(in, length); } @Override public int writeBytes(ScatteringByteChannel in, int length) throws IOException { ensureWritableBytes(length); return super.writeBytes(in, length); } @Override public void writeZero(int length) { ensureWritableBytes(length); super.writeZero(length); } public ChannelBuffer duplicate() { return new DuplicatedChannelBuffer(this); } public ChannelBuffer copy(int index, int length) { DynamicChannelBuffer copiedBuffer = new DynamicChannelBuffer(order(), Math.max(length, 64), factory()); copiedBuffer.buffer = buffer.copy(index, length); copiedBuffer.setIndex(0, length); return copiedBuffer; } public ChannelBuffer slice(int index, int length) { if (index == 0) { if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } return new TruncatedChannelBuffer(this, length); } else { if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } return new SlicedChannelBuffer(this, index, length); } } public ByteBuffer toByteBuffer(int index, int length) { return buffer.toByteBuffer(index, length); } public String toString(int index, int length, String charsetName) { return buffer.toString(index, length, charsetName); } private void ensureWritableBytes(int requestedBytes) { if (requestedBytes <= writableBytes()) { return; } int newCapacity; if (capacity() == 0) { newCapacity = initialCapacity; if (newCapacity == 0) { newCapacity = 1; } } else { newCapacity = capacity(); } int minNewCapacity = writerIndex() + requestedBytes; while (newCapacity < minNewCapacity) { newCapacity <<= 1; } ChannelBuffer newBuffer = factory().getBuffer(order(), newCapacity); newBuffer.writeBytes(buffer, 0, writerIndex()); buffer = newBuffer; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ChannelBuffer.java0000644000175000017500000017066511216124124027420 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.UnsupportedCharsetException; import java.util.NoSuchElementException; /** * A random and sequential accessible sequence of zero or more bytes (octets). * This interface provides an abstract view for one or more primitive byte * arrays ({@code byte[]}) and {@linkplain ByteBuffer NIO buffers}. * *

Creation of a buffer

* * It is recommended to create a new buffer using the helper methods in * {@link ChannelBuffers} rather than calling an individual implementation's * constructor. * *

Random Access Indexing

* * Just like an ordinary primitive byte array, {@link ChannelBuffer} uses * zero-based indexing. * It means the index of the first byte is always {@code 0} and the index of * the last byte is always {@link #capacity() capacity - 1}. For example, to * iterate all bytes of a buffer, you can do the following, regardless of * its internal implementation: * *
 * ChannelBuffer buffer = ...;
 * for (int i = 0; i < buffer.capacity(); i ++) {
 *     byte b = array.getByte(i);
 *     System.out.println((char) b);
 * }
 * 
* *

Sequential Access Indexing

* * {@link ChannelBuffer} provides two pointer variables to support sequential * read and write operations - {@link #readerIndex() readerIndex} for a read * operation and {@link #writerIndex() writerIndex} for a write operation * respectively. The following diagram shows how a buffer is segmented into * three areas by the two pointers: * *
 *      +-------------------+------------------+------------------+
 *      | discardable bytes |  readable bytes  |  writable bytes  |
 *      |                   |     (CONTENT)    |                  |
 *      +-------------------+------------------+------------------+
 *      |                   |                  |                  |
 *      0      <=      readerIndex   <=   writerIndex    <=    capacity
 * 
* *

Readable bytes (the actual content)

* * This segment is where the actual data is stored. Any operation whose name * starts with {@code read} or {@code skip} will get or skip the data at the * current {@link #readerIndex() readerIndex} and increase it by the number of * read bytes. If the argument of the read operation is also a * {@link ChannelBuffer} and no destination index is specified, the specified * buffer's {@link #readerIndex() readerIndex} is increased together. *

* If there's not enough content left, {@link IndexOutOfBoundsException} is * raised. The default value of newly allocated, wrapped or copied buffer's * {@link #readerIndex() readerIndex} is {@code 0}. * *

 * // Iterates the readable bytes of a buffer.
 * ChannelBuffer buffer = ...;
 * while (buffer.readable()) {
 *     System.out.println(buffer.readByte());
 * }
 * 
* *

Writable bytes

* * This segment is a undefined space which needs to be filled. Any operation * whose name ends with {@code write} will write the data at the current * {@link #writerIndex() writerIndex} and increase it by the number of written * bytes. If the argument of the write operation is also a {@link ChannelBuffer}, * and no source index is specified, the specified buffer's * {@link #readerIndex() readerIndex} is increased together. *

* If there's not enough writable bytes left, {@link IndexOutOfBoundsException} * is raised. The default value of newly allocated buffer's * {@link #writerIndex() writerIndex} is {@code 0}. The default value of * wrapped or copied buffer's {@link #writerIndex() writerIndex} is the * {@link #capacity() capacity} of the buffer. * *

 * // Fills the writable bytes of a buffer with random integers.
 * ChannelBuffer buffer = ...;
 * while (buffer.writableBytes() >= 4) {
 *     buffer.writeInt(random.nextInt());
 * }
 * 
* *

Discardable bytes

* * This segment contains the bytes which were read already by a read operation. * Initially, the size of this segment is {@code 0}, but its size increases up * to the {@link #writerIndex() writerIndex} as read operations are executed. * The read bytes can be discarded by calling {@link #discardReadBytes()} to * reclaim unused area as depicted by the following diagram: * *
 *  BEFORE discardReadBytes()
 *
 *      +-------------------+------------------+------------------+
 *      | discardable bytes |  readable bytes  |  writable bytes  |
 *      +-------------------+------------------+------------------+
 *      |                   |                  |                  |
 *      0      <=      readerIndex   <=   writerIndex    <=    capacity
 *
 *
 *  AFTER discardReadBytes()
 *
 *      +------------------+--------------------------------------+
 *      |  readable bytes  |    writable bytes (got more space)   |
 *      +------------------+--------------------------------------+
 *      |                  |                                      |
 * readerIndex (0) <= writerIndex (decreased)        <=        capacity
 * 
* *

Clearing the buffer indexes

* * You can set both {@link #readerIndex() readerIndex} and * {@link #writerIndex() writerIndex} to {@code 0} by calling {@link #clear()}. * It does not clear the buffer content (e.g. filling with {@code 0}) but just * clears the two pointers. Please also note that the semantic of this * operation is different from {@link ByteBuffer#clear()}. * *
 *  BEFORE clear()
 *
 *      +-------------------+------------------+------------------+
 *      | discardable bytes |  readable bytes  |  writable bytes  |
 *      +-------------------+------------------+------------------+
 *      |                   |                  |                  |
 *      0      <=      readerIndex   <=   writerIndex    <=    capacity
 *
 *
 *  AFTER clear()
 *
 *      +---------------------------------------------------------+
 *      |             writable bytes (got more space)             |
 *      +---------------------------------------------------------+
 *      |                                                         |
 *      0 = readerIndex = writerIndex            <=            capacity
 * 
* *

Search operations

* * Various {@code indexOf()} methods help you locate an index of a value which * meets a certain criteria. Complicated dynamic sequential search can be done * with {@link ChannelBufferIndexFinder} as well as simple static single byte * search. * *

Mark and reset

* * There are two marker indexes in every buffer. One is for storing * {@link #readerIndex() readerIndex} and the other is for storing * {@link #writerIndex() writerIndex}. You can always reposition one of the * two indexes by calling a reset method. It works in a similar fashion to * the mark and reset methods in {@link InputStream} except that there's no * {@code readlimit}. * *

Derived buffers

* * You can create a view of an existing buffer by calling either * {@link #duplicate()}, {@link #slice()} or {@link #slice(int, int)}. * A derived buffer will have an independent {@link #readerIndex() readerIndex}, * {@link #writerIndex() writerIndex} and marker indexes, while it shares * other internal data representation, just like a NIO buffer does. *

* In case a completely fresh copy of an existing buffer is required, please * call {@link #copy()} method instead. * *

Conversion to existing JDK types

* *

NIO Buffers

* * Various {@link #toByteBuffer()} and {@link #toByteBuffers()} methods convert * a {@link ChannelBuffer} into one or more NIO buffers. These methods avoid * buffer allocation and memory copy whenever possible, but there's no * guarantee that memory copy will not be involved or that an explicit memory * copy will be involved. * *

Strings

* * Various {@link #toString(String)} methods convert a {@link ChannelBuffer} * into a {@link String}. Please note that {@link #toString()} is not a * conversion method. * *

I/O Streams

* * Please refer to {@link ChannelBufferInputStream} and * {@link ChannelBufferOutputStream}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1401 $, $Date: 2009-06-17 01:24:52 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.landmark */ public interface ChannelBuffer extends Comparable { /** * Returns the factory which creates a {@link ChannelBuffer} whose * type and default {@link ByteOrder} are same with this buffer. */ ChannelBufferFactory factory(); /** * Returns the number of bytes (octets) this buffer can contain. */ int capacity(); /** * Returns the endianness * of this buffer. */ ByteOrder order(); /** * Returns the {@code readerIndex} of this buffer. */ int readerIndex(); /** * Sets the {@code readerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code readerIndex} is * less than {@code 0} or * greater than {@code this.writerIndex} */ void readerIndex(int readerIndex); /** * Returns the {@code writerIndex} of this buffer. */ int writerIndex(); /** * Sets the {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code writerIndex} is * less than {@code this.readerIndex} or * greater than {@code this.capacity} */ void writerIndex(int writerIndex); /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer * in one shot. This method is useful when you have to worry about the * invocation order of {@link #readerIndex(int)} and {@link #writerIndex(int)} * methods. For example, the following code will fail: * *
     * // Create a buffer whose readerIndex, writerIndex and capacity are
     * // 0, 0 and 8 respectively.
     * ChannelBuffer buf = ChannelBuffers.buffer(8);
     *
     * // IndexOutOfBoundsException is thrown because the specified
     * // readerIndex (2) cannot be greater than the current writerIndex (0).
     * buf.readerIndex(2);
     * buf.writerIndex(4);
     * 
* * The following code will also fail: * *
     * // Create a buffer whose readerIndex, writerIndex and capacity are
     * // 0, 8 and 8 respectively.
     * ChannelBuffer buf = ChannelBuffers.wrappedBuffer(new byte[8]);
     *
     * // readerIndex becomes 8.
     * buf.readLong();
     *
     * // IndexOutOfBoundsException is thrown because the specified
     * // writerIndex (4) cannot be less than the current readerIndex (8).
     * buf.writerIndex(4);
     * buf.readerIndex(2);
     * 
* * By contrast, {@link #setIndex(int, int)} guarantees that it never * throws an {@link IndexOutOfBoundsException} as long as the specified * indexes meet basic constraints, regardless what the current index * values of the buffer are: * *
     * // No matter what the current state of the buffer is, the following
     * // call always succeeds as long as the capacity of the buffer is not
     * // less than 4.
     * buf.setIndex(2, 4);
     * 
* * @throws IndexOutOfBoundsException * if the specified {@code readerIndex} is less than 0, * if the specified {@code writerIndex} is less than the specified * {@code readerIndex} or if the specified {@code writerIndex} is * greater than {@code this.capacity} */ void setIndex(int readerIndex, int writerIndex); /** * Returns the number of readable bytes which is equal to * {@code (this.writerIndex - this.readerIndex)}. */ int readableBytes(); /** * Returns the number of writable bytes which is equal to * {@code (this.capacity - this.writerIndex)}. */ int writableBytes(); /** * Returns {@code true} * if and only if {@code (this.writerIndex - this.readerIndex)} is greater * than {@code 0}. */ boolean readable(); /** * Returns {@code true} * if and only if {@code (this.capacity - this.writerIndex)} is greater * than {@code 0}. */ boolean writable(); /** * Sets the {@code readerIndex} and {@code writerIndex} of this buffer to * {@code 0}. * This method is identical to {@link #setIndex(int, int) setIndex(0, 0)}. *

* Please note that the behavior of this method is different * from that of NIO buffer, which sets the {@code limit} to * the {@code capacity} of the buffer. */ void clear(); /** * Marks the current {@code readerIndex} in this buffer. You can * reposition the current {@code readerIndex} to the marked * {@code readerIndex} by calling {@link #resetReaderIndex()}. * The initial value of the marked {@code readerIndex} is {@code 0}. */ void markReaderIndex(); /** * Repositions the current {@code readerIndex} to the marked * {@code readerIndex} in this buffer. * * @throws IndexOutOfBoundsException * if the current {@code writerIndex} is less than the marked * {@code readerIndex} */ void resetReaderIndex(); /** * Marks the current {@code writerIndex} in this buffer. You can * reposition the current {@code writerIndex} to the marked * {@code writerIndex} by calling {@link #resetWriterIndex()}. * The initial value of the marked {@code writerIndex} is {@code 0}. */ void markWriterIndex(); /** * Repositions the current {@code writerIndex} to the marked * {@code writerIndex} in this buffer. * * @throws IndexOutOfBoundsException * if the current {@code readerIndex} is greater than the marked * {@code writerIndex} */ void resetWriterIndex(); /** * Discards the bytes between the 0th index and {@code readerIndex}. * It moves the bytes between {@code readerIndex} and {@code writerIndex} * to the 0th index, and sets {@code readerIndex} and {@code writerIndex} * to {@code 0} and {@code oldWriterIndex - oldReaderIndex} respectively. *

* Please refer to the class documentation for more detailed explanation. */ void discardReadBytes(); /** * Gets a byte at the specified absolute {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ byte getByte(int index); /** * Gets an unsigned byte at the specified absolute {@code index} in this * buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ short getUnsignedByte(int index); /** * Gets a 16-bit short integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ short getShort(int index); /** * Gets an unsigned 16-bit short integer at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ int getUnsignedShort(int index); /** * Gets a 24-bit medium integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ int getMedium(int index); /** * Gets an unsigned 24-bit medium integer at the specified absolute * {@code index} in this buffer. This method does not modify * {@code readerIndex} or {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ int getUnsignedMedium(int index); /** * Gets a 32-bit integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ int getInt(int index); /** * Gets an unsigned 32-bit integer at the specified absolute {@code index} * in this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ long getUnsignedInt(int index); /** * Gets a 64-bit long integer at the specified absolute {@code index} in * this buffer. This method does not modify {@code readerIndex} or * {@code writerIndex} of this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ long getLong(int index); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination becomes * non-writable. This method is basically same with * {@link #getBytes(int, ChannelBuffer, int, int)}, except that this * method increases the {@code writerIndex} of the destination by the * number of the transferred bytes while * {@link #getBytes(int, ChannelBuffer, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.writableBytes} is greater than * {@code this.capacity} */ void getBytes(int index, ChannelBuffer dst); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. This method is basically same * with {@link #getBytes(int, ChannelBuffer, int, int)}, except that this * method increases the {@code writerIndex} of the destination by the * number of the transferred bytes while * {@link #getBytes(int, ChannelBuffer, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code length} is greater than {@code dst.writableBytes} */ void getBytes(int index, ChannelBuffer dst, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code dstIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code dstIndex + length} is greater than * {@code dst.capacity} */ void getBytes(int index, ChannelBuffer dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.length} is greater than * {@code this.capacity} */ void getBytes(int index, byte[] dst); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of this buffer. * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code dstIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code dstIndex + length} is greater than * {@code dst.length} */ void getBytes(int index, byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the specified absolute {@code index} until the destination's position * reaches its limit. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer while the destination's {@code position} will be increased. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + dst.remaining()} is greater than * {@code this.capacity} */ void getBytes(int index, ByteBuffer dst); /** * Transfers this buffer's data to the specified stream starting at the * specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified stream threw an exception during I/O */ void getBytes(int index, OutputStream out, int length) throws IOException; /** * Transfers this buffer's data to the specified channel starting at the * specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than * {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ int getBytes(int index, GatheringByteChannel out, int length) throws IOException; /** * Sets the specified byte at the specified absolute {@code index} in this * buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 1} is greater than {@code this.capacity} */ void setByte(int index, byte value); /** * Sets the specified 16-bit short integer at the specified absolute * {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 2} is greater than {@code this.capacity} */ void setShort(int index, short value); /** * Sets the specified 24-bit medium integer at the specified absolute * {@code index} in this buffer. Please note that the most significant * byte is ignored in the specified value. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 3} is greater than {@code this.capacity} */ void setMedium(int index, int value); /** * Sets the specified 32-bit integer at the specified absolute * {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 4} is greater than {@code this.capacity} */ void setInt(int index, int value); /** * Sets the specified 64-bit long integer at the specified absolute * {@code index} in this buffer. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * {@code index + 8} is greater than {@code this.capacity} */ void setLong(int index, long value); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the destination becomes * unreadable. This method is basically same with * {@link #setBytes(int, ChannelBuffer, int, int)}, except that this * method increases the {@code readerIndex} of the source buffer by * the number of the transferred bytes while * {@link #getBytes(int, ChannelBuffer, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.readableBytes} is greater than * {@code this.capacity} */ void setBytes(int index, ChannelBuffer src); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. This method is basically same * with {@link #setBytes(int, ChannelBuffer, int, int)}, except that this * method increases the {@code readerIndex} of the source buffer by * the number of the transferred bytes while * {@link #getBytes(int, ChannelBuffer, int, int)} does not. * This method does not modify {@code readerIndex} or {@code writerIndex} of * the source buffer (i.e. {@code this}). * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code length} is greater than {@code src.readableBytes} */ void setBytes(int index, ChannelBuffer src, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} * of both the source (i.e. {@code this}) and the destination. * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code srcIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code srcIndex + length} is greater than * {@code src.capacity} */ void setBytes(int index, ChannelBuffer src, int srcIndex, int length); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.length} is greater than * {@code this.capacity} */ void setBytes(int index, byte[] src); /** * Transfers the specified source array's data to this buffer starting at * the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0}, * if the specified {@code srcIndex} is less than {@code 0}, * if {@code index + length} is greater than * {@code this.capacity}, or * if {@code srcIndex + length} is greater than {@code src.length} */ void setBytes(int index, byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the specified absolute {@code index} until the source buffer's position * reaches its limit. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + src.remaining()} is greater than * {@code this.capacity} */ void setBytes(int index, ByteBuffer src); /** * Transfers the content of the specified source stream to this buffer * starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified stream threw an exception during I/O */ int setBytes(int index, InputStream in, int length) throws IOException; /** * Transfers the content of the specified source channel to this buffer * starting at the specified absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel. * {@code -1} if the specified channel is closed. * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} * @throws IOException * if the specified channel threw an exception during I/O */ int setBytes(int index, ScatteringByteChannel in, int length) throws IOException; /** * Fills this buffer with NUL (0x00) starting at the specified * absolute {@code index}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @param length the number of NULs to write to the buffer * * @throws IndexOutOfBoundsException * if the specified {@code index} is less than {@code 0} or * if {@code index + length} is greater than {@code this.capacity} */ void setZero(int index, int length); /** * Gets a byte at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ byte readByte(); /** * Gets an unsigned byte at the current {@code readerIndex} and increases * the {@code readerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 1} */ short readUnsignedByte(); /** * Gets a 16-bit short integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ short readShort(); /** * Gets an unsigned 16-bit short integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 2} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 2} */ int readUnsignedShort(); /** * Gets a 24-bit medium integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ int readMedium(); /** * Gets an unsigned 24-bit medium integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 3} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 3} */ int readUnsignedMedium(); /** * Gets a 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ int readInt(); /** * Gets an unsigned 32-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 4} */ long readUnsignedInt(); /** * Gets a 64-bit integer at the current {@code readerIndex} * and increases the {@code readerIndex} by {@code 8} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.readableBytes} is less than {@code 8} */ long readLong(); /** * Transfers this buffer's data to a newly created buffer starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * The returned buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and {@code length} respectively. * * @param length the number of bytes to transfer * * @return the newly created buffer which contains the transferred bytes * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ ChannelBuffer readBytes(int length); /** * Transfers this buffer's data to a newly created buffer starting at * the current {@code readerIndex} until the specified {@code indexFinder} * returns {@code true} and increases the {@code readerIndex} * by the number of the transferred bytes. The returned buffer's * {@code readerIndex} and {@code writerIndex} are {@code 0} and * the number of the transferred bytes respectively. * * @param indexFinder finds the end index of the sub-region * * @return the newly created buffer which contains the transferred bytes * * @throws NoSuchElementException * if {@code indexFinder} didn't return {@code true} at all */ ChannelBuffer readBytes(ChannelBufferIndexFinder indexFinder); /** * Returns a new slice of this buffer's sub-region starting at the current * {@code readerIndex} and increases the {@code readerIndex} by the size * of the new slice (= {@code length}). * * @param length the size of the new slice * * @return the newly created slice * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ ChannelBuffer readSlice(int length); /** * Returns a new slice of this buffer's sub-region starting at the current * {@code readerIndex} and increases the {@code readerIndex} by the size * of the new slice (determined by {@code indexFinder}). * * @param indexFinder finds the end index of the sub-region * * @return the newly created slice * * @throws NoSuchElementException * if {@code indexFinder} didn't return {@code true} at all */ ChannelBuffer readSlice(ChannelBufferIndexFinder indexFinder); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} until the destination becomes * non-writable, and increases the {@code readerIndex} by the number of the * transferred bytes. This method is basically same with * {@link #readBytes(ChannelBuffer, int, int)}, except that this method * increases the {@code writerIndex} of the destination by the number of * the transferred bytes while {@link #readBytes(ChannelBuffer, int, int)} * does not. * * @throws IndexOutOfBoundsException * if {@code dst.writableBytes} is greater than * {@code this.readableBytes} */ void readBytes(ChannelBuffer dst); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). This method * is basically same with {@link #readBytes(ChannelBuffer, int, int)}, * except that this method increases the {@code writerIndex} of the * destination by the number of the transferred bytes (= {@code length}) * while {@link #readBytes(ChannelBuffer, int, int)} does not. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} or * if {@code length} is greater than {@code dst.writableBytes} */ void readBytes(ChannelBuffer dst, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code dstIndex} is less than {@code 0}, * if {@code length} is greater than {@code this.readableBytes}, or * if {@code dstIndex + length} is greater than * {@code dst.capacity} */ void readBytes(ChannelBuffer dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code dst.length}). * * @throws IndexOutOfBoundsException * if {@code dst.length} is greater than {@code this.readableBytes} */ void readBytes(byte[] dst); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} and increases the {@code readerIndex} * by the number of the transferred bytes (= {@code length}). * * @param dstIndex the first index of the destination * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code dstIndex} is less than {@code 0}, * if {@code length} is greater than {@code this.readableBytes}, or * if {@code dstIndex + length} is greater than {@code dst.length} */ void readBytes(byte[] dst, int dstIndex, int length); /** * Transfers this buffer's data to the specified destination starting at * the current {@code readerIndex} until the destination's position * reaches its limit, and increases the {@code readerIndex} by the * number of the transferred bytes. * * @throws IndexOutOfBoundsException * if {@code dst.remaining()} is greater than * {@code this.readableBytes} */ void readBytes(ByteBuffer dst); /** * Transfers this buffer's data to the specified stream starting at the * current {@code readerIndex}. * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified stream threw an exception during I/O */ void readBytes(OutputStream out, int length) throws IOException; /** * Transfers this buffer's data to the specified stream starting at the * current {@code readerIndex}. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes written out to the specified channel * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} * @throws IOException * if the specified channel threw an exception during I/O */ int readBytes(GatheringByteChannel out, int length) throws IOException; /** * Increases the current {@code readerIndex} by the specified * {@code length} in this buffer. * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.readableBytes} */ void skipBytes(int length); /** * Increases the current {@code readerIndex} until the specified * {@code indexFinder} returns {@code true} in this buffer. * * @return the number of skipped bytes * * @throws NoSuchElementException * if {@code firstIndexFinder} didn't return {@code true} at all */ int skipBytes(ChannelBufferIndexFinder indexFinder); /** * Sets the specified byte at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 1} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.writableBytes} is less than {@code 1} */ void writeByte(byte value); /** * Sets the specified 16-bit short integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 2} * in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.writableBytes} is less than {@code 2} */ void writeShort(short value); /** * Sets the specified 24-bit medium integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 3} * in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.writableBytes} is less than {@code 3} */ void writeMedium(int value); /** * Sets the specified 32-bit integer at the current {@code writerIndex} * and increases the {@code writerIndex} by {@code 4} in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.writableBytes} is less than {@code 4} */ void writeInt(int value); /** * Sets the specified 64-bit long integer at the current * {@code writerIndex} and increases the {@code writerIndex} by {@code 8} * in this buffer. * * @throws IndexOutOfBoundsException * if {@code this.writableBytes} is less than {@code 8} */ void writeLong(long value); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer becomes * unreadable, and increases the {@code writerIndex} by the number of * the transferred bytes. This method is basically same with * {@link #writeBytes(ChannelBuffer, int, int)}, except that this method * increases the {@code readerIndex} of the source buffer by the number of * the transferred bytes while {@link #writeBytes(ChannelBuffer, int, int)} * does not. * * @throws IndexOutOfBoundsException * if {@code src.readableBytes} is greater than * {@code this.writableBytes} * */ void writeBytes(ChannelBuffer src); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). This method * is basically same with {@link #writeBytes(ChannelBuffer, int, int)}, * except that this method increases the {@code readerIndex} of the source * buffer by the number of the transferred bytes (= {@code length}) while * {@link #writeBytes(ChannelBuffer, int, int)} does not. * * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.writableBytes} or * if {@code length} is greater then {@code src.readableBytes} */ void writeBytes(ChannelBuffer src, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code srcIndex} is less than {@code 0}, * if {@code srcIndex + length} is greater than * {@code src.capacity}, or * if {@code length} is greater than {@code this.writableBytes} */ void writeBytes(ChannelBuffer src, int srcIndex, int length); /** * Transfers the specified source array's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code src.length}). * * @throws IndexOutOfBoundsException * if {@code src.length} is greater than {@code this.writableBytes} */ void writeBytes(byte[] src); /** * Transfers the specified source array's data to this buffer starting at * the current {@code writerIndex} and increases the {@code writerIndex} * by the number of the transferred bytes (= {@code length}). * * @param srcIndex the first index of the source * @param length the number of bytes to transfer * * @throws IndexOutOfBoundsException * if the specified {@code srcIndex} is less than {@code 0}, * if {@code srcIndex + length} is greater than * {@code src.length}, or * if {@code length} is greater than {@code this.writableBytes} */ void writeBytes(byte[] src, int srcIndex, int length); /** * Transfers the specified source buffer's data to this buffer starting at * the current {@code writerIndex} until the source buffer's position * reaches its limit, and increases the {@code writerIndex} by the * number of the transferred bytes. * * @throws IndexOutOfBoundsException * if {@code src.remaining()} is greater than * {@code this.writableBytes} */ void writeBytes(ByteBuffer src); /** * Transfers the content of the specified stream to this buffer * starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * * @param length the number of bytes to transfer * * @return the actual number of bytes read in from the specified stream * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.writableBytes} * @throws IOException * if the specified stream threw an exception during I/O */ int writeBytes(InputStream in, int length) throws IOException; /** * Transfers the content of the specified channel to this buffer * starting at the current {@code writerIndex} and increases the * {@code writerIndex} by the number of the transferred bytes. * * @param length the maximum number of bytes to transfer * * @return the actual number of bytes read in from the specified channel * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.writableBytes} * @throws IOException * if the specified channel threw an exception during I/O */ int writeBytes(ScatteringByteChannel in, int length) throws IOException; /** * Fills this buffer with NUL (0x00) starting at the current * {@code writerIndex} and increases the {@code writerIndex} by the * specified {@code length}. * * @param length the number of NULs to write to the buffer * * @throws IndexOutOfBoundsException * if {@code length} is greater than {@code this.writableBytes} */ void writeZero(int length); /** * Locates the first occurrence of the specified {@code value} in this * buffer. The search takes place from the specified {@code fromIndex} * (inclusive) to the specified {@code toIndex} (exclusive). *

* If {@code fromIndex} is greater than {@code toIndex}, the search is * performed in a reversed order. *

* This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the absolute index of the first occurrence if found. * {@code -1} otherwise. */ int indexOf(int fromIndex, int toIndex, byte value); /** * Locates the first index where the specified {@code indexFinder} * returns {@code true}. The search takes place from the specified * {@code fromIndex} (inclusive) to the specified {@code toIndex} * (exclusive). *

* If {@code fromIndex} is greater than {@code toIndex}, the search is * performed in a reversed order. *

* This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @return the absolute index where the specified {@code indexFinder} * returned {@code true} if the {@code indexFinder} returned * {@code true}. {@code -1} otherwise. */ int indexOf(int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder); /** * Returns a copy of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer does not affect each other at all. * This method is identical to {@code buf.copy(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * */ ChannelBuffer copy(); /** * Returns a copy of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer does not affect each other at all. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ChannelBuffer copy(int index, int length); /** * Returns a slice of this buffer's readable bytes. Modifying the content * of the returned buffer or this buffer affects each other's content * while they maintain separate indexes and marks. This method is * identical to {@code buf.slice(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ChannelBuffer slice(); /** * Returns a slice of this buffer's sub-region. Modifying the content of * the returned buffer or this buffer affects each other's content while * they maintain separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ChannelBuffer slice(int index, int length); /** * Returns a buffer which shares the whole region of this buffer. * Modifying the content of the returned buffer or this buffer affects * each other's content while they maintain separate indexes and marks. * This method is identical to {@code buf.slice(0, buf.capacity())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ChannelBuffer duplicate(); /** * Converts this buffer's readable bytes into a NIO buffer. The returned * buffer might or might not share the content with this buffer, while * they have separate indexes and marks. This method is identical to * {@code buf.toByteBuffer(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ByteBuffer toByteBuffer(); /** * Converts this buffer's sub-region into a NIO buffer. The returned * buffer might or might not share the content with this buffer, while * they have separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ByteBuffer toByteBuffer(int index, int length); /** * Converts this buffer's readable bytes into an array of NIO buffers. * The returned buffers might or might not share the content with this * buffer, while they have separate indexes and marks. This method is * identical to {@code buf.toByteBuffers(buf.readerIndex(), buf.readableBytes())}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ByteBuffer[] toByteBuffers(); /** * Converts this buffer's sub-region into an array of NIO buffers. * The returned buffers might or might not share the content with this * buffer, while they have separate indexes and marks. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. */ ByteBuffer[] toByteBuffers(int index, int length); /** * Decodes this buffer's readable bytes into a string with the specified * character set name. This method is identical to * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName)}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws UnsupportedCharsetException * if the specified character set name is not supported by the * current VM */ String toString(String charsetName); /** * Decodes this buffer's readable bytes into a string until the specified * {@code terminatorFinder} returns {@code true} with the specified * character set name. This method is identical to * {@code buf.toString(buf.readerIndex(), buf.readableBytes(), charsetName, terminatorFinder)}. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws UnsupportedCharsetException * if the specified character set name is not supported by the * current VM */ String toString( String charsetName, ChannelBufferIndexFinder terminatorFinder); /** * Decodes this buffer's sub-region into a string with the specified * character set name. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws UnsupportedCharsetException * if the specified character set name is not supported by the * current VM */ String toString(int index, int length, String charsetName); /** * Decodes this buffer's readable bytes into a string until the specified * {@code terminatorFinder} returns {@code true} with the specified * character set name. * This method does not modify {@code readerIndex} or {@code writerIndex} of * this buffer. * * @throws UnsupportedCharsetException * if the specified character set name is not supported by the * current VM */ String toString( int index, int length, String charsetName, ChannelBufferIndexFinder terminatorFinder); /** * Returns a hash code which was calculated from the content of this * buffer. If there's a byte array which is * {@linkplain #equals(Object) equal to} this array, both arrays should * return the same value. */ int hashCode(); /** * Determines if the content of the specified buffer is identical to the * content of this array. 'Identical' here means: *

    *
  • the size of the contents of the two buffers are same and
  • *
  • every single byte of the content of the two buffers are same.
  • *
* Please note that it does not compare {@link #readerIndex()} nor * {@link #writerIndex()}. This method also returns {@code false} for * {@code null} and an object which is not an instance of * {@link ChannelBuffer} type. */ boolean equals(Object obj); /** * Compares the content of the specified buffer to the content of this * buffer. Comparison is performed in the same manner with the string * comparison functions of various languages such as {@code strcmp}, * {@code memcmp} and {@link String#compareTo(String)}. */ int compareTo(ChannelBuffer buffer); /** * Returns the string representation of this buffer. This method does not * necessarily return the whole content of the buffer but returns * the values of the key properties such as {@link #readerIndex()}, * {@link #writerIndex()} and {@link #capacity()}. */ String toString(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ChannelBufferOutputStream.java0000644000175000017500000001047411216124124032004 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.DataOutput; import java.io.DataOutputStream; import java.io.IOException; import java.io.OutputStream; /** * An {@link OutputStream} which writes data to a {@link ChannelBuffer}. *

* A write operation against this stream will occur at the {@code writerIndex} * of its underlying buffer and the {@code writerIndex} will increase during * the write operation. *

* This stream implements {@link DataOutput} for your convenience. * The endianness of the stream is not always big endian but depends on * the endianness of the underlying buffer. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1401 $, $Date: 2009-06-17 01:24:52 -0700 (Wed, 17 Jun 2009) $ * * @see ChannelBufferInputStream * @apiviz.uses org.jboss.netty.buffer.ChannelBuffer */ public class ChannelBufferOutputStream extends OutputStream implements DataOutput { private final ChannelBuffer buffer; private final int startIndex; private final DataOutputStream utf8out = new DataOutputStream(this); /** * Creates a new stream which writes data to the specified {@code buffer}. */ public ChannelBufferOutputStream(ChannelBuffer buffer) { if (buffer == null) { throw new NullPointerException("buffer"); } this.buffer = buffer; startIndex = buffer.writerIndex(); } /** * Returns the number of written bytes by this stream so far. */ public int writtenBytes() { return buffer.writerIndex() - startIndex; } @Override public void write(byte[] b, int off, int len) throws IOException { if (len == 0) { return; } buffer.writeBytes(b, off, len); } @Override public void write(byte[] b) throws IOException { buffer.writeBytes(b); } @Override public void write(int b) throws IOException { buffer.writeByte((byte) b); } public void writeBoolean(boolean v) throws IOException { write(v? (byte) 1 : (byte) 0); } public void writeByte(int v) throws IOException { write(v); } public void writeBytes(String s) throws IOException { int len = s.length(); for (int i = 0; i < len; i ++) { write((byte) s.charAt(i)); } } public void writeChar(int v) throws IOException { writeShort((short) v); } public void writeChars(String s) throws IOException { int len = s.length(); for (int i = 0 ; i < len ; i ++) { writeChar(s.charAt(i)); } } public void writeDouble(double v) throws IOException { writeLong(Double.doubleToLongBits(v)); } public void writeFloat(float v) throws IOException { writeInt(Float.floatToIntBits(v)); } public void writeInt(int v) throws IOException { buffer.writeInt(v); } public void writeLong(long v) throws IOException { buffer.writeLong(v); } public void writeShort(int v) throws IOException { buffer.writeShort((short) v); } public void writeUTF(String s) throws IOException { utf8out.writeUTF(s); } /** * Returns the buffer where this stream is writing data. */ public ChannelBuffer buffer() { return buffer; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/BigEndianHeapChannelBuffer.java0000644000175000017500000001144611117154322031751 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.nio.ByteOrder; /** * A big-endian Java heap buffer. It is recommended to use {@link ChannelBuffers#buffer(int)} * and {@link ChannelBuffers#wrappedBuffer(byte[])} instead of calling the * constructor explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 592 $, $Date: 2008-12-08 00:20:34 -0800 (Mon, 08 Dec 2008) $ */ public class BigEndianHeapChannelBuffer extends HeapChannelBuffer { /** * Creates a new big-endian heap buffer with a newly allocated byte array. * * @param length the length of the new byte array */ public BigEndianHeapChannelBuffer(int length) { super(length); } /** * Creates a new big-endian heap buffer with an existing byte array. * * @param array the byte array to wrap */ public BigEndianHeapChannelBuffer(byte[] array) { super(array); } private BigEndianHeapChannelBuffer(byte[] array, int readerIndex, int writerIndex) { super(array, readerIndex, writerIndex); } public ChannelBufferFactory factory() { return HeapChannelBufferFactory.getInstance(ByteOrder.BIG_ENDIAN); } public ByteOrder order() { return ByteOrder.BIG_ENDIAN; } public short getShort(int index) { return (short) (array[index] << 8 | array[index+1] & 0xFF); } public int getUnsignedMedium(int index) { return (array[index] & 0xff) << 16 | (array[index+1] & 0xff) << 8 | (array[index+2] & 0xff) << 0; } public int getInt(int index) { return (array[index] & 0xff) << 24 | (array[index+1] & 0xff) << 16 | (array[index+2] & 0xff) << 8 | (array[index+3] & 0xff) << 0; } public long getLong(int index) { return ((long) array[index] & 0xff) << 56 | ((long) array[index+1] & 0xff) << 48 | ((long) array[index+2] & 0xff) << 40 | ((long) array[index+3] & 0xff) << 32 | ((long) array[index+4] & 0xff) << 24 | ((long) array[index+5] & 0xff) << 16 | ((long) array[index+6] & 0xff) << 8 | ((long) array[index+7] & 0xff) << 0; } public void setShort(int index, short value) { array[index ] = (byte) (value >>> 8); array[index+1] = (byte) (value >>> 0); } public void setMedium(int index, int value) { array[index ] = (byte) (value >>> 16); array[index+1] = (byte) (value >>> 8); array[index+2] = (byte) (value >>> 0); } public void setInt(int index, int value) { array[index ] = (byte) (value >>> 24); array[index+1] = (byte) (value >>> 16); array[index+2] = (byte) (value >>> 8); array[index+3] = (byte) (value >>> 0); } public void setLong(int index, long value) { array[index ] = (byte) (value >>> 56); array[index+1] = (byte) (value >>> 48); array[index+2] = (byte) (value >>> 40); array[index+3] = (byte) (value >>> 32); array[index+4] = (byte) (value >>> 24); array[index+5] = (byte) (value >>> 16); array[index+6] = (byte) (value >>> 8); array[index+7] = (byte) (value >>> 0); } public ChannelBuffer duplicate() { return new BigEndianHeapChannelBuffer(array, readerIndex(), writerIndex()); } public ChannelBuffer copy(int index, int length) { if (index < 0 || length < 0 || index + length > array.length) { throw new IndexOutOfBoundsException(); } byte[] copiedArray = new byte[length]; System.arraycopy(array, index, copiedArray, 0, length); return new BigEndianHeapChannelBuffer(copiedArray); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/AbstractChannelBufferFactory.java0000644000175000017500000000431411117154322032422 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.nio.ByteOrder; /** * A skeletal implementation of {@link ChannelBufferFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 592 $, $Date: 2008-12-08 00:20:34 -0800 (Mon, 08 Dec 2008) $ */ public abstract class AbstractChannelBufferFactory implements ChannelBufferFactory { private final ByteOrder defaultOrder; /** * Creates a new factory whose default {@link ByteOrder} is * {@link ByteOrder#BIG_ENDIAN}. */ protected AbstractChannelBufferFactory() { this(ByteOrder.BIG_ENDIAN); } /** * Creates a new factory with the specified default {@link ByteOrder}. * * @param defaultOrder the default {@link ByteOrder} of this factory */ protected AbstractChannelBufferFactory(ByteOrder defaultOrder) { if (defaultOrder == null) { throw new NullPointerException("defaultOrder"); } this.defaultOrder = defaultOrder; } public ChannelBuffer getBuffer(int capacity) { return getBuffer(getDefaultOrder(), capacity); } public ByteOrder getDefaultOrder() { return defaultOrder; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/WrappedChannelBuffer.java0000644000175000017500000000304111107226261030726 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; /** * The common interface for buffer wrappers and derived buffers. Most users won't * need to use this interface. It is used internally in most cases. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 472 $, $Date: 2008-11-13 23:45:53 -0800 (Thu, 13 Nov 2008) $ * */ public interface WrappedChannelBuffer extends ChannelBuffer { /** * Returns this buffer's parent that this buffer is wrapping. */ ChannelBuffer unwrap(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/SlicedChannelBuffer.java0000644000175000017500000001631311117154322030534 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; /** * A derived buffer which exposes its parent's sub-region only. It is * recommended to use {@link ChannelBuffer#slice()} and * {@link ChannelBuffer#slice(int, int)} instead of calling the constructor * explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 592 $, $Date: 2008-12-08 00:20:34 -0800 (Mon, 08 Dec 2008) $ * */ public class SlicedChannelBuffer extends AbstractChannelBuffer implements WrappedChannelBuffer { private final ChannelBuffer buffer; private final int adjustment; private final int length; public SlicedChannelBuffer(ChannelBuffer buffer, int index, int length) { if (index < 0 || index > buffer.capacity()) { throw new IndexOutOfBoundsException(); } if (index + length > buffer.capacity()) { throw new IndexOutOfBoundsException(); } this.buffer = buffer; adjustment = index; this.length = length; writerIndex(length); } public ChannelBuffer unwrap() { return buffer; } public ChannelBufferFactory factory() { return buffer.factory(); } public ByteOrder order() { return buffer.order(); } public int capacity() { return length; } public byte getByte(int index) { checkIndex(index); return buffer.getByte(index + adjustment); } public short getShort(int index) { checkIndex(index, 2); return buffer.getShort(index + adjustment); } public int getUnsignedMedium(int index) { checkIndex(index, 3); return buffer.getUnsignedMedium(index + adjustment); } public int getInt(int index) { checkIndex(index, 4); return buffer.getInt(index + adjustment); } public long getLong(int index) { checkIndex(index, 8); return buffer.getLong(index + adjustment); } public ChannelBuffer duplicate() { ChannelBuffer duplicate = new SlicedChannelBuffer(buffer, adjustment, length); duplicate.setIndex(readerIndex(), writerIndex()); return duplicate; } public ChannelBuffer copy(int index, int length) { checkIndex(index, length); return buffer.copy(index + adjustment, length); } public ChannelBuffer slice(int index, int length) { checkIndex(index, length); if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } return new SlicedChannelBuffer(buffer, index + adjustment, length); } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index + adjustment, dst, dstIndex, length); } public void getBytes(int index, byte[] dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index + adjustment, dst, dstIndex, length); } public void getBytes(int index, ByteBuffer dst) { checkIndex(index, dst.remaining()); buffer.getBytes(index + adjustment, dst); } public void setByte(int index, byte value) { checkIndex(index); buffer.setByte(index + adjustment, value); } public void setShort(int index, short value) { checkIndex(index, 2); buffer.setShort(index + adjustment, value); } public void setMedium(int index, int value) { checkIndex(index, 3); buffer.setMedium(index + adjustment, value); } public void setInt(int index, int value) { checkIndex(index, 4); buffer.setInt(index + adjustment, value); } public void setLong(int index, long value) { checkIndex(index, 8); buffer.setLong(index + adjustment, value); } public void setBytes(int index, byte[] src, int srcIndex, int length) { checkIndex(index, length); buffer.setBytes(index + adjustment, src, srcIndex, length); } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { checkIndex(index, length); buffer.setBytes(index + adjustment, src, srcIndex, length); } public void setBytes(int index, ByteBuffer src) { checkIndex(index, src.remaining()); buffer.setBytes(index + adjustment, src); } public void getBytes(int index, OutputStream out, int length) throws IOException { checkIndex(index, length); buffer.getBytes(index + adjustment, out, length); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { checkIndex(index, length); return buffer.getBytes(index + adjustment, out, length); } public int setBytes(int index, InputStream in, int length) throws IOException { checkIndex(index, length); return buffer.setBytes(index + adjustment, in, length); } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { checkIndex(index, length); return buffer.setBytes(index + adjustment, in, length); } public ByteBuffer toByteBuffer(int index, int length) { checkIndex(index, length); return buffer.toByteBuffer(index + adjustment, length); } public String toString(int index, int length, String charsetName) { checkIndex(index, length); return buffer.toString(index + adjustment, length, charsetName); } private void checkIndex(int index) { if (index < 0 || index >= capacity()) { throw new IndexOutOfBoundsException(); } } private void checkIndex(int startIndex, int length) { if (length < 0) { throw new IllegalArgumentException( "length is negative: " + length); } if (startIndex < 0) { throw new IndexOutOfBoundsException(); } if (startIndex + length > capacity()) { throw new IndexOutOfBoundsException(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/AbstractChannelBuffer.java0000644000175000017500000003717311156127144031110 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.util.NoSuchElementException; /** * A skeletal implementation of a buffer. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1017 $, $Date: 2009-03-11 23:40:36 -0700 (Wed, 11 Mar 2009) $ */ public abstract class AbstractChannelBuffer implements ChannelBuffer { private int readerIndex; private int writerIndex; private int markedReaderIndex; private int markedWriterIndex; public int readerIndex() { return readerIndex; } public void readerIndex(int readerIndex) { if (readerIndex < 0 || readerIndex > writerIndex) { throw new IndexOutOfBoundsException(); } this.readerIndex = readerIndex; } public int writerIndex() { return writerIndex; } public void writerIndex(int writerIndex) { if (writerIndex < readerIndex || writerIndex > capacity()) { throw new IndexOutOfBoundsException(); } this.writerIndex = writerIndex; } public void setIndex(int readerIndex, int writerIndex) { if (readerIndex < 0 || readerIndex > writerIndex || writerIndex > capacity()) { throw new IndexOutOfBoundsException(); } this.readerIndex = readerIndex; this.writerIndex = writerIndex; } public void clear() { readerIndex = writerIndex = 0; } public boolean readable() { return readableBytes() > 0; } public boolean writable() { return writableBytes() > 0; } public int readableBytes() { return writerIndex - readerIndex; } public int writableBytes() { return capacity() - writerIndex; } public void markReaderIndex() { markedReaderIndex = readerIndex; } public void resetReaderIndex() { readerIndex(markedReaderIndex); } public void markWriterIndex() { markedWriterIndex = writerIndex; } public void resetWriterIndex() { writerIndex = markedWriterIndex; } public void discardReadBytes() { if (readerIndex == 0) { return; } setBytes(0, this, readerIndex, writerIndex - readerIndex); writerIndex -= readerIndex; markedReaderIndex = Math.max(markedReaderIndex - readerIndex, 0); markedWriterIndex = Math.max(markedWriterIndex - readerIndex, 0); readerIndex = 0; } public short getUnsignedByte(int index) { return (short) (getByte(index) & 0xFF); } public int getUnsignedShort(int index) { return getShort(index) & 0xFFFF; } public int getMedium(int index) { int value = getUnsignedMedium(index); if ((value & 0x800000) != 0) { value |= 0xff000000; } return value; } public long getUnsignedInt(int index) { return getInt(index) & 0xFFFFFFFFL; } public void getBytes(int index, byte[] dst) { getBytes(index, dst, 0, dst.length); } public void getBytes(int index, ChannelBuffer dst) { getBytes(index, dst, dst.writableBytes()); } public void getBytes(int index, ChannelBuffer dst, int length) { if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } getBytes(index, dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } public void setBytes(int index, byte[] src) { setBytes(index, src, 0, src.length); } public void setBytes(int index, ChannelBuffer src) { setBytes(index, src, src.readableBytes()); } public void setBytes(int index, ChannelBuffer src, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } setBytes(index, src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } public void setZero(int index, int length) { if (length == 0) { return; } if (length < 0) { throw new IllegalArgumentException( "length must be 0 or greater than 0."); } int nLong = length >>> 3; int nBytes = length & 7; for (int i = nLong; i > 0; i --) { setLong(index, 0); index += 8; } if (nBytes == 4) { setInt(index, 0); } else if (nBytes < 4) { for (int i = nBytes; i > 0; i --) { setByte(index, (byte) 0); index ++; } } else { setInt(index, 0); index += 4; for (int i = nBytes - 4; i > 0; i --) { setByte(index, (byte) 0); index ++; } } } public byte readByte() { if (readerIndex == writerIndex) { throw new IndexOutOfBoundsException(); } return getByte(readerIndex ++); } public short readUnsignedByte() { return (short) (readByte() & 0xFF); } public short readShort() { checkReadableBytes(2); short v = getShort(readerIndex); readerIndex += 2; return v; } public int readUnsignedShort() { return readShort() & 0xFFFF; } public int readMedium() { int value = readUnsignedMedium(); if ((value & 0x800000) != 0) { value |= 0xff000000; } return value; } public int readUnsignedMedium() { checkReadableBytes(3); int v = getUnsignedMedium(readerIndex); readerIndex += 3; return v; } public int readInt() { checkReadableBytes(4); int v = getInt(readerIndex); readerIndex += 4; return v; } public long readUnsignedInt() { return readInt() & 0xFFFFFFFFL; } public long readLong() { checkReadableBytes(8); long v = getLong(readerIndex); readerIndex += 8; return v; } public ChannelBuffer readBytes(int length) { checkReadableBytes(length); if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } ChannelBuffer buf = factory().getBuffer(order(), length); buf.writeBytes(this, readerIndex, length); readerIndex += length; return buf; } public ChannelBuffer readBytes(ChannelBufferIndexFinder endIndexFinder) { int endIndex = indexOf(readerIndex, writerIndex, endIndexFinder); if (endIndex < 0) { throw new NoSuchElementException(); } return readBytes(endIndex - readerIndex); } public ChannelBuffer readSlice(int length) { ChannelBuffer slice = slice(readerIndex, length); readerIndex += length; return slice; } public ChannelBuffer readSlice(ChannelBufferIndexFinder endIndexFinder) { int endIndex = indexOf(readerIndex, writerIndex, endIndexFinder); if (endIndex < 0) { throw new NoSuchElementException(); } return readSlice(endIndex - readerIndex); } public void readBytes(byte[] dst, int dstIndex, int length) { checkReadableBytes(length); getBytes(readerIndex, dst, dstIndex, length); readerIndex += length; } public void readBytes(byte[] dst) { readBytes(dst, 0, dst.length); } public void readBytes(ChannelBuffer dst) { readBytes(dst, dst.writableBytes()); } public void readBytes(ChannelBuffer dst, int length) { if (length > dst.writableBytes()) { throw new IndexOutOfBoundsException(); } readBytes(dst, dst.writerIndex(), length); dst.writerIndex(dst.writerIndex() + length); } public void readBytes(ChannelBuffer dst, int dstIndex, int length) { checkReadableBytes(length); getBytes(readerIndex, dst, dstIndex, length); readerIndex += length; } public void readBytes(ByteBuffer dst) { int length = dst.remaining(); checkReadableBytes(length); getBytes(readerIndex, dst); readerIndex += length; } public int readBytes(GatheringByteChannel out, int length) throws IOException { checkReadableBytes(length); int readBytes = getBytes(readerIndex, out, length); readerIndex += readBytes; return readBytes; } public void readBytes(OutputStream out, int length) throws IOException { checkReadableBytes(length); getBytes(readerIndex, out, length); readerIndex += length; } public void skipBytes(int length) { int newReaderIndex = readerIndex + length; if (newReaderIndex > writerIndex) { throw new IndexOutOfBoundsException(); } readerIndex = newReaderIndex; } public int skipBytes(ChannelBufferIndexFinder firstIndexFinder) { int oldReaderIndex = readerIndex; int newReaderIndex = indexOf(oldReaderIndex, writerIndex, firstIndexFinder); if (newReaderIndex < 0) { throw new NoSuchElementException(); } readerIndex(newReaderIndex); return newReaderIndex - oldReaderIndex; } public void writeByte(byte value) { setByte(writerIndex ++, value); } public void writeShort(short value) { setShort(writerIndex, value); writerIndex += 2; } public void writeMedium(int value) { setMedium(writerIndex, value); writerIndex += 3; } public void writeInt(int value) { setInt(writerIndex, value); writerIndex += 4; } public void writeLong(long value) { setLong(writerIndex, value); writerIndex += 8; } public void writeBytes(byte[] src, int srcIndex, int length) { setBytes(writerIndex, src, srcIndex, length); writerIndex += length; } public void writeBytes(byte[] src) { writeBytes(src, 0, src.length); } public void writeBytes(ChannelBuffer src) { writeBytes(src, src.readableBytes()); } public void writeBytes(ChannelBuffer src, int length) { if (length > src.readableBytes()) { throw new IndexOutOfBoundsException(); } writeBytes(src, src.readerIndex(), length); src.readerIndex(src.readerIndex() + length); } public void writeBytes(ChannelBuffer src, int srcIndex, int length) { setBytes(writerIndex, src, srcIndex, length); writerIndex += length; } public void writeBytes(ByteBuffer src) { int length = src.remaining(); setBytes(writerIndex, src); writerIndex += length; } public int writeBytes(InputStream in, int length) throws IOException { int writtenBytes = setBytes(writerIndex, in, length); if (writtenBytes > 0) { writerIndex += writtenBytes; } return writtenBytes; } public int writeBytes(ScatteringByteChannel in, int length) throws IOException { int writtenBytes = setBytes(writerIndex, in, length); if (writtenBytes > 0) { writerIndex += writtenBytes; } return writtenBytes; } public void writeZero(int length) { if (length == 0) { return; } if (length < 0) { throw new IllegalArgumentException( "length must be 0 or greater than 0."); } int nLong = length >>> 3; int nBytes = length & 7; for (int i = nLong; i > 0; i --) { writeLong(0); } if (nBytes == 4) { writeInt(0); } else if (nBytes < 4) { for (int i = nBytes; i > 0; i --) { writeByte((byte) 0); } } else { writeInt(0); for (int i = nBytes - 4; i > 0; i --) { writeByte((byte) 0); } } } public ChannelBuffer copy() { return copy(readerIndex, readableBytes()); } public ChannelBuffer slice() { return slice(readerIndex, readableBytes()); } public ByteBuffer toByteBuffer() { return toByteBuffer(readerIndex, readableBytes()); } public ByteBuffer[] toByteBuffers() { return toByteBuffers(readerIndex, readableBytes()); } public ByteBuffer[] toByteBuffers(int index, int length) { return new ByteBuffer[] { toByteBuffer(index, length) }; } public String toString(String charsetName) { return toString(readerIndex, readableBytes(), charsetName); } public String toString(String charsetName, ChannelBufferIndexFinder terminatorFinder) { return toString(readerIndex, readableBytes(), charsetName, terminatorFinder); } public String toString( int index, int length, String charsetName, ChannelBufferIndexFinder terminatorFinder) { if (terminatorFinder == null) { return toString(index, length, charsetName); } int terminatorIndex = indexOf(index, index + length, terminatorFinder); if (terminatorIndex < 0) { return toString(index, length, charsetName); } return toString(index, terminatorIndex - index, charsetName); } public int indexOf(int fromIndex, int toIndex, byte value) { return ChannelBuffers.indexOf(this, fromIndex, toIndex, value); } public int indexOf(int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder) { return ChannelBuffers.indexOf(this, fromIndex, toIndex, indexFinder); } @Override public int hashCode() { return ChannelBuffers.hashCode(this); } @Override public boolean equals(Object o) { if (!(o instanceof ChannelBuffer)) { return false; } return ChannelBuffers.equals(this, (ChannelBuffer) o); } public int compareTo(ChannelBuffer that) { return ChannelBuffers.compare(this, that); } @Override public String toString() { return getClass().getSimpleName() + '(' + "ridx=" + readerIndex + ", " + "widx=" + writerIndex + ", " + "cap=" + capacity() + ')'; } /** * Throws an {@link IndexOutOfBoundsException} if the current * {@linkplain #readableBytes() readable bytes} of this buffer is less * than the specified value. */ protected void checkReadableBytes(int minimumReadableBytes) { if (readableBytes() < minimumReadableBytes) { throw new IndexOutOfBoundsException(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/HeapChannelBufferFactory.java0000644000175000017500000000567111117154322031543 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.nio.ByteOrder; /** * A {@link ChannelBufferFactory} which merely allocates a heap buffer with * the specified capacity. {@link HeapChannelBufferFactory} should perform * very well in most situations because it relies on the JVM garbage collector, * which is highly optimized for heap allocation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 592 $, $Date: 2008-12-08 00:20:34 -0800 (Mon, 08 Dec 2008) $ */ public class HeapChannelBufferFactory extends AbstractChannelBufferFactory { private static final HeapChannelBufferFactory INSTANCE_BE = new HeapChannelBufferFactory(ByteOrder.BIG_ENDIAN); private static final HeapChannelBufferFactory INSTANCE_LE = new HeapChannelBufferFactory(ByteOrder.LITTLE_ENDIAN); public static ChannelBufferFactory getInstance() { return INSTANCE_BE; } public static ChannelBufferFactory getInstance(ByteOrder endianness) { if (endianness == ByteOrder.BIG_ENDIAN) { return INSTANCE_BE; } else if (endianness == ByteOrder.LITTLE_ENDIAN) { return INSTANCE_LE; } else if (endianness == null) { throw new NullPointerException("endianness"); } else { throw new IllegalStateException("Should not reach here"); } } /** * Creates a new factory whose default {@link ByteOrder} is * {@link ByteOrder#BIG_ENDIAN}. */ public HeapChannelBufferFactory() { super(); } /** * Creates a new factory with the specified default {@link ByteOrder}. * * @param defaultOrder the default {@link ByteOrder} of this factory */ public HeapChannelBufferFactory(ByteOrder defaultOrder) { super(defaultOrder); } public ChannelBuffer getBuffer(ByteOrder order, int capacity) { return ChannelBuffers.buffer(order, capacity); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ChannelBufferFactory.java0000644000175000017500000000515411216122405030736 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.nio.ByteOrder; /** * A factory that creates or pools {@link ChannelBuffer}s. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1400 $, $Date: 2009-06-17 01:10:45 -0700 (Wed, 17 Jun 2009) $ */ public interface ChannelBufferFactory { /** * Returns a {@link ChannelBuffer} with the specified {@code capacity}. * This method is identical to {@code getBuffer(getDefaultOrder(), capacity)}. * * @param capacity the capacity of the returned {@link ChannelBuffer} * @return a {@link ChannelBuffer} with the specified {@code capacity}, * whose {@code readerIndex} and {@code writerIndex} are {@code 0} */ ChannelBuffer getBuffer(int capacity); /** * Returns a {@link ChannelBuffer} with the specified {@code endianness} * and {@code capacity}. * * @param endianness the endianness of the returned {@link ChannelBuffer} * @param capacity the capacity of the returned {@link ChannelBuffer} * @return a {@link ChannelBuffer} with the specified {@code endianness} and * {@code capacity}, whose {@code readerIndex} and {@code writerIndex} * are {@code 0} */ ChannelBuffer getBuffer(ByteOrder endianness, int capacity); /** * Returns the default endianness of the {@link ChannelBuffer} which is * returned by {@link #getBuffer(int)}. * * @return the default endianness of the {@link ChannelBuffer} which is * returned by {@link #getBuffer(int)} */ ByteOrder getDefaultOrder(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/DirectChannelBufferFactory.java0000644000175000017500000001666411145211131032075 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.lang.ref.ReferenceQueue; import java.nio.ByteOrder; /** * A {@link ChannelBufferFactory} which pre-allocates a large chunk of direct * buffer and returns its slice on demand. Direct buffers are reclaimed via * {@link ReferenceQueue} in most JDK implementations, and therefore they are * deallocated less efficiently than an ordinary heap buffer. Consequently, * a user will get {@link OutOfMemoryError} when one tries to allocate small * direct buffers more often than the GC throughput of direct buffers, which * is much lower than the GC throughput of heap buffers. This factory avoids * this problem by allocating a large chunk of pre-allocated direct buffer and * reducing the number of the garbage collected internal direct buffer objects. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 877 $, $Date: 2009-02-12 22:25:29 -0800 (Thu, 12 Feb 2009) $ */ public class DirectChannelBufferFactory extends AbstractChannelBufferFactory { private static final DirectChannelBufferFactory INSTANCE_BE = new DirectChannelBufferFactory(ByteOrder.BIG_ENDIAN); private static final DirectChannelBufferFactory INSTANCE_LE = new DirectChannelBufferFactory(ByteOrder.LITTLE_ENDIAN); public static ChannelBufferFactory getInstance() { return INSTANCE_BE; } public static ChannelBufferFactory getInstance(ByteOrder defaultEndianness) { if (defaultEndianness == ByteOrder.BIG_ENDIAN) { return INSTANCE_BE; } else if (defaultEndianness == ByteOrder.LITTLE_ENDIAN) { return INSTANCE_LE; } else if (defaultEndianness == null) { throw new NullPointerException("defaultEndianness"); } else { throw new IllegalStateException("Should not reach here"); } } private final Object bigEndianLock = new Object(); private final Object littleEndianLock = new Object(); private final int preallocatedBufferCapacity; private ChannelBuffer preallocatedBigEndianBuffer = null; private int preallocatedBigEndianBufferPosition; private ChannelBuffer preallocatedLittleEndianBuffer = null; private int preallocatedLittleEndianBufferPosition; /** * Creates a new factory whose default {@link ByteOrder} is * {@link ByteOrder#BIG_ENDIAN}. */ public DirectChannelBufferFactory() { this(ByteOrder.BIG_ENDIAN); } /** * Creates a new factory whose default {@link ByteOrder} is * {@link ByteOrder#BIG_ENDIAN}. */ public DirectChannelBufferFactory(int preallocatedBufferCapacity) { this(ByteOrder.BIG_ENDIAN, preallocatedBufferCapacity); } /** * Creates a new factory with the specified default {@link ByteOrder}. * * @param defaultOrder the default {@link ByteOrder} of this factory */ public DirectChannelBufferFactory(ByteOrder defaultOrder) { this(defaultOrder, 1048576); } /** * Creates a new factory with the specified default {@link ByteOrder}. * * @param defaultOrder the default {@link ByteOrder} of this factory */ public DirectChannelBufferFactory(ByteOrder defaultOrder, int preallocatedBufferCapacity) { super(defaultOrder); if (preallocatedBufferCapacity <= 0) { throw new IllegalArgumentException( "preallocatedBufferCapacity must be greater than 0: " + preallocatedBufferCapacity); } this.preallocatedBufferCapacity = preallocatedBufferCapacity; } public ChannelBuffer getBuffer(ByteOrder order, int capacity) { if (order == null) { throw new NullPointerException("order"); } if (capacity < 0) { throw new IllegalArgumentException("capacity: " + capacity); } if (capacity == 0) { return ChannelBuffers.EMPTY_BUFFER; } if (capacity >= preallocatedBufferCapacity) { return ChannelBuffers.directBuffer(order, capacity); } ChannelBuffer slice; if (order == ByteOrder.BIG_ENDIAN) { slice = allocateBigEndianBuffer(capacity); } else { slice = allocateLittleEndianBuffer(capacity); } slice.clear(); return slice; } private ChannelBuffer allocateBigEndianBuffer(int capacity) { ChannelBuffer slice; synchronized (bigEndianLock) { if (preallocatedBigEndianBuffer == null) { preallocatedBigEndianBuffer = ChannelBuffers.directBuffer(ByteOrder.BIG_ENDIAN, preallocatedBufferCapacity); slice = preallocatedBigEndianBuffer.slice(0, capacity); preallocatedBigEndianBufferPosition = capacity; } else if (preallocatedBigEndianBuffer.capacity() - preallocatedBigEndianBufferPosition >= capacity) { slice = preallocatedBigEndianBuffer.slice(preallocatedBigEndianBufferPosition, capacity); preallocatedBigEndianBufferPosition += capacity; } else { preallocatedBigEndianBuffer = ChannelBuffers.directBuffer(ByteOrder.BIG_ENDIAN, preallocatedBufferCapacity); slice = preallocatedBigEndianBuffer.slice(0, capacity); preallocatedBigEndianBufferPosition = capacity; } } return slice; } private synchronized ChannelBuffer allocateLittleEndianBuffer(int capacity) { ChannelBuffer slice; synchronized (littleEndianLock) { if (preallocatedLittleEndianBuffer == null) { preallocatedLittleEndianBuffer = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, preallocatedBufferCapacity); slice = preallocatedLittleEndianBuffer.slice(0, capacity); preallocatedLittleEndianBufferPosition = capacity; } else if (preallocatedLittleEndianBuffer.capacity() - preallocatedLittleEndianBufferPosition >= capacity) { slice = preallocatedLittleEndianBuffer.slice(preallocatedLittleEndianBufferPosition, capacity); preallocatedLittleEndianBufferPosition += capacity; } else { preallocatedLittleEndianBuffer = ChannelBuffers.directBuffer(ByteOrder.LITTLE_ENDIAN, preallocatedBufferCapacity); slice = preallocatedLittleEndianBuffer.slice(0, capacity); preallocatedLittleEndianBufferPosition = capacity; } } return slice; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/TruncatedChannelBuffer.java0000644000175000017500000001514111117154322031260 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; /** * A derived buffer which hides its parent's tail data beyond a certain index. * It is recommended to use {@link ChannelBuffer#slice()} and * {@link ChannelBuffer#slice(int, int)} instead of calling the constructor * explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 592 $, $Date: 2008-12-08 00:20:34 -0800 (Mon, 08 Dec 2008) $ * */ public class TruncatedChannelBuffer extends AbstractChannelBuffer implements WrappedChannelBuffer { private final ChannelBuffer buffer; private final int length; public TruncatedChannelBuffer(ChannelBuffer buffer, int length) { if (length > buffer.capacity()) { throw new IndexOutOfBoundsException(); } this.buffer = buffer; this.length = length; writerIndex(length); } public ChannelBuffer unwrap() { return buffer; } public ChannelBufferFactory factory() { return buffer.factory(); } public ByteOrder order() { return buffer.order(); } public int capacity() { return length; } public byte getByte(int index) { checkIndex(index); return buffer.getByte(index); } public short getShort(int index) { checkIndex(index, 2); return buffer.getShort(index); } public int getUnsignedMedium(int index) { checkIndex(index, 3); return buffer.getUnsignedMedium(index); } public int getInt(int index) { checkIndex(index, 4); return buffer.getInt(index); } public long getLong(int index) { checkIndex(index, 8); return buffer.getLong(index); } public ChannelBuffer duplicate() { ChannelBuffer duplicate = new TruncatedChannelBuffer(buffer, length); duplicate.setIndex(readerIndex(), writerIndex()); return duplicate; } public ChannelBuffer copy(int index, int length) { checkIndex(index, length); return buffer.copy(index, length); } public ChannelBuffer slice(int index, int length) { checkIndex(index, length); if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } return buffer.slice(index, length); } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, byte[] dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, ByteBuffer dst) { checkIndex(index, dst.remaining()); buffer.getBytes(index, dst); } public void setByte(int index, byte value) { checkIndex(index); buffer.setByte(index, value); } public void setShort(int index, short value) { checkIndex(index, 2); buffer.setShort(index, value); } public void setMedium(int index, int value) { checkIndex(index, 3); buffer.setMedium(index, value); } public void setInt(int index, int value) { checkIndex(index, 4); buffer.setInt(index, value); } public void setLong(int index, long value) { checkIndex(index, 8); buffer.setLong(index, value); } public void setBytes(int index, byte[] src, int srcIndex, int length) { checkIndex(index, length); buffer.setBytes(index, src, srcIndex, length); } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { checkIndex(index, length); buffer.setBytes(index, src, srcIndex, length); } public void setBytes(int index, ByteBuffer src) { checkIndex(index, src.remaining()); buffer.setBytes(index, src); } public void getBytes(int index, OutputStream out, int length) throws IOException { checkIndex(index, length); buffer.getBytes(index, out, length); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { checkIndex(index, length); return buffer.getBytes(index, out, length); } public int setBytes(int index, InputStream in, int length) throws IOException { checkIndex(index, length); return buffer.setBytes(index, in, length); } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { checkIndex(index, length); return buffer.setBytes(index, in, length); } public ByteBuffer toByteBuffer(int index, int length) { checkIndex(index, length); return buffer.toByteBuffer(index, length); } public String toString(int index, int length, String charsetName) { checkIndex(index, length); return buffer.toString(index, length, charsetName); } private void checkIndex(int index) { if (index < 0 || index >= capacity()) { throw new IndexOutOfBoundsException(); } } private void checkIndex(int index, int length) { if (length < 0) { throw new IllegalArgumentException( "length is negative: " + length); } if (index + length > capacity()) { throw new IndexOutOfBoundsException(); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/LittleEndianHeapChannelBuffer.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/LittleEndianHeapChannelBuffer.java0000644000175000017500000001151611117154322032503 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.nio.ByteOrder; /** * A little-endian Java heap buffer. It is recommended to use {@link ChannelBuffers#buffer(ByteOrder, int)} * and {@link ChannelBuffers#wrappedBuffer(ByteOrder, byte[])} instead of * calling the constructor explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 592 $, $Date: 2008-12-08 00:20:34 -0800 (Mon, 08 Dec 2008) $ */ public class LittleEndianHeapChannelBuffer extends HeapChannelBuffer { /** * Creates a new little-endian heap buffer with a newly allocated byte array. * * @param length the length of the new byte array */ public LittleEndianHeapChannelBuffer(int length) { super(length); } /** * Creates a new little-endian heap buffer with an existing byte array. * * @param array the byte array to wrap */ public LittleEndianHeapChannelBuffer(byte[] array) { super(array); } private LittleEndianHeapChannelBuffer(byte[] array, int readerIndex, int writerIndex) { super(array, readerIndex, writerIndex); } public ChannelBufferFactory factory() { return HeapChannelBufferFactory.getInstance(ByteOrder.LITTLE_ENDIAN); } public ByteOrder order() { return ByteOrder.LITTLE_ENDIAN; } public short getShort(int index) { return (short) (array[index] & 0xFF | array[index+1] << 8); } public int getUnsignedMedium(int index) { return (array[index ] & 0xff) << 0 | (array[index+1] & 0xff) << 8 | (array[index+2] & 0xff) << 16; } public int getInt(int index) { return (array[index ] & 0xff) << 0 | (array[index+1] & 0xff) << 8 | (array[index+2] & 0xff) << 16 | (array[index+3] & 0xff) << 24; } public long getLong(int index) { return ((long) array[index] & 0xff) << 0 | ((long) array[index+1] & 0xff) << 8 | ((long) array[index+2] & 0xff) << 16 | ((long) array[index+3] & 0xff) << 24 | ((long) array[index+4] & 0xff) << 32 | ((long) array[index+5] & 0xff) << 40 | ((long) array[index+6] & 0xff) << 48 | ((long) array[index+7] & 0xff) << 56; } public void setShort(int index, short value) { array[index ] = (byte) (value >>> 0); array[index+1] = (byte) (value >>> 8); } public void setMedium(int index, int value) { array[index ] = (byte) (value >>> 0); array[index+1] = (byte) (value >>> 8); array[index+2] = (byte) (value >>> 16); } public void setInt(int index, int value) { array[index ] = (byte) (value >>> 0); array[index+1] = (byte) (value >>> 8); array[index+2] = (byte) (value >>> 16); array[index+3] = (byte) (value >>> 24); } public void setLong(int index, long value) { array[index ] = (byte) (value >>> 0); array[index+1] = (byte) (value >>> 8); array[index+2] = (byte) (value >>> 16); array[index+3] = (byte) (value >>> 24); array[index+4] = (byte) (value >>> 32); array[index+5] = (byte) (value >>> 40); array[index+6] = (byte) (value >>> 48); array[index+7] = (byte) (value >>> 56); } public ChannelBuffer duplicate() { return new LittleEndianHeapChannelBuffer(array, readerIndex(), writerIndex()); } public ChannelBuffer copy(int index, int length) { if (index < 0 || length < 0 || index + length > array.length) { throw new IndexOutOfBoundsException(); } byte[] copiedArray = new byte[length]; System.arraycopy(array, index, copiedArray, 0, length); return new LittleEndianHeapChannelBuffer(copiedArray); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/package-info.java0000644000175000017500000001520011175564104027233 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Abstraction of a byte buffer - the fundamental data structure * to represent a low-level binary and text message. * * Netty uses its own buffer API instead of NIO {@link java.nio.ByteBuffer} to * represent a sequence of bytes. This approach has significant advantage over * using {@link java.nio.ByteBuffer}. Netty's new buffer type, * {@link org.jboss.netty.buffer.ChannelBuffer}, has been designed from ground * up to address the problems of {@link java.nio.ByteBuffer} and to meet the * daily needs of network application developers. To list a few cool features: *

    *
  • You can define your buffer type if necessary.
  • *
  • Transparent zero copy is achieved by built-in composite buffer type.
  • *
  • A dynamic buffer type is provided out-of-the-box, whose capacity is * expanded on demand, just like {@link java.lang.StringBuffer}.
  • *
  • There's no need to call the {@code flip()} method anymore.
  • *
  • It is often faster than {@link java.nio.ByteBuffer}.
  • *
* *

Extensibility

* * {@link org.jboss.netty.buffer.ChannelBuffer} has rich set of operations * optimized for rapid protocol implementation. For example, * {@link org.jboss.netty.buffer.ChannelBuffer} provides various operations * for accessing unsigned values and strings and searching for certain byte * sequence in a buffer. You can also extend or wrap existing buffer type * to add convenient accessors. The custom buffer type still implements * {@link org.jboss.netty.buffer.ChannelBuffer} interface rather than * introducing an incompatible type. * *

Transparent Zero Copy

* * To lift up the performance of a network application to the extreme, you need * to reduce the number of memory copy operation. You might have a set of * buffers that could be sliced and combined to compose a whole message. Netty * provides a composite buffer which allows you to create a new buffer from the * arbitrary number of existing buffers with no memory copy. For example, a * message could be composed of two parts; header and body. In a modularized * application, the two parts could be produced by different modules and * assembled later when the message is sent out. *
 * +--------+----------+
 * | header |   body   |
 * +--------+----------+
 * 
* If {@link java.nio.ByteBuffer} were used, you would have to create a new big * buffer and copy the two parts into the new buffer. Alternatively, you can * perform a gathering write operation in NIO, but it restricts you to represent * the composite of buffers as an array of {@link java.nio.ByteBuffer}s rather * than a single buffer, breaking the abstraction and introducing complicated * state management. Moreover, it's of no use if you are not going to read or * write from an NIO channel. *
 * // The composite type is incompatible with the component type.
 * ByteBuffer[] message = new ByteBuffer[] { header, body };
 * 
* By contrast, {@link org.jboss.netty.buffer.ChannelBuffer} does not have such * caveats because it is fully extensible and has a built-in composite buffer * type. *
 * // The composite type is compatible with the component type.
 * ChannelBuffer message = ChannelBuffers.wrappedBuffer(header, body);
 *
 * // Therefore, you can even create a composite by mixing a composite and an
 * // ordinary buffer.
 * ChannelBuffer messageWithFooter = ChannelBuffers.wrappedBuffer(message, footer);
 *
 * // Because the composite is still a ChannelBuffer, you can access its content
 * // easily, and the accessor method will behave just like it's a single buffer
 * // even if the region you want to access spans over multiple components.  The
 * // unsigned integer being read here is located across body and footer.
 * messageWithFooter.getUnsignedInt(
 *     messageWithFooter.readableBytes() - footer.readableBytes() - 1);
 * 
* *

Automatic Capacity Extension

* * Many protocols define variable length messages, which means there's no way to * determine the length of a message until you construct the message or it is * difficult and inconvenient to calculate the length precisely. It is just * like when you build a {@link java.lang.String}. You often estimate the length * of the resulting string and let {@link java.lang.StringBuffer} expand itself * on demand. Netty allows you to do the same via a dynamic buffer * which is created by the * {@link org.jboss.netty.buffer.ChannelBuffers#dynamicBuffer()} method. *
 * // A new dynamic buffer is created.  Internally, the actual buffer is created
 * // lazily to avoid potentially wasted memory space.
 * ChannelBuffer b = ChannelBuffers.dynamicBuffer(4);
 *
 * // When the first write attempt is made, the internal buffer is created with
 * // the specified initial capacity (4).
 * b.writeByte('1');
 *
 * b.writeByte('2');
 * b.writeByte('3');
 * b.writeByte('4');
 *
 * // When the number of written bytes exceeds the initial capacity (4), the
 * // internal buffer is reallocated automatically with a larger capacity.
 * b.writeByte('5');
 * 
* *

Better Performance

* * Most frequently used buffer implementation of * {@link org.jboss.netty.buffer.ChannelBuffer} is a very thin wrapper of a * byte array (i.e. {@code byte[]}). Unlike {@link java.nio.ByteBuffer}, it has * no complicated boundary check and index compensation, and therefore it is * easier for a JVM to optimize the buffer access. More complicated buffer * implementation is used only for sliced or composite buffers, and it performs * as well as {@link java.nio.ByteBuffer}. * * @apiviz.landmark * @apiviz.exclude ^java\.io\.[^\.]+Stream$ */ package org.jboss.netty.buffer;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/CompositeChannelBuffer.java0000644000175000017500000004704711215363236031310 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.List; /** * A virtual buffer which shows multiple buffers as a single merged buffer. It * is recommended to use {@link ChannelBuffers#wrappedBuffer(ChannelBuffer...)} * instead of calling the constructor explicitly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1362 $, $Date: 2009-06-14 23:13:50 -0700 (Sun, 14 Jun 2009) $ * */ public class CompositeChannelBuffer extends AbstractChannelBuffer { private final ChannelBuffer[] slices; private final ByteOrder order; private final int[] indices; private int lastSliceId; public CompositeChannelBuffer(ChannelBuffer... buffers) { if (buffers.length == 0) { throw new IllegalArgumentException("buffers should not be empty."); } ByteOrder expectedEndianness = null; for (ChannelBuffer buffer : buffers) { if (buffer.capacity() != 0) { expectedEndianness = buffer.order(); } } if (expectedEndianness == null) { throw new IllegalArgumentException("buffers have only empty buffers."); } order = expectedEndianness; slices = new ChannelBuffer[buffers.length]; for (int i = 0; i < buffers.length; i ++) { if (buffers[i].capacity() != 0 && buffers[i].order() != expectedEndianness) { throw new IllegalArgumentException( "All buffers must have the same endianness."); } slices[i] = buffers[i].slice(); } indices = new int[buffers.length + 1]; for (int i = 1; i <= buffers.length; i ++) { indices[i] = indices[i - 1] + slices[i - 1].capacity(); } writerIndex(capacity()); } private CompositeChannelBuffer(CompositeChannelBuffer buffer) { order = buffer.order; slices = buffer.slices.clone(); indices = buffer.indices.clone(); setIndex(buffer.readerIndex(), buffer.writerIndex()); } public ChannelBufferFactory factory() { return HeapChannelBufferFactory.getInstance(order()); } public ByteOrder order() { return order; } public int capacity() { return indices[slices.length]; } public byte getByte(int index) { int sliceId = sliceId(index); return slices[sliceId].getByte(index - indices[sliceId]); } public short getShort(int index) { int sliceId = sliceId(index); if (index + 2 <= indices[sliceId + 1]) { return slices[sliceId].getShort(index - indices[sliceId]); } else if (order() == ByteOrder.BIG_ENDIAN) { return (short) ((getByte(index) & 0xff) << 8 | getByte(index + 1) & 0xff); } else { return (short) (getByte(index) & 0xff | (getByte(index + 1) & 0xff) << 8); } } public int getUnsignedMedium(int index) { int sliceId = sliceId(index); if (index + 3 <= indices[sliceId + 1]) { return slices[sliceId].getUnsignedMedium(index - indices[sliceId]); } else if (order() == ByteOrder.BIG_ENDIAN) { return (getShort(index) & 0xffff) << 8 | getByte(index + 2) & 0xff; } else { return getShort(index) & 0xFFFF | (getByte(index + 2) & 0xFF) << 16; } } public int getInt(int index) { int sliceId = sliceId(index); if (index + 4 <= indices[sliceId + 1]) { return slices[sliceId].getInt(index - indices[sliceId]); } else if (order() == ByteOrder.BIG_ENDIAN) { return (getShort(index) & 0xffff) << 16 | getShort(index + 2) & 0xffff; } else { return getShort(index) & 0xFFFF | (getShort(index + 2) & 0xFFFF) << 16; } } public long getLong(int index) { int sliceId = sliceId(index); if (index + 8 <= indices[sliceId + 1]) { return slices[sliceId].getLong(index - indices[sliceId]); } else if (order() == ByteOrder.BIG_ENDIAN) { return (getInt(index) & 0xffffffffL) << 32 | getInt(index + 4) & 0xffffffffL; } else { return getInt(index) & 0xFFFFFFFFL | (getInt(index + 4) & 0xFFFFFFFFL) << 32; } } public void getBytes(int index, byte[] dst, int dstIndex, int length) { int sliceId = sliceId(index); if (index > capacity() - length || dstIndex > dst.length - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.getBytes(index - adjustment, dst, dstIndex, localLength); index += localLength; dstIndex += localLength; length -= localLength; i ++; } } public void getBytes(int index, ByteBuffer dst) { int sliceId = sliceId(index); int limit = dst.limit(); int length = dst.remaining(); if (index > capacity() - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; try { while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); dst.limit(dst.position() + localLength); s.getBytes(index - adjustment, dst); index += localLength; length -= localLength; i ++; } } finally { dst.limit(limit); } } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { int sliceId = sliceId(index); if (index > capacity() - length || dstIndex > dst.capacity() - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.getBytes(index - adjustment, dst, dstIndex, localLength); index += localLength; dstIndex += localLength; length -= localLength; i ++; } } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { // XXX Gathering write is not supported because of a known issue. // See http://bugs.sun.com/view_bug.do?bug_id=6210541 // This issue appeared in 2004 and is still unresolved!? return out.write(toByteBuffer(index, length)); } public void getBytes(int index, OutputStream out, int length) throws IOException { int sliceId = sliceId(index); if (index > capacity() - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.getBytes(index - adjustment, out, localLength); index += localLength; length -= localLength; i ++; } } public void setByte(int index, byte value) { int sliceId = sliceId(index); slices[sliceId].setByte(index - indices[sliceId], value); } public void setShort(int index, short value) { int sliceId = sliceId(index); if (index + 2 <= indices[sliceId + 1]) { slices[sliceId].setShort(index - indices[sliceId], value); } else if (order() == ByteOrder.BIG_ENDIAN) { setByte(index, (byte) (value >>> 8)); setByte(index + 1, (byte) value); } else { setByte(index , (byte) value); setByte(index + 1, (byte) (value >>> 8)); } } public void setMedium(int index, int value) { int sliceId = sliceId(index); if (index + 3 <= indices[sliceId + 1]) { slices[sliceId].setMedium(index - indices[sliceId], value); } else if (order() == ByteOrder.BIG_ENDIAN) { setShort(index, (short) (value >> 8)); setByte(index + 2, (byte) value); } else { setShort(index , (short) value); setByte (index + 2, (byte) (value >>> 16)); } } public void setInt(int index, int value) { int sliceId = sliceId(index); if (index + 4 <= indices[sliceId + 1]) { slices[sliceId].setInt(index - indices[sliceId], value); } else if (order() == ByteOrder.BIG_ENDIAN) { setShort(index, (short) (value >>> 16)); setShort(index + 2, (short) value); } else { setShort(index , (short) value); setShort(index + 2, (short) (value >>> 16)); } } public void setLong(int index, long value) { int sliceId = sliceId(index); if (index + 8 <= indices[sliceId + 1]) { slices[sliceId].setLong(index - indices[sliceId], value); } else if (order() == ByteOrder.BIG_ENDIAN) { setInt(index, (int) (value >>> 32)); setInt(index + 4, (int) value); } else { setInt(index , (int) value); setInt(index + 4, (int) (value >>> 32)); } } public void setBytes(int index, byte[] src, int srcIndex, int length) { int sliceId = sliceId(index); if (index > capacity() - length || srcIndex > src.length - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.setBytes(index - adjustment, src, srcIndex, localLength); index += localLength; srcIndex += localLength; length -= localLength; i ++; } } public void setBytes(int index, ByteBuffer src) { int sliceId = sliceId(index); int limit = src.limit(); int length = src.remaining(); if (index > capacity() - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; try { while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); src.limit(src.position() + localLength); s.setBytes(index - adjustment, src); index += localLength; length -= localLength; i ++; } } finally { src.limit(limit); } } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { int sliceId = sliceId(index); if (index > capacity() - length || srcIndex > src.capacity() - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.setBytes(index - adjustment, src, srcIndex, localLength); index += localLength; srcIndex += localLength; length -= localLength; i ++; } } public int setBytes(int index, InputStream in, int length) throws IOException { int sliceId = sliceId(index); if (index > capacity() - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; int readBytes = 0; do { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); int localReadBytes = s.setBytes(index - adjustment, in, localLength); if (localReadBytes < 0) { if (readBytes == 0) { return -1; } else { break; } } if (localReadBytes == localLength) { index += localLength; length -= localLength; readBytes += localLength; i ++; } else { index += localReadBytes; length -= localReadBytes; readBytes += localReadBytes; } } while (length > 0); return readBytes; } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { int sliceId = sliceId(index); if (index > capacity() - length) { throw new IndexOutOfBoundsException(); } int i = sliceId; int readBytes = 0; do { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); int localReadBytes = s.setBytes(index - adjustment, in, localLength); if (localReadBytes == localLength) { index += localLength; length -= localLength; readBytes += localLength; i ++; } else { index += localReadBytes; length -= localReadBytes; readBytes += localReadBytes; } } while (length > 0); return readBytes; } public ChannelBuffer duplicate() { ChannelBuffer duplicate = new CompositeChannelBuffer(this); duplicate.setIndex(readerIndex(), writerIndex()); return duplicate; } public ChannelBuffer copy(int index, int length) { int sliceId = sliceId(index); if (index > capacity() - length) { throw new IndexOutOfBoundsException(); } ChannelBuffer dst = factory().getBuffer(order(), length); copyTo(index, length, sliceId, dst); return dst; } private void copyTo(int index, int length, int sliceId, ChannelBuffer dst) { int dstIndex = 0; int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.getBytes(index - adjustment, dst, dstIndex, localLength); index += localLength; dstIndex += localLength; length -= localLength; i ++; } dst.writerIndex(dst.capacity()); } public ChannelBuffer slice(int index, int length) { if (index == 0) { if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } else { return new TruncatedChannelBuffer(this, length); } } else if (index < 0 || index > capacity() - length) { throw new IndexOutOfBoundsException(); } else if (length == 0) { return ChannelBuffers.EMPTY_BUFFER; } else { return new SlicedChannelBuffer(this, index, length); } } public ByteBuffer toByteBuffer(int index, int length) { if (slices.length == 1) { return slices[0].toByteBuffer(index, length); } ByteBuffer[] buffers = toByteBuffers(index, length); ByteBuffer merged = ByteBuffer.allocate(length).order(order()); for (ByteBuffer b: buffers) { merged.put(b); } merged.flip(); return merged; } @Override public ByteBuffer[] toByteBuffers(int index, int length) { int sliceId = sliceId(index); if (index + length > capacity()) { throw new IndexOutOfBoundsException(); } List buffers = new ArrayList(slices.length); int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); buffers.add(s.toByteBuffer(index - adjustment, localLength)); index += localLength; length -= localLength; i ++; } return buffers.toArray(new ByteBuffer[buffers.size()]); } public String toString(int index, int length, String charsetName) { int sliceId = sliceId(index); if (index + length <= indices[sliceId + 1]) { return slices[sliceId].toString( index - indices[sliceId], length, charsetName); } byte[] data = new byte[length]; int dataIndex = 0; int i = sliceId; while (length > 0) { ChannelBuffer s = slices[i]; int adjustment = indices[i]; int localLength = Math.min(length, s.capacity() - (index - adjustment)); s.getBytes(index - adjustment, data, dataIndex, localLength); index += localLength; dataIndex += localLength; length -= localLength; i ++; } try { return new String(data, charsetName); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(charsetName); } } private int sliceId(int index) { int lastSliceId = this.lastSliceId; if (index >= indices[lastSliceId]) { if (index < indices[lastSliceId + 1]) { return lastSliceId; } // Search right for (int i = lastSliceId + 1; i < slices.length; i ++) { if (index < indices[i + 1]) { this.lastSliceId = i; return i; } } } else { // Search left for (int i = lastSliceId - 1; i >= 0; i --) { if (index >= indices[i]) { this.lastSliceId = i; return i; } } } throw new IndexOutOfBoundsException(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/buffer/ChannelBuffers.java0000644000175000017500000010023411216124423027566 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.buffer; import java.io.UnsupportedEncodingException; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.UnsupportedCharsetException; /** * Creates a new {@link ChannelBuffer} by allocating new space or by wrapping * or copying existing byte arrays, byte buffers and a string. * *

Use static import

* This classes is intended to be used with Java 5 static import statement: * *
 * import static org.jboss.netty.buffer.ChannelBuffers.*;
 *
 * ChannelBuffer heapBuffer = buffer(128);
 * ChannelBuffer directBuffer = directBuffer(256);
 * ChannelBuffer dynamicBuffer = dynamicBuffer(512);
 * ChannelBuffer wrappedBuffer = wrappedBuffer(new byte[128], new byte[256]);
 * ChannelBuffer copiedBuffer = copiedBuffer(ByteBuffer.allocate(128));
 * 
* *

Allocating a new buffer

* * Three buffer types are provided out of the box. * *
    *
  • {@link #buffer(int)} allocates a new fixed-capacity heap buffer.
  • *
  • {@link #directBuffer(int)} allocates a new fixed-capacity direct buffer.
  • *
  • {@link #dynamicBuffer(int)} allocates a new dynamic-capacity heap * buffer, whose capacity increases automatically as needed by a write * operation.
  • *
* *

Creating a wrapped buffer

* * Wrapped buffer is a buffer which is a view of one or more existing * byte arrays and byte buffers. Any changes in the content of the original * array or buffer will be visible in the wrapped buffer. Various wrapper * methods are provided and their name is all {@code wrappedBuffer()}. * You might want to take a look at the methods that accept varargs closely if * you want to create a buffer which is composed of more than one array to * reduce the number of memory copy. * *

Creating a copied buffer

* * Copied buffer is a deep copy of one or more existing byte arrays, byte * buffers or a string. Unlike a wrapped buffer, there's no shared data * between the original data and the copied buffer. Various copy methods are * provided and their name is all {@code copiedBuffer()}. It is also convenient * to use this operation to merge multiple buffers into one buffer. * *

Miscellaneous utility methods

* * This class also provides various utility methods to help implementation * of a new buffer type, generation of hex dump and swapping an integer's * byte order. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1402 $, $Date: 2009-06-17 01:28:03 -0700 (Wed, 17 Jun 2009) $ * * @apiviz.landmark * @apiviz.has org.jboss.netty.buffer.ChannelBuffer oneway - - creates */ public class ChannelBuffers { /** * Big endian byte order. */ public static final ByteOrder BIG_ENDIAN = ByteOrder.BIG_ENDIAN; /** * Little endian byte order. */ public static final ByteOrder LITTLE_ENDIAN = ByteOrder.LITTLE_ENDIAN; /** * A buffer whose capacity is {@code 0}. */ public static final ChannelBuffer EMPTY_BUFFER = new BigEndianHeapChannelBuffer(0); private static final char[] HEXDUMP_TABLE = new char[256 * 4]; static { final char[] DIGITS = "0123456789abcdef".toCharArray(); for (int i = 0; i < 256; i ++) { HEXDUMP_TABLE[(i << 1) + 0] = DIGITS[i >>> 4 & 0x0F]; HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i >>> 0 & 0x0F]; } } /** * Creates a new big-endian Java heap buffer with the specified * {@code capacity}. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ChannelBuffer buffer(int capacity) { return buffer(BIG_ENDIAN, capacity); } /** * Creates a new Java heap buffer with the specified {@code endianness} * and {@code capacity}. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ChannelBuffer buffer(ByteOrder endianness, int capacity) { if (endianness == BIG_ENDIAN) { if (capacity == 0) { return EMPTY_BUFFER; } return new BigEndianHeapChannelBuffer(capacity); } else if (endianness == LITTLE_ENDIAN) { if (capacity == 0) { return EMPTY_BUFFER; } return new LittleEndianHeapChannelBuffer(capacity); } else { throw new NullPointerException("endianness"); } } /** * Creates a new big-endian direct buffer with the specified * {@code capacity}. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ChannelBuffer directBuffer(int capacity) { return directBuffer(BIG_ENDIAN, capacity); } /** * Creates a new direct buffer with the specified {@code endianness} and * {@code capacity}. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ChannelBuffer directBuffer(ByteOrder endianness, int capacity) { if (endianness == null) { throw new NullPointerException("endianness"); } if (capacity == 0) { return EMPTY_BUFFER; } ChannelBuffer buffer = new ByteBufferBackedChannelBuffer( ByteBuffer.allocateDirect(capacity).order(endianness)); buffer.clear(); return buffer; } /** * Creates a new big-endian dynamic buffer whose estimated data length is * {@code 256} bytes. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ChannelBuffer dynamicBuffer() { return dynamicBuffer(BIG_ENDIAN, 256); } public static ChannelBuffer dynamicBuffer(ChannelBufferFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } return new DynamicChannelBuffer(factory.getDefaultOrder(), 256, factory); } /** * Creates a new big-endian dynamic buffer with the specified estimated * data length. More accurate estimation yields less unexpected * reallocation overhead. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0}. */ public static ChannelBuffer dynamicBuffer(int estimatedLength) { return dynamicBuffer(BIG_ENDIAN, estimatedLength); } /** * Creates a new dynamic buffer with the specified endianness and * the specified estimated data length. More accurate estimation yields * less unexpected reallocation overhead. The new buffer's * {@code readerIndex} and {@code writerIndex} are {@code 0}. */ public static ChannelBuffer dynamicBuffer(ByteOrder endianness, int estimatedLength) { return new DynamicChannelBuffer(endianness, estimatedLength); } public static ChannelBuffer dynamicBuffer(int estimatedLength, ChannelBufferFactory factory) { if (factory == null) { throw new NullPointerException("factory"); } return new DynamicChannelBuffer(factory.getDefaultOrder(), estimatedLength, factory); } public static ChannelBuffer dynamicBuffer(ByteOrder endianness, int estimatedLength, ChannelBufferFactory factory) { return new DynamicChannelBuffer(endianness, estimatedLength, factory); } /** * Creates a new big-endian buffer which wraps the specified {@code array}. * A modification on the specified array's content will be visible to the * returned buffer. */ public static ChannelBuffer wrappedBuffer(byte[] array) { return wrappedBuffer(BIG_ENDIAN, array); } /** * Creates a new buffer which wraps the specified {@code array} with the * specified {@code endianness}. A modification on the specified array's * content will be visible to the returned buffer. */ public static ChannelBuffer wrappedBuffer(ByteOrder endianness, byte[] array) { if (endianness == BIG_ENDIAN) { if (array.length == 0) { return EMPTY_BUFFER; } return new BigEndianHeapChannelBuffer(array); } else if (endianness == LITTLE_ENDIAN) { if (array.length == 0) { return EMPTY_BUFFER; } return new LittleEndianHeapChannelBuffer(array); } else { throw new NullPointerException("endianness"); } } /** * Creates a new big-endian buffer which wraps the sub-region of the * specified {@code array}. A modification on the specified array's * content will be visible to the returned buffer. */ public static ChannelBuffer wrappedBuffer(byte[] array, int offset, int length) { return wrappedBuffer(BIG_ENDIAN, array, offset, length); } /** * Creates a new buffer which wraps the sub-region of the specified * {@code array} with the specified {@code endianness}. A modification on * the specified array's content will be visible to the returned buffer. */ public static ChannelBuffer wrappedBuffer(ByteOrder endianness, byte[] array, int offset, int length) { if (endianness == null) { throw new NullPointerException("endianness"); } if (offset == 0) { if (length == array.length) { return wrappedBuffer(endianness, array); } else { if (length == 0) { return EMPTY_BUFFER; } else { return new TruncatedChannelBuffer(wrappedBuffer(endianness, array), length); } } } else { if (length == 0) { return EMPTY_BUFFER; } else { return new SlicedChannelBuffer(wrappedBuffer(endianness, array), offset, length); } } } /** * Creates a new buffer which wraps the specified NIO buffer's current * slice. A modification on the specified buffer's content and endianness * will be visible to the returned buffer. */ public static ChannelBuffer wrappedBuffer(ByteBuffer buffer) { if (!buffer.hasRemaining()) { return EMPTY_BUFFER; } if (!buffer.isReadOnly() && buffer.hasArray()) { return wrappedBuffer(buffer.array(), buffer.arrayOffset(),buffer.remaining()); } else { return new ByteBufferBackedChannelBuffer(buffer); } } /** * Creates a new buffer which wraps the specified buffer's readable bytes. * A modification on the specified buffer's content will be visible to the * returned buffer. */ public static ChannelBuffer wrappedBuffer(ChannelBuffer buffer) { if (buffer.readable()) { return buffer.slice(); } else { return EMPTY_BUFFER; } } /** * Creates a new big-endian composite buffer which wraps the specified * arrays without copying them. A modification on the specified arrays' * content will be visible to the returned buffer. */ public static ChannelBuffer wrappedBuffer(byte[]... arrays) { return wrappedBuffer(BIG_ENDIAN, arrays); } /** * Creates a new composite buffer which wraps the specified arrays without * copying them. A modification on the specified arrays' content will be * visible to the returned buffer. * * @param endianness the endianness of the new buffer */ public static ChannelBuffer wrappedBuffer(ByteOrder endianness, byte[]... arrays) { switch (arrays.length) { case 0: break; case 1: if (arrays[0].length != 0) { return wrappedBuffer(endianness, arrays[0]); } break; default: ChannelBuffer[] wrappedBuffers = new ChannelBuffer[arrays.length]; for (int i = 0; i < arrays.length; i ++) { wrappedBuffers[i] = wrappedBuffer(endianness, arrays[i]); } return wrappedBuffer(wrappedBuffers); } return EMPTY_BUFFER; } /** * Creates a new composite buffer which wraps the specified buffers without * copying them. A modification on the specified buffers' content will be * visible to the returned buffer. * * @throws IllegalArgumentException * if the specified buffers' endianness are different from each * other */ public static ChannelBuffer wrappedBuffer(ChannelBuffer... buffers) { switch (buffers.length) { case 0: break; case 1: if (buffers[0].readable()) { return wrappedBuffer(buffers[0]); } break; default: for (ChannelBuffer b: buffers) { if (b.readable()) { return new CompositeChannelBuffer(buffers); } } } return EMPTY_BUFFER; } /** * Creates a new composite buffer which wraps the specified NIO buffers * without copying them. A modification on the specified buffers' content * will be visible to the returned buffer. * * @throws IllegalArgumentException * if the specified buffers' endianness are different from each * other */ public static ChannelBuffer wrappedBuffer(ByteBuffer... buffers) { switch (buffers.length) { case 0: break; case 1: if (buffers[0].hasRemaining()) { return wrappedBuffer(buffers[0]); } break; default: ChannelBuffer[] wrappedBuffers = new ChannelBuffer[buffers.length]; for (int i = 0; i < buffers.length; i ++) { wrappedBuffers[i] = wrappedBuffer(buffers[i]); } return wrappedBuffer(wrappedBuffers); } return EMPTY_BUFFER; } /** * Creates a new big-endian buffer whose content is a copy of the * specified {@code array}. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0} and {@code array.length} respectively. */ public static ChannelBuffer copiedBuffer(byte[] array) { return copiedBuffer(BIG_ENDIAN, array); } /** * Creates a new buffer with the specified {@code endianness} whose * content is a copy of the specified {@code array}. The new buffer's * {@code readerIndex} and {@code writerIndex} are {@code 0} and * {@code array.length} respectively. */ public static ChannelBuffer copiedBuffer(ByteOrder endianness, byte[] array) { if (endianness == BIG_ENDIAN) { if (array.length == 0) { return EMPTY_BUFFER; } return new BigEndianHeapChannelBuffer(array.clone()); } else if (endianness == LITTLE_ENDIAN) { if (array.length == 0) { return EMPTY_BUFFER; } return new LittleEndianHeapChannelBuffer(array.clone()); } else { throw new NullPointerException("endianness"); } } /** * Creates a new big-endian buffer whose content is a copy of the * specified {@code array}'s sub-region. The new buffer's * {@code readerIndex} and {@code writerIndex} are {@code 0} and * the specified {@code length} respectively. */ public static ChannelBuffer copiedBuffer(byte[] array, int offset, int length) { return copiedBuffer(BIG_ENDIAN, array, offset, length); } /** * Creates a new buffer with the specified {@code endianness} whose * content is a copy of the specified {@code array}'s sub-region. The new * buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} and * the specified {@code length} respectively. */ public static ChannelBuffer copiedBuffer(ByteOrder endianness, byte[] array, int offset, int length) { if (endianness == null) { throw new NullPointerException("endianness"); } if (length == 0) { return EMPTY_BUFFER; } byte[] copy = new byte[length]; System.arraycopy(array, offset, copy, 0, length); return wrappedBuffer(endianness, copy); } /** * Creates a new buffer whose content is a copy of the specified * {@code buffer}'s current slice. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and {@code buffer.remaining} * respectively. */ public static ChannelBuffer copiedBuffer(ByteBuffer buffer) { int length = buffer.remaining(); if (length == 0) { return EMPTY_BUFFER; } byte[] copy = new byte[length]; int position = buffer.position(); try { buffer.get(copy); } finally { buffer.position(position); } return wrappedBuffer(buffer.order(), copy); } /** * Creates a new buffer whose content is a copy of the specified * {@code buffer}'s readable bytes. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and {@code buffer.readableBytes} * respectively. */ public static ChannelBuffer copiedBuffer(ChannelBuffer buffer) { if (buffer.readable()) { return buffer.copy(); } else { return EMPTY_BUFFER; } } /** * Creates a new big-endian buffer whose content is a merged copy of * the specified {@code arrays}. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and the sum of all arrays' * {@code length} respectively. */ public static ChannelBuffer copiedBuffer(byte[]... arrays) { return copiedBuffer(BIG_ENDIAN, arrays); } /** * Creates a new buffer with the specified {@code endianness} whose * content is a merged copy of the specified {@code arrays}. The new * buffer's {@code readerIndex} and {@code writerIndex} are {@code 0} * and the sum of all arrays' {@code length} respectively. */ public static ChannelBuffer copiedBuffer(ByteOrder endianness, byte[]... arrays) { switch (arrays.length) { case 0: return EMPTY_BUFFER; case 1: if (arrays[0].length == 0) { return EMPTY_BUFFER; } else { return copiedBuffer(endianness, arrays[0]); } } // Merge the specified arrays into one array. int length = 0; for (byte[] a: arrays) { if (Integer.MAX_VALUE - length < a.length) { throw new IllegalArgumentException( "The total length of the specified arrays is too big."); } length += a.length; } if (length == 0) { return EMPTY_BUFFER; } byte[] mergedArray = new byte[length]; for (int i = 0, j = 0; i < arrays.length; i ++) { byte[] a = arrays[i]; System.arraycopy(a, 0, mergedArray, j, a.length); j += a.length; } return wrappedBuffer(endianness, mergedArray); } /** * Creates a new buffer whose content is a merged copy of the specified * {@code buffers}' readable bytes. The new buffer's {@code readerIndex} * and {@code writerIndex} are {@code 0} and the sum of all buffers' * {@code readableBytes} respectively. * * @throws IllegalArgumentException * if the specified buffers' endianness are different from each * other */ public static ChannelBuffer copiedBuffer(ChannelBuffer... buffers) { switch (buffers.length) { case 0: return EMPTY_BUFFER; case 1: return copiedBuffer(buffers[0]); } ChannelBuffer[] copiedBuffers = new ChannelBuffer[buffers.length]; for (int i = 0; i < buffers.length; i ++) { copiedBuffers[i] = copiedBuffer(buffers[i]); } return wrappedBuffer(copiedBuffers); } /** * Creates a new buffer whose content is a merged copy of the specified * {@code buffers}' slices. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0} and the sum of all buffers' * {@code remaining} respectively. * * @throws IllegalArgumentException * if the specified buffers' endianness are different from each * other */ public static ChannelBuffer copiedBuffer(ByteBuffer... buffers) { switch (buffers.length) { case 0: return EMPTY_BUFFER; case 1: return copiedBuffer(buffers[0]); } ChannelBuffer[] copiedBuffers = new ChannelBuffer[buffers.length]; for (int i = 0; i < buffers.length; i ++) { copiedBuffers[i] = copiedBuffer(buffers[i]); } return wrappedBuffer(copiedBuffers); } /** * Creates a new big-endian buffer whose content is the specified * {@code string} encoded by the specified {@code charsetName}. * The new buffer's {@code readerIndex} and {@code writerIndex} are * {@code 0} and the length of the encoded string respectively. */ public static ChannelBuffer copiedBuffer(String string, String charsetName) { return copiedBuffer(BIG_ENDIAN, string, charsetName); } /** * Creates a new buffer with the specified {@code endianness} whose * content is the specified {@code string} encoded by the specified * {@code charsetName}. The new buffer's {@code readerIndex} and * {@code writerIndex} are {@code 0} and the length of the encoded string * respectively. */ public static ChannelBuffer copiedBuffer(ByteOrder endianness, String string, String charsetName) { try { return wrappedBuffer(endianness, string.getBytes(charsetName)); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(charsetName); } } /** * Creates a read-only buffer which disallows any modification operations * on the specified {@code buffer}. The new buffer has the same * {@code readerIndex} and {@code writerIndex} with the specified * {@code buffer}. */ public static ChannelBuffer unmodifiableBuffer(ChannelBuffer buffer) { if (buffer instanceof ReadOnlyChannelBuffer) { buffer = ((ReadOnlyChannelBuffer) buffer).unwrap(); } return new ReadOnlyChannelBuffer(buffer); } /** * Returns a hex dump * of the specified buffer's readable bytes. */ public static String hexDump(ChannelBuffer buffer) { return hexDump(buffer, buffer.readerIndex(), buffer.readableBytes()); } /** * Returns a hex dump * of the specified buffer's sub-region. */ public static String hexDump(ChannelBuffer buffer, int fromIndex, int length) { if (length < 0) { throw new IllegalArgumentException("length: " + length); } if (length == 0) { return ""; } int endIndex = fromIndex + length; char[] buf = new char[length << 1]; int srcIdx = fromIndex; int dstIdx = 0; for (; srcIdx < endIndex; srcIdx ++, dstIdx += 2) { System.arraycopy( HEXDUMP_TABLE, buffer.getUnsignedByte(srcIdx) << 1, buf, dstIdx, 2); } return new String(buf); } /** * Calculates the hash code of the specified buffer. This method is * useful when implementing a new buffer type. */ public static int hashCode(ChannelBuffer buffer) { final int aLen = buffer.readableBytes(); final int intCount = aLen >>> 2; final int byteCount = aLen & 3; int hashCode = 1; int arrayIndex = buffer.readerIndex(); if (buffer.order() == BIG_ENDIAN) { for (int i = intCount; i > 0; i --) { hashCode = 31 * hashCode + buffer.getInt(arrayIndex); arrayIndex += 4; } } else { for (int i = intCount; i > 0; i --) { hashCode = 31 * hashCode + swapInt(buffer.getInt(arrayIndex)); arrayIndex += 4; } } for (int i = byteCount; i > 0; i --) { hashCode = 31 * hashCode + buffer.getByte(arrayIndex ++); } if (hashCode == 0) { hashCode = 1; } return hashCode; } /** * Returns {@code true} if and only if the two specified buffers are * identical to each other as described in {@code ChannelBuffer#equals(Object)}. * This method is useful when implementing a new buffer type. */ public static boolean equals(ChannelBuffer bufferA, ChannelBuffer bufferB) { final int aLen = bufferA.readableBytes(); if (aLen != bufferB.readableBytes()) { return false; } final int longCount = aLen >>> 3; final int byteCount = aLen & 7; int aIndex = bufferA.readerIndex(); int bIndex = bufferB.readerIndex(); if (bufferA.order() == bufferB.order()) { for (int i = longCount; i > 0; i --) { if (bufferA.getLong(aIndex) != bufferB.getLong(bIndex)) { return false; } aIndex += 8; bIndex += 8; } } else { for (int i = longCount; i > 0; i --) { if (bufferA.getLong(aIndex) != swapLong(bufferB.getLong(bIndex))) { return false; } aIndex += 8; bIndex += 8; } } for (int i = byteCount; i > 0; i --) { if (bufferA.getByte(aIndex) != bufferB.getByte(bIndex)) { return false; } aIndex ++; bIndex ++; } return true; } /** * Compares the two specified buffers as described in {@link ChannelBuffer#compareTo(ChannelBuffer)}. * This method is useful when implementing a new buffer type. */ public static int compare(ChannelBuffer bufferA, ChannelBuffer bufferB) { final int aLen = bufferA.readableBytes(); final int bLen = bufferB.readableBytes(); final int minLength = Math.min(aLen, bLen); final int uintCount = minLength >>> 2; final int byteCount = minLength & 3; int aIndex = bufferA.readerIndex(); int bIndex = bufferB.readerIndex(); if (bufferA.order() == bufferB.order()) { for (int i = uintCount; i > 0; i --) { long va = bufferA.getUnsignedInt(aIndex); long vb = bufferB.getUnsignedInt(bIndex); if (va > vb) { return 1; } else if (va < vb) { return -1; } aIndex += 4; bIndex += 4; } } else { for (int i = uintCount; i > 0; i --) { long va = bufferA.getUnsignedInt(aIndex); long vb = swapInt(bufferB.getInt(bIndex)) & 0xFFFFFFFFL; if (va > vb) { return 1; } else if (va < vb) { return -1; } aIndex += 4; bIndex += 4; } } for (int i = byteCount; i > 0; i --) { byte va = bufferA.getByte(aIndex); byte vb = bufferB.getByte(bIndex); if (va > vb) { return 1; } else if (va < vb) { return -1; } aIndex ++; bIndex ++; } return aLen - bLen; } /** * The default implementation of {@link ChannelBuffer#indexOf(int, int, byte)}. * This method is useful when implementing a new buffer type. */ public static int indexOf(ChannelBuffer buffer, int fromIndex, int toIndex, byte value) { if (fromIndex <= toIndex) { return firstIndexOf(buffer, fromIndex, toIndex, value); } else { return lastIndexOf(buffer, fromIndex, toIndex, value); } } /** * The default implementation of {@link ChannelBuffer#indexOf(int, int, ChannelBufferIndexFinder)}. * This method is useful when implementing a new buffer type. */ public static int indexOf(ChannelBuffer buffer, int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder) { if (fromIndex <= toIndex) { return firstIndexOf(buffer, fromIndex, toIndex, indexFinder); } else { return lastIndexOf(buffer, fromIndex, toIndex, indexFinder); } } /** * Toggles the endianness of the specified 16-bit short integer. */ public static short swapShort(short value) { return (short) (value << 8 | value >>> 8 & 0xff); } /** * Toggles the endianness of the specified 24-bit medium integer. */ public static int swapMedium(int value) { return value << 16 & 0xff0000 | value & 0xff00 | value >>> 16 & 0xff; } /** * Toggles the endianness of the specified 32-bit integer. */ public static int swapInt(int value) { return swapShort((short) value) << 16 | swapShort((short) (value >>> 16)) & 0xffff; } /** * Toggles the endianness of the specified 64-bit long integer. */ public static long swapLong(long value) { return (long) swapInt((int) value) << 32 | swapInt((int) (value >>> 32)) & 0xffffffffL; } private static int firstIndexOf(ChannelBuffer buffer, int fromIndex, int toIndex, byte value) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || buffer.capacity() == 0) { return -1; } for (int i = fromIndex; i < toIndex; i ++) { if (buffer.getByte(i) == value) { return i; } } return -1; } private static int lastIndexOf(ChannelBuffer buffer, int fromIndex, int toIndex, byte value) { fromIndex = Math.min(fromIndex, buffer.capacity()); if (fromIndex < 0 || buffer.capacity() == 0) { return -1; } for (int i = fromIndex - 1; i >= toIndex; i --) { if (buffer.getByte(i) == value) { return i; } } return -1; } private static int firstIndexOf(ChannelBuffer buffer, int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder) { fromIndex = Math.max(fromIndex, 0); if (fromIndex >= toIndex || buffer.capacity() == 0) { return -1; } for (int i = fromIndex; i < toIndex; i ++) { if (indexFinder.find(buffer, i)) { return i; } } return -1; } private static int lastIndexOf(ChannelBuffer buffer, int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder) { fromIndex = Math.min(fromIndex, buffer.capacity()); if (fromIndex < 0 || buffer.capacity() == 0) { return -1; } for (int i = fromIndex - 1; i >= toIndex; i --) { if (indexFinder.find(buffer, i)) { return i; } } return -1; } private ChannelBuffers() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/0000755000175000017500000000000011316313146024205 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/0000755000175000017500000000000011316313146025673 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/TimeoutException.java0000644000175000017500000000376011216671722032057 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import org.jboss.netty.channel.ChannelException; /** * A {@link TimeoutException} when no data was either read or written within a * certain period of time. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1462 $, $Date: 2009-06-19 04:17:38 -0700 (Fri, 19 Jun 2009) $ */ public class TimeoutException extends ChannelException { private static final long serialVersionUID = 4673641882869672533L; /** * Creates a new instance. */ public TimeoutException() { super(); } /** * Creates a new instance. */ public TimeoutException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public TimeoutException(String message) { super(message); } /** * Creates a new instance. */ public TimeoutException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/DefaultIdleStateEvent.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/DefaultIdleStateEvent.jav0000644000175000017500000000530111216671722032567 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import static org.jboss.netty.channel.Channels.*; import java.text.DateFormat; import java.util.Date; import java.util.Locale; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; /** * The default {@link IdleStateEvent} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev$, $Date$ */ public class DefaultIdleStateEvent implements IdleStateEvent { private final Channel channel; private final IdleState state; private final long lastActivityTimeMillis; /** * Creates a new instance. */ public DefaultIdleStateEvent( Channel channel, IdleState state, long lastActivityTimeMillis) { if (channel == null) { throw new NullPointerException("channel"); } if (state == null) { throw new NullPointerException("state"); } this.channel = channel; this.state = state; this.lastActivityTimeMillis = lastActivityTimeMillis; } public Channel getChannel() { return channel; } public ChannelFuture getFuture() { return succeededFuture(getChannel()); } public IdleState getState() { return state; } public long getLastActivityTimeMillis() { return lastActivityTimeMillis; } @Override public String toString() { return getChannel().toString() + ' ' + getState() + " since " + DateFormat.getDateTimeInstance( DateFormat.SHORT, DateFormat.SHORT, Locale.US).format( new Date(getLastActivityTimeMillis())); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/WriteTimeoutException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/WriteTimeoutException.jav0000644000175000017500000000376011216671722032731 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; /** * A {@link TimeoutException} raised by {@link WriteTimeoutHandler} when no data * was written within a certain period of time. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1462 $, $Date: 2009-06-19 04:17:38 -0700 (Fri, 19 Jun 2009) $ */ public class WriteTimeoutException extends TimeoutException { private static final long serialVersionUID = -7746685254523245218L; /** * Creates a new instance. */ public WriteTimeoutException() { super(); } /** * Creates a new instance. */ public WriteTimeoutException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public WriteTimeoutException(String message) { super(message); } /** * Creates a new instance. */ public WriteTimeoutException(Throwable cause) { super(cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/IdleState.java0000644000175000017500000000312111216671722030417 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import org.jboss.netty.channel.Channel; /** * An {@link Enum} that represents the idle state of a {@link Channel}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1462 $, $Date: 2009-06-19 04:17:38 -0700 (Fri, 19 Jun 2009) $ */ public enum IdleState { /** * No data was received for a while. */ READER_IDLE, /** * No data was sent for a while. */ WRITER_IDLE, /** * No data was either received or sent for a while. */ ALL_IDLE; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/IdleStateHandler.java0000644000175000017500000003320311216740252031714 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import static org.jboss.netty.channel.Channels.*; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.LifeCycleAwareChannelHandler; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.WriteCompletionEvent; import org.jboss.netty.util.ExternalResourceReleasable; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; /** * Triggers an {@link IdleStateEvent} when a {@link Channel} has not performed * read, write, or both operation for a while. * *

Supported idle states

* * * * * * * * * * * * * * * * *
PropertyMeaning
{@code readerIdleTime}an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE} * will be triggered when no read was performed for the specified period of * time. Specify {@code 0} to disable.
{@code writerIdleTime}an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE} * will be triggered when no write was performed for the specified period of * time. Specify {@code 0} to disable.
{@code allIdleTime}an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE} * will be triggered when neither read nor write was performed for the * specified period of time. Specify {@code 0} to disable.
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1477 $, $Date: 2009-06-19 09:45:30 -0700 (Fri, 19 Jun 2009) $ * * @see HashedWheelTimer * @see ReadTimeoutHandler * @see WriteTimeoutHandler */ @ChannelPipelineCoverage("one") public class IdleStateHandler extends SimpleChannelUpstreamHandler implements LifeCycleAwareChannelHandler, ExternalResourceReleasable { final Timer timer; final long readerIdleTimeMillis; volatile Timeout readerIdleTimeout; private volatile ReaderIdleTimeoutTask readerIdleTimeoutTask; volatile long lastReadTime; final long writerIdleTimeMillis; volatile Timeout writerIdleTimeout; private volatile WriterIdleTimeoutTask writerIdleTimeoutTask; volatile long lastWriteTime; final long allIdleTimeMillis; volatile Timeout allIdleTimeout; private volatile AllIdleTimeoutTask allIdleTimeoutTask; /** * Creates a new instance. * * @param timer * the {@link Timer} that is used to trigger the scheduled event. * The recommended {@link Timer} implementation is {@link HashedWheelTimer}. * @param readerIdleTimeSeconds * an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE} * will be triggered when no read was performed for the specified * period of time. Specify {@code 0} to disable. * @param writerIdleTimeSeconds * an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE} * will be triggered when no write was performed for the specified * period of time. Specify {@code 0} to disable. * @param allIdleTimeSeconds * an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE} * will be triggered when neither read nor write was performed for * the specified period of time. Specify {@code 0} to disable. */ public IdleStateHandler( Timer timer, int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) { this(timer, readerIdleTimeSeconds, writerIdleTimeSeconds, allIdleTimeSeconds, TimeUnit.SECONDS); } /** * Creates a new instance. * * @param timer * the {@link Timer} that is used to trigger the scheduled event. * The recommended {@link Timer} implementation is {@link HashedWheelTimer}. * @param readerIdleTime * an {@link IdleStateEvent} whose state is {@link IdleState#READER_IDLE} * will be triggered when no read was performed for the specified * period of time. Specify {@code 0} to disable. * @param writerIdleTime * an {@link IdleStateEvent} whose state is {@link IdleState#WRITER_IDLE} * will be triggered when no write was performed for the specified * period of time. Specify {@code 0} to disable. * @param allIdleTime * an {@link IdleStateEvent} whose state is {@link IdleState#ALL_IDLE} * will be triggered when neither read nor write was performed for * the specified period of time. Specify {@code 0} to disable. * @param unit * the {@link TimeUnit} of {@code readerIdleTime}, * {@code writeIdleTime}, and {@code allIdleTime} */ public IdleStateHandler( Timer timer, long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit) { if (timer == null) { throw new NullPointerException("timer"); } if (unit == null) { throw new NullPointerException("unit"); } this.timer = timer; readerIdleTimeMillis = unit.toMillis(readerIdleTime); writerIdleTimeMillis = unit.toMillis(writerIdleTime); allIdleTimeMillis = unit.toMillis(allIdleTime); } /** * Stops the {@link Timer} which was specified in the constructor of this * handler. You should not call this method if the {@link Timer} is in use * by other objects. */ public void releaseExternalResources() { timer.stop(); } public void beforeAdd(ChannelHandlerContext ctx) throws Exception { initialize(ctx); } public void afterAdd(ChannelHandlerContext ctx) throws Exception { // NOOP } public void beforeRemove(ChannelHandlerContext ctx) throws Exception { destroy(); } public void afterRemove(ChannelHandlerContext ctx) throws Exception { // NOOP } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { initialize(ctx); ctx.sendUpstream(e); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { destroy(); ctx.sendUpstream(e); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { lastReadTime = System.currentTimeMillis(); ctx.sendUpstream(e); } @Override public void writeComplete(ChannelHandlerContext ctx, WriteCompletionEvent e) throws Exception { if (e.getWrittenAmount() > 0) { lastWriteTime = System.currentTimeMillis(); } ctx.sendUpstream(e); } private void initialize(ChannelHandlerContext ctx) { lastReadTime = lastWriteTime = System.currentTimeMillis(); readerIdleTimeoutTask = new ReaderIdleTimeoutTask(ctx); writerIdleTimeoutTask = new WriterIdleTimeoutTask(ctx); allIdleTimeoutTask = new AllIdleTimeoutTask(ctx); if (readerIdleTimeMillis > 0) { readerIdleTimeout = timer.newTimeout( readerIdleTimeoutTask, readerIdleTimeMillis, TimeUnit.MILLISECONDS); } if (writerIdleTimeMillis > 0) { writerIdleTimeout = timer.newTimeout( writerIdleTimeoutTask, writerIdleTimeMillis, TimeUnit.MILLISECONDS); } if (allIdleTimeMillis > 0) { allIdleTimeout = timer.newTimeout( allIdleTimeoutTask, allIdleTimeMillis, TimeUnit.MILLISECONDS); } } private void destroy() { if (readerIdleTimeout != null) { readerIdleTimeout.cancel(); } if (writerIdleTimeout != null) { writerIdleTimeout.cancel(); } if (allIdleTimeout != null) { allIdleTimeout.cancel(); } readerIdleTimeout = null; readerIdleTimeoutTask = null; writerIdleTimeout = null; writerIdleTimeoutTask = null; allIdleTimeout = null; allIdleTimeoutTask = null; } protected void channelIdle( ChannelHandlerContext ctx, IdleState state, long lastActivityTimeMillis) throws Exception { ctx.sendUpstream(new DefaultIdleStateEvent(ctx.getChannel(), state, lastActivityTimeMillis)); } private final class ReaderIdleTimeoutTask implements TimerTask { private final ChannelHandlerContext ctx; ReaderIdleTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } public void run(Timeout timeout) throws Exception { if (timeout.isCancelled() || !ctx.getChannel().isOpen()) { return; } long currentTime = System.currentTimeMillis(); long lastReadTime = IdleStateHandler.this.lastReadTime; long nextDelay = readerIdleTimeMillis - (currentTime - lastReadTime); if (nextDelay <= 0) { // Reader is idle - set a new timeout and notify the callback. readerIdleTimeout = timer.newTimeout(this, readerIdleTimeMillis, TimeUnit.MILLISECONDS); try { channelIdle(ctx, IdleState.READER_IDLE, lastReadTime); } catch (Throwable t) { fireExceptionCaught(ctx, t); } } else { // Read occurred before the timeout - set a new timeout with shorter delay. readerIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS); } } } private final class WriterIdleTimeoutTask implements TimerTask { private final ChannelHandlerContext ctx; WriterIdleTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } public void run(Timeout timeout) throws Exception { if (timeout.isCancelled() || !ctx.getChannel().isOpen()) { return; } long currentTime = System.currentTimeMillis(); long lastWriteTime = IdleStateHandler.this.lastWriteTime; long nextDelay = writerIdleTimeMillis - (currentTime - lastWriteTime); if (nextDelay <= 0) { // Writer is idle - set a new timeout and notify the callback. writerIdleTimeout = timer.newTimeout(this, writerIdleTimeMillis, TimeUnit.MILLISECONDS); try { channelIdle(ctx, IdleState.WRITER_IDLE, lastWriteTime); } catch (Throwable t) { fireExceptionCaught(ctx, t); } } else { // Write occurred before the timeout - set a new timeout with shorter delay. writerIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS); } } } private final class AllIdleTimeoutTask implements TimerTask { private final ChannelHandlerContext ctx; AllIdleTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } public void run(Timeout timeout) throws Exception { if (timeout.isCancelled() || !ctx.getChannel().isOpen()) { return; } long currentTime = System.currentTimeMillis(); long lastIoTime = Math.max(lastReadTime, lastWriteTime); long nextDelay = allIdleTimeMillis - (currentTime - lastIoTime); if (nextDelay <= 0) { // Both reader and writer are idle - set a new timeout and // notify the callback. allIdleTimeout = timer.newTimeout(this, allIdleTimeMillis, TimeUnit.MILLISECONDS); try { channelIdle(ctx, IdleState.ALL_IDLE, lastIoTime); } catch (Throwable t) { fireExceptionCaught(ctx, t); } } else { // Either read or write occurred before the timeout - set a new // timeout with shorter delay. allIdleTimeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS); } } } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/IdleStateAwareChannelHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/IdleStateAwareChannelHand0000644000175000017500000000425111216674077032556 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.SimpleChannelHandler; /** * An extended {@link SimpleChannelHandler} that adds the handler method for * an {@link IdleStateEvent}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1465 $, $Date: 2009-06-19 04:36:31 -0700 (Fri, 19 Jun 2009) $ */ public class IdleStateAwareChannelHandler extends SimpleChannelHandler { /** * Creates a new instance. */ public IdleStateAwareChannelHandler() { super(); } @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof IdleStateEvent) { channelIdle(ctx, (IdleStateEvent) e); } else { super.handleUpstream(ctx, e); } } /** * Invoked when a {@link Channel} has been idle for a while. */ public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) { ctx.sendUpstream(e); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/IdleStateAwareChannelUpstreamHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/IdleStateAwareChannelUpst0000644000175000017500000000432111216674077032635 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * An extended {@link SimpleChannelUpstreamHandler} that adds the handler method * for an {@link IdleStateEvent}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1465 $, $Date: 2009-06-19 04:36:31 -0700 (Fri, 19 Jun 2009) $ */ public class IdleStateAwareChannelUpstreamHandler extends SimpleChannelUpstreamHandler { /** * Creates a new instance. */ public IdleStateAwareChannelUpstreamHandler() { super(); } @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof IdleStateEvent) { channelIdle(ctx, (IdleStateEvent) e); } else { super.handleUpstream(ctx, e); } } /** * Invoked when a {@link Channel} has been idle for a while. */ public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) { ctx.sendUpstream(e); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/ReadTimeoutException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/ReadTimeoutException.java0000644000175000017500000000374611216671722032657 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; /** * A {@link TimeoutException} raised by {@link ReadTimeoutHandler} when no data * was read within a certain period of time. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1462 $, $Date: 2009-06-19 04:17:38 -0700 (Fri, 19 Jun 2009) $ */ public class ReadTimeoutException extends TimeoutException { private static final long serialVersionUID = -4596059237992273913L; /** * Creates a new instance. */ public ReadTimeoutException() { super(); } /** * Creates a new instance. */ public ReadTimeoutException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public ReadTimeoutException(String message) { super(message); } /** * Creates a new instance. */ public ReadTimeoutException(Throwable cause) { super(cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/package-info.java0000644000175000017500000000224411216671722031072 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Adds support for read and write timeout and idle connection notification * using a {@link org.jboss.netty.util.Timer}. */ package org.jboss.netty.handler.timeout;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/ReadTimeoutHandler.java0000644000175000017500000001517311216674454032300 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import static org.jboss.netty.channel.Channels.*; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.LifeCycleAwareChannelHandler; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.util.ExternalResourceReleasable; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; /** * Raises a {@link ReadTimeoutException} when no data was read within a certain * period of time. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1466 $, $Date: 2009-06-19 04:40:28 -0700 (Fri, 19 Jun 2009) $ * * @see HashedWheelTimer * @see WriteTimeoutHandler * @see IdleStateHandler */ @ChannelPipelineCoverage("one") public class ReadTimeoutHandler extends SimpleChannelUpstreamHandler implements LifeCycleAwareChannelHandler, ExternalResourceReleasable { static final ReadTimeoutException EXCEPTION = new ReadTimeoutException(); final Timer timer; final long timeoutMillis; volatile Timeout timeout; private volatile ReadTimeoutTask task; volatile long lastReadTime; /** * Creates a new instance. * * @param timer * the {@link Timer} that is used to trigger the scheduled event. * The recommended {@link Timer} implementation is {@link HashedWheelTimer}. * @param timeoutSeconds * read timeout in seconds */ public ReadTimeoutHandler(Timer timer, int timeoutSeconds) { this(timer, timeoutSeconds, TimeUnit.SECONDS); } /** * Creates a new instance. * * @param timer * the {@link Timer} that is used to trigger the scheduled event. * The recommended {@link Timer} implementation is {@link HashedWheelTimer}. * @param timeout * read timeout * @param unit * the {@link TimeUnit} of {@code timeout} */ public ReadTimeoutHandler(Timer timer, long timeout, TimeUnit unit) { if (timer == null) { throw new NullPointerException("timer"); } if (unit == null) { throw new NullPointerException("unit"); } this.timer = timer; timeoutMillis = unit.toMillis(timeout); } /** * Stops the {@link Timer} which was specified in the constructor of this * handler. You should not call this method if the {@link Timer} is in use * by other objects. */ public void releaseExternalResources() { timer.stop(); } public void beforeAdd(ChannelHandlerContext ctx) throws Exception { initialize(ctx); } public void afterAdd(ChannelHandlerContext ctx) throws Exception { // NOOP } public void beforeRemove(ChannelHandlerContext ctx) throws Exception { destroy(); } public void afterRemove(ChannelHandlerContext ctx) throws Exception { // NOOP } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { initialize(ctx); ctx.sendUpstream(e); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { destroy(); ctx.sendUpstream(e); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { lastReadTime = System.currentTimeMillis(); ctx.sendUpstream(e); } private void initialize(ChannelHandlerContext ctx) { lastReadTime = System.currentTimeMillis(); task = new ReadTimeoutTask(ctx); if (timeoutMillis > 0) { timeout = timer.newTimeout(task, timeoutMillis, TimeUnit.MILLISECONDS); } } private void destroy() { if (timeout != null) { timeout.cancel(); } timeout = null; task = null; } protected void readTimedOut(ChannelHandlerContext ctx) throws Exception { Channels.fireExceptionCaught(ctx, EXCEPTION); } private final class ReadTimeoutTask implements TimerTask { private final ChannelHandlerContext ctx; ReadTimeoutTask(ChannelHandlerContext ctx) { this.ctx = ctx; } public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.getChannel().isOpen()) { return; } long currentTime = System.currentTimeMillis(); long nextDelay = timeoutMillis - (currentTime - lastReadTime); if (nextDelay <= 0) { // Read timed out - set a new timeout and notify the callback. ReadTimeoutHandler.this.timeout = timer.newTimeout(this, timeoutMillis, TimeUnit.MILLISECONDS); try { readTimedOut(ctx); } catch (Throwable t) { fireExceptionCaught(ctx, t); } } else { // Read occurred before the timeout - set a new timeout with shorter delay. ReadTimeoutHandler.this.timeout = timer.newTimeout(this, nextDelay, TimeUnit.MILLISECONDS); } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/IdleStateEvent.java0000644000175000017500000000323011216671722031422 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; /** * A {@link ChannelEvent} that is triggered when a {@link Channel} has been idle * for a while. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1462 $, $Date: 2009-06-19 04:17:38 -0700 (Fri, 19 Jun 2009) $ */ public interface IdleStateEvent extends ChannelEvent { /** * Returns the detailed idle state. */ IdleState getState(); /** * Returns the last time when I/O occurred in milliseconds. */ long getLastActivityTimeMillis(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/timeout/WriteTimeoutHandler.java0000644000175000017500000001402311216674454032510 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.timeout; import static org.jboss.netty.channel.Channels.*; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelDownstreamHandler; import org.jboss.netty.util.ExternalResourceReleasable; import org.jboss.netty.util.HashedWheelTimer; import org.jboss.netty.util.Timeout; import org.jboss.netty.util.Timer; import org.jboss.netty.util.TimerTask; /** * Raises a {@link WriteTimeoutException} when no data was written within a * certain period of time. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1466 $, $Date: 2009-06-19 04:40:28 -0700 (Fri, 19 Jun 2009) $ * * @see HashedWheelTimer * @see ReadTimeoutHandler * @see IdleStateHandler */ @ChannelPipelineCoverage("all") public class WriteTimeoutHandler extends SimpleChannelDownstreamHandler implements ExternalResourceReleasable { static final WriteTimeoutException EXCEPTION = new WriteTimeoutException(); private final Timer timer; private final long timeoutMillis; /** * Creates a new instance. * * @param timer * the {@link Timer} that is used to trigger the scheduled event. * The recommended {@link Timer} implementation is {@link HashedWheelTimer}. * @param timeoutSeconds * write timeout in seconds */ public WriteTimeoutHandler(Timer timer, int timeoutSeconds) { this(timer, timeoutSeconds, TimeUnit.SECONDS); } /** * Creates a new instance. * * @param timer * the {@link Timer} that is used to trigger the scheduled event. * The recommended {@link Timer} implementation is {@link HashedWheelTimer}. * @param timeout * write timeout * @param unit * the {@link TimeUnit} of {@code timeout} */ public WriteTimeoutHandler(Timer timer, long timeout, TimeUnit unit) { if (timer == null) { throw new NullPointerException("timer"); } if (unit == null) { throw new NullPointerException("unit"); } this.timer = timer; timeoutMillis = unit.toMillis(timeout); } /** * Stops the {@link Timer} which was specified in the constructor of this * handler. You should not call this method if the {@link Timer} is in use * by other objects. */ public void releaseExternalResources() { timer.stop(); } protected long getTimeoutMillis(@SuppressWarnings("unused") MessageEvent e) { return timeoutMillis; } @Override public void writeRequested(ChannelHandlerContext ctx, MessageEvent e) throws Exception { long timeoutMillis = getTimeoutMillis(e); if (timeoutMillis > 0) { // Set timeout only when getTimeoutMillis() returns a positive value. ChannelFuture future = e.getFuture(); final Timeout timeout = timer.newTimeout( new WriteTimeoutTask(ctx, future), timeoutMillis, TimeUnit.MILLISECONDS); future.addListener(new TimeoutCanceller(timeout)); } super.writeRequested(ctx, e); } protected void writeTimedOut(ChannelHandlerContext ctx) throws Exception { Channels.fireExceptionCaught(ctx, EXCEPTION); } private final class WriteTimeoutTask implements TimerTask { private final ChannelHandlerContext ctx; private final ChannelFuture future; WriteTimeoutTask(ChannelHandlerContext ctx, ChannelFuture future) { this.ctx = ctx; this.future = future; } public void run(Timeout timeout) throws Exception { if (timeout.isCancelled()) { return; } if (!ctx.getChannel().isOpen()) { return; } // Mark the future as failure if (future.setFailure(EXCEPTION)) { // If succeeded to mark as failure, notify the pipeline, too. try { writeTimedOut(ctx); } catch (Throwable t) { fireExceptionCaught(ctx, t); } } } } /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1466 $, $Date: 2009-06-19 04:40:28 -0700 (Fri, 19 Jun 2009) $ */ private static final class TimeoutCanceller implements ChannelFutureListener { private final Timeout timeout; TimeoutCanceller(Timeout timeout) { this.timeout = timeout; } public void operationComplete(ChannelFuture future) throws Exception { timeout.cancel(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/stream/0000755000175000017500000000000011316313146025500 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/stream/ChunkedStream.java0000644000175000017500000000716511216667051031117 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.stream; import static org.jboss.netty.buffer.ChannelBuffers.*; import java.io.InputStream; import java.io.PushbackInputStream; /** * A {@link ChunkedInput} that fetches data from an {@link InputStream} chunk by * chunk. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1461 $, $Date: 2009-06-19 03:53:29 -0700 (Fri, 19 Jun 2009) $ */ public class ChunkedStream implements ChunkedInput { static final int DEFAULT_CHUNK_SIZE = 8192; private final PushbackInputStream in; private final int chunkSize; private volatile long offset; /** * Creates a new instance that fetches data from the specified stream. */ public ChunkedStream(InputStream in) { this(in, DEFAULT_CHUNK_SIZE); } /** * Creates a new instance that fetches data from the specified stream. * * @param chunkSize the number of bytes to fetch on each * {@link #nextChunk()} call */ public ChunkedStream(InputStream in, int chunkSize) { if (in == null) { throw new NullPointerException("in"); } if (chunkSize <= 0) { throw new IllegalArgumentException( "chunkSize: " + chunkSize + " (expected: a positive integer)"); } if (in instanceof PushbackInputStream) { this.in = (PushbackInputStream) in; } else { this.in = new PushbackInputStream(in); } this.chunkSize = chunkSize; } /** * Returns the number of transferred bytes. */ public long getTransferredBytes() { return offset; } public boolean hasNextChunk() throws Exception { int b = in.read(); if (b < 0) { return false; } else { in.unread(b); return true; } } public void close() throws Exception { in.close(); } public Object nextChunk() throws Exception { if (!hasNextChunk()) { return null; } final int chunkSize = Math.min(this.chunkSize, in.available()); final byte[] chunk = new byte[chunkSize]; int readBytes = 0; for (;;) { int localReadBytes = in.read(chunk, readBytes, chunkSize - readBytes); if (localReadBytes < 0) { break; } readBytes += localReadBytes; offset += localReadBytes; if (readBytes == chunkSize) { break; } } return wrappedBuffer(chunk, 0, readBytes); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/stream/ChunkedFile.java0000644000175000017500000001135411216667051030536 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.stream; import static org.jboss.netty.buffer.ChannelBuffers.*; import java.io.File; import java.io.IOException; import java.io.RandomAccessFile; /** * A {@link ChunkedInput} that fetches data from a file chunk by chunk. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1461 $, $Date: 2009-06-19 03:53:29 -0700 (Fri, 19 Jun 2009) $ */ public class ChunkedFile implements ChunkedInput { private final RandomAccessFile file; private final long startOffset; private final long endOffset; private final int chunkSize; private volatile long offset; /** * Creates a new instance that fetches data from the specified file. */ public ChunkedFile(File file) throws IOException { this(file, ChunkedStream.DEFAULT_CHUNK_SIZE); } /** * Creates a new instance that fetches data from the specified file. * * @param chunkSize the number of bytes to fetch on each * {@link #nextChunk()} call */ public ChunkedFile(File file, int chunkSize) throws IOException { this(new RandomAccessFile(file, "r"), chunkSize); } /** * Creates a new instance that fetches data from the specified file. * * @param chunkSize the number of bytes to fetch on each * {@link #nextChunk()} call */ public ChunkedFile(RandomAccessFile file, int chunkSize) throws IOException { this(file, 0, file.length(), chunkSize); } /** * Creates a new instance that fetches data from the specified file. * * @param offset the offset of the file where the transfer begins * @param length the number of bytes to transfer * @param chunkSize the number of bytes to fetch on each * {@link #nextChunk()} call */ public ChunkedFile(RandomAccessFile file, long offset, long length, int chunkSize) throws IOException { if (file == null) { throw new NullPointerException("file"); } if (offset < 0) { throw new IllegalArgumentException( "offset: " + offset + " (expected: 0 or greater)"); } if (length < 0) { throw new IllegalArgumentException( "length: " + length + " (expected: 0 or greater)"); } if (chunkSize <= 0) { throw new IllegalArgumentException( "chunkSize: " + chunkSize + " (expected: a positive integer)"); } this.file = file; this.offset = startOffset = offset; endOffset = offset + length; this.chunkSize = chunkSize; file.seek(offset); } /** * Returns the offset in the file where the transfer began. */ public long getStartOffset() { return startOffset; } /** * Returns the offset in the file where the transfer will end. */ public long getEndOffset() { return endOffset; } /** * Returns the offset in the file where the transfer is happening currently. */ public long getCurrentOffset() { return offset; } public boolean hasNextChunk() throws Exception { return offset < endOffset && file.getChannel().isOpen(); } public void close() throws Exception { file.close(); } public Object nextChunk() throws Exception { long offset = this.offset; if (offset >= endOffset) { return null; } int chunkSize = (int) Math.min(this.chunkSize, endOffset - offset); byte[] chunk = new byte[chunkSize]; file.readFully(chunk); this.offset = offset + chunkSize; return wrappedBuffer(chunk); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/stream/ChunkedInput.java0000644000175000017500000000413311216723540030747 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.stream; import org.jboss.netty.buffer.ChannelBuffer; /** * A large data stream which is consumed by {@link ChunkedWriteHandler}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1471 $, $Date: 2009-06-19 07:57:36 -0700 (Fri, 19 Jun 2009) $ */ public interface ChunkedInput { /** * Returns {@code true} if and only if there is any data left in the * stream. */ boolean hasNextChunk() throws Exception; /** * Fetches a chunked data from the stream. The returned chunk is usually * a {@link ChannelBuffer}, but you could extend an existing implementation * to convert the {@link ChannelBuffer} into a different type that your * handler or encoder understands. * * @return the fetched chunk, which is usually {@link ChannelBuffer}. * {@code null} if there is no data left in the stream. */ Object nextChunk() throws Exception; /** * Releases the resources associated with the stream. */ void close() throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/stream/ChunkedWriteHandler.java0000644000175000017500000001613711216666227032257 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.stream; import static org.jboss.netty.channel.Channels.*; import java.util.Queue; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.LinkedTransferQueue; /** * A {@link ChannelHandler} that adds support for writing a large data stream * asynchronously neither spending a lot of memory nor getting * {@link java.lang.OutOfMemoryError}. Large data streaming such as file * transfer requires complicated state management in a {@link ChannelHandler} * implementation. {@link ChunkedWriteHandler} manages such complicated states * so that you can send a large data stream without difficulties. *

* To use {@link ChunkedWriteHandler} in your application, you have to insert * a new {@link ChunkedWriteHandler} instance: *

 * ChannelPipeline p = ...;
 * p.addLast("streamer", new ChunkedWriteHandler());
 * p.addLast("handler", new MyHandler());
 * 
* Once inserted, you can write a {@link ChunkedInput} so that the * {@link ChunkedWriteHandler} can pick it up and fetch the content of the * stream chunk by chunk and write the fetched chunk downstream: *
 * Channel ch = ...;
 * ch.write(new ChunkedFile(new File("video.mkv"));
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1460 $, $Date: 2009-06-19 03:46:47 -0700 (Fri, 19 Jun 2009) $ */ @ChannelPipelineCoverage("one") public class ChunkedWriteHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(ChunkedWriteHandler.class); private final Queue queue = new LinkedTransferQueue(); private MessageEvent currentEvent; /** * Creates a new instance. */ public ChunkedWriteHandler() { super(); } public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (!(e instanceof MessageEvent)) { ctx.sendDownstream(e); return; } queue.offer((MessageEvent) e); if (ctx.getChannel().isWritable()) { flushWriteEventQueue(ctx); } } public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { ChannelStateEvent cse = (ChannelStateEvent) e; if (cse.getState() == ChannelState.INTEREST_OPS && ctx.getChannel().isWritable()) { // Continue writing when the channel becomes writable. flushWriteEventQueue(ctx); } } ctx.sendUpstream(e); } private synchronized void flushWriteEventQueue(ChannelHandlerContext ctx) throws Exception { Channel channel = ctx.getChannel(); do { if (currentEvent == null) { currentEvent = queue.poll(); } if (currentEvent == null) { break; } Object m = currentEvent.getMessage(); if (m instanceof ChunkedInput) { ChunkedInput chunks = (ChunkedInput) m; Object chunk; boolean last; try { chunk = chunks.nextChunk(); last = !chunks.hasNextChunk(); } catch (Throwable t) { currentEvent.getFuture().setFailure(t); fireExceptionCaught(ctx, t); try { chunks.close(); } catch (Throwable t2) { logger.warn("Failed to close a chunked input.", t2); } break; } if (chunk != null) { ChannelFuture writeFuture; final MessageEvent currentEvent = this.currentEvent; if (last) { this.currentEvent = null; writeFuture = currentEvent.getFuture(); writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { ((ChunkedInput) currentEvent.getMessage()).close(); } }); } else { writeFuture = future(channel); writeFuture.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { currentEvent.getFuture().setFailure(future.getCause()); ((ChunkedInput) currentEvent.getMessage()).close(); } } }); } Channels.write( ctx, writeFuture, chunk, currentEvent.getRemoteAddress()); } else { currentEvent = null; } } else { ctx.sendDownstream(currentEvent); currentEvent = null; } } while (channel.isWritable()); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/stream/package-info.java0000644000175000017500000000240311216666227030700 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Writes very large data stream asynchronously neither spending a lot of * memory nor getting {@link java.lang.OutOfMemoryError}. For a detailed * example, please refer to {@code org.jboss.netty.example.http.file}. */ package org.jboss.netty.handler.stream;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/logging/0000755000175000017500000000000011316313145025632 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/logging/LoggingHandler.java0000644000175000017500000001574411216656323031403 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.logging; import static org.jboss.netty.buffer.ChannelBuffers.*; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.logging.InternalLogLevel; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; /** * A {@link ChannelHandler} that logs all events via {@link InternalLogger}. * By default, all events are logged at DEBUG level. You can extend * this class and override {@link #log(ChannelEvent)} to change the default * behavior. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1458 $, $Date: 2009-06-19 02:39:31 -0700 (Fri, 19 Jun 2009) $ */ @ChannelPipelineCoverage("all") public class LoggingHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler { private static final InternalLogLevel DEFAULT_LEVEL = InternalLogLevel.DEBUG; private final InternalLogger logger; private final InternalLogLevel level; private final boolean hexDump; /** * Creates a new instance whose logger name is the fully qualified class * name of the instance with hex dump enabled. */ public LoggingHandler() { this(true); } /** * Creates a new instance whose logger name is the fully qualified class * name of the instance. * * @param hexDump {@code true} if and only if the hex dump of the received * message is logged */ public LoggingHandler(boolean hexDump) { logger = InternalLoggerFactory.getInstance(getClass()); level = DEFAULT_LEVEL; this.hexDump = hexDump; } /** * Creates a new instance with the specified logger name and with hex dump * enabled. */ public LoggingHandler(Class clazz) { this(clazz, true); } /** * Creates a new instance with the specified logger name. * * @param hexDump {@code true} if and only if the hex dump of the received * message is logged */ public LoggingHandler(Class clazz, boolean hexDump) { this(clazz, DEFAULT_LEVEL, hexDump); } /** * Creates a new instance with the specified logger name. * * @param level the log level * @param hexDump {@code true} if and only if the hex dump of the received * message is logged */ public LoggingHandler(Class clazz, InternalLogLevel level, boolean hexDump) { if (clazz == null) { throw new NullPointerException("clazz"); } if (level == null) { throw new NullPointerException("level"); } logger = InternalLoggerFactory.getInstance(clazz); this.level = level; this.hexDump = hexDump; } /** * Creates a new instance with the specified logger name and with hex dump * enabled. */ public LoggingHandler(String name) { this(name, true); } /** * Creates a new instance with the specified logger name. * * @param hexDump {@code true} if and only if the hex dump of the received * message is logged */ public LoggingHandler(String name, boolean hexDump) { this(name, DEFAULT_LEVEL, hexDump); } /** * Creates a new instance with the specified logger name. * * @param level the log level * @param hexDump {@code true} if and only if the hex dump of the received * message is logged */ public LoggingHandler(String name, InternalLogLevel level, boolean hexDump) { if (name == null) { throw new NullPointerException("name"); } if (level == null) { throw new NullPointerException("level"); } logger = InternalLoggerFactory.getInstance(name); this.level = level; this.hexDump = hexDump; } /** * Returns the {@link InternalLogger} that this handler uses to log * a {@link ChannelEvent}. */ public InternalLogger getLogger() { return logger; } /** * Returns the {@link InternalLogLevel} that this handler uses to log * a {@link ChannelEvent}. */ public InternalLogLevel getLevel() { return level; } /** * Logs the specified event to the {@link InternalLogger} returned by * {@link #getLogger()}. If hex dump has been enabled for this handler, * the hex dump of the {@link ChannelBuffer} in a {@link MessageEvent} will * be logged together. */ public void log(ChannelEvent e) { if (getLogger().isEnabled(level)) { String msg = e.toString(); // Append hex dump if necessary. if (hexDump && e instanceof MessageEvent) { MessageEvent me = (MessageEvent) e; if (me.getMessage() instanceof ChannelBuffer) { ChannelBuffer buf = (ChannelBuffer) me.getMessage(); msg = msg + " - (HEXDUMP: " + hexDump(buf) + ')'; } } // Log the message (and exception if available.) if (e instanceof ExceptionEvent) { getLogger().log(level, msg, ((ExceptionEvent) e).getCause()); } else { getLogger().log(level, msg); } } } public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { log(e); ctx.sendUpstream(e); } public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { log(e); ctx.sendDownstream(e); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/logging/package-info.java0000644000175000017500000000230711216657035031033 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Logs a {@link org.jboss.netty.channel.ChannelEvent} for debugging purpose * using an {@link org.jboss.netty.logging.InternalLogger}. * * @apiviz.hidden */ package org.jboss.netty.handler.logging;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/0000755000175000017500000000000011316313145026207 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/ExecutionHandler.java0000644000175000017500000001107611165336702032326 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.execution; import java.util.concurrent.Executor; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.util.ExternalResourceReleasable; import org.jboss.netty.util.internal.ExecutorUtil; /** * Forwards an upstream {@link ChannelEvent} to an {@link Executor}. *

* You can implement various thread model by adding this handler to a * {@link ChannelPipeline}. The most common use case of this handler is to * add a {@link ExecutionHandler} which was specified with * {@link OrderedMemoryAwareThreadPoolExecutor}: *

 * ChannelPipeline pipeline = ...;
 * pipeline.addLast("decoder", new MyProtocolDecoder());
 * pipeline.addLast("encoder", new MyProtocolEncoder());
 *
 * // HERE
 * pipeline.addLast("executor", new {@link ExecutionHandler}(new {@link OrderedMemoryAwareThreadPoolExecutor}(16, 1048576, 1048576)));
 *
 * pipeline.addLast("handler", new MyBusinessLogicHandler());
 * 
* to utilize more processors to handle {@link ChannelEvent}s. You can also * use other {@link Executor} implementation than the recommended * {@link OrderedMemoryAwareThreadPoolExecutor}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1124 $, $Date: 2009-04-03 00:41:54 -0700 (Fri, 03 Apr 2009) $ * * @apiviz.landmark * @apiviz.has java.util.concurrent.ThreadPoolExecutor */ @ChannelPipelineCoverage("all") public class ExecutionHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler, ExternalResourceReleasable { private final Executor executor; /** * Creates a new instance with the specified {@link Executor}. */ public ExecutionHandler(Executor executor) { if (executor == null) { throw new NullPointerException("executor"); } this.executor = executor; } /** * Returns the {@link Executor} which was specified with the constructor. */ public Executor getExecutor() { return executor; } /** * Shuts down the {@link Executor} which was specified with the constructor * and wait for its termination. */ public void releaseExternalResources() { ExecutorUtil.terminate(getExecutor()); } public void handleUpstream( ChannelHandlerContext context, ChannelEvent e) throws Exception { executor.execute(new ChannelEventRunnable(context, e)); } public void handleDownstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { ChannelStateEvent cse = (ChannelStateEvent) e; if (cse.getState() == ChannelState.INTEREST_OPS && (((Integer) cse.getValue()).intValue() & Channel.OP_READ) != 0) { // setReadable(true) requested boolean readSuspended = ctx.getAttachment() != null; if (readSuspended) { // Drop the request silently if MemoryAwareThreadPool has // set the flag. e.getFuture().setSuccess(); return; } } } ctx.sendDownstream(e); } } ././@LongLink0000000000000000000000000000016700000000000011571 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/OrderedMemoryAwareThreadPoolExecutor.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/OrderedMemoryAwareThrea0000644000175000017500000002445111175733454032675 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.execution; import java.util.LinkedList; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.ThreadFactory; import java.util.concurrent.TimeUnit; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.util.ObjectSizeEstimator; import org.jboss.netty.util.internal.ConcurrentIdentityWeakKeyHashMap; /** * A {@link MemoryAwareThreadPoolExecutor} which maintains the * {@link ChannelEvent} order for the same {@link Channel}. *

* {@link OrderedMemoryAwareThreadPoolExecutor} executes the queued task in the * same thread if an existing thread is running a task associated with the same * {@link Channel}. This behavior is to make sure the events from the same * {@link Channel} are handled in a correct order. A different thread might be * chosen only when the task queue of the {@link Channel} is empty. *

* Although {@link OrderedMemoryAwareThreadPoolExecutor} guarantees the order * of {@link ChannelEvent}s. It does not guarantee that the invocation will be * made by the same thread for the same channel, but it does guarantee that * the invocation will be made sequentially for the events of the same channel. * For example, the events can be processed as depicted below: * *

 *           -----------------------------------> Timeline ----------------------------------->
 *
 * Thread X: --- Channel A (Event 1) --.   .-- Channel B (Event 2) --- Channel B (Event 3) --->
 *                                      \ /
 *                                       X
 *                                      / \
 * Thread Y: --- Channel B (Event 1) --'   '-- Channel A (Event 2) --- Channel A (Event 3) --->
 * 
* * Please note that the events of different channels are independent from each * other. That is, an event of Channel B will not be blocked by an event of * Channel A and vice versa, unless the thread pool is exhausted. *

* If you want the events associated with the same channel to be executed * simultaneously, please use {@link MemoryAwareThreadPoolExecutor} instead. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author David M. Lloyd (david.lloyd@redhat.com) * * @version $Rev: 1273 $, $Date: 2009-04-28 19:10:52 -0700 (Tue, 28 Apr 2009) $ * * @apiviz.landmark */ public class OrderedMemoryAwareThreadPoolExecutor extends MemoryAwareThreadPoolExecutor { private final ConcurrentMap childExecutors = new ConcurrentIdentityWeakKeyHashMap(); /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. */ public OrderedMemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize) { super(corePoolSize, maxChannelMemorySize, maxTotalMemorySize); } /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. * @param keepAliveTime the amount of time for an inactive thread to shut itself down * @param unit the {@link TimeUnit} of {@code keepAliveTime} */ public OrderedMemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize, long keepAliveTime, TimeUnit unit) { super(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, keepAliveTime, unit); } /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. * @param keepAliveTime the amount of time for an inactive thread to shut itself down * @param unit the {@link TimeUnit} of {@code keepAliveTime} * @param threadFactory the {@link ThreadFactory} of this pool */ public OrderedMemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) { super(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, keepAliveTime, unit, threadFactory); } /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. * @param keepAliveTime the amount of time for an inactive thread to shut itself down * @param unit the {@link TimeUnit} of {@code keepAliveTime} * @param threadFactory the {@link ThreadFactory} of this pool * @param objectSizeEstimator the {@link ObjectSizeEstimator} of this pool */ public OrderedMemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize, long keepAliveTime, TimeUnit unit, ObjectSizeEstimator objectSizeEstimator, ThreadFactory threadFactory) { super(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, keepAliveTime, unit, objectSizeEstimator, threadFactory); } /** * Executes the specified task concurrently while maintaining the event * order. */ @Override protected void doExecute(Runnable task) { if (!(task instanceof ChannelEventRunnable)) { doUnorderedExecute(task); } else { ChannelEventRunnable r = (ChannelEventRunnable) task; getOrderedExecutor(r.getEvent()).execute(task); } } private Executor getOrderedExecutor(ChannelEvent e) { Channel channel = e.getChannel(); Executor executor = childExecutors.get(channel); if (executor == null) { executor = new ChildExecutor(); Executor oldExecutor = childExecutors.putIfAbsent(channel, executor); if (oldExecutor != null) { executor = oldExecutor; } } // Remove the entry when the channel closes. if (e instanceof ChannelStateEvent) { ChannelStateEvent se = (ChannelStateEvent) e; if (se.getState() == ChannelState.OPEN && !channel.isOpen()) { childExecutors.remove(channel); } } return executor; } @Override protected boolean shouldCount(Runnable task) { if (task instanceof ChildExecutor) { return false; } return super.shouldCount(task); } void onAfterExecute(Runnable r, Throwable t) { afterExecute(r, t); } private final class ChildExecutor implements Executor, Runnable { private final LinkedList tasks = new LinkedList(); ChildExecutor() { super(); } public void execute(Runnable command) { boolean needsExecution; synchronized (tasks) { needsExecution = tasks.isEmpty(); tasks.add(command); } if (needsExecution) { doUnorderedExecute(this); } } public void run() { Thread thread = Thread.currentThread(); for (;;) { final Runnable task; synchronized (tasks) { task = tasks.getFirst(); } boolean ran = false; beforeExecute(thread, task); try { task.run(); ran = true; onAfterExecute(task, null); } catch (RuntimeException e) { if (!ran) { onAfterExecute(task, e); } throw e; } finally { synchronized (tasks) { tasks.removeFirst(); if (tasks.isEmpty()) { break; } } } } } } } ././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/MemoryAwareThreadPoolExecutor.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/MemoryAwareThreadPoolEx0000644000175000017500000004713511212141660032647 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.execution; import java.lang.reflect.Method; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.RejectedExecutionHandler; import java.util.concurrent.Semaphore; import java.util.concurrent.ThreadFactory; import java.util.concurrent.ThreadPoolExecutor; import java.util.concurrent.TimeUnit; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicLong; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.WriteCompletionEvent; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.DefaultObjectSizeEstimator; import org.jboss.netty.util.ObjectSizeEstimator; import org.jboss.netty.util.internal.ConcurrentIdentityHashMap; import org.jboss.netty.util.internal.LinkedTransferQueue; /** * A {@link ThreadPoolExecutor} which blocks the task submission when there's * too many tasks in the queue. *

* Both per-{@link Channel} and per-{@link Executor} limitation can be applied. * If the total size of the unprocessed tasks (i.e. {@link Runnable}s) exceeds * either per-{@link Channel} or per-{@link Executor} threshold, any further * {@link #execute(Runnable)} call will block until the tasks in the queue * are processed so that the total size goes under the threshold. *

* {@link ObjectSizeEstimator} is used to calculate the size of each task. *

* Please note that this executor does not maintain the order of the * {@link ChannelEvent}s for the same {@link Channel}. For example, * you can even receive a {@code "channelClosed"} event before a * {@code "messageReceived"} event, as depicted by the following diagram. * * For example, the events can be processed as depicted below: * *

 *           --------------------------------> Timeline -------------------------------->
 *
 * Thread X: --- Channel A (Event 2) --- Channel A (Event 1) --------------------------->
 *
 * Thread Y: --- Channel A (Event 3) --- Channel B (Event 2) --- Channel B (Event 3) --->
 *
 * Thread Z: --- Channel B (Event 1) --- Channel B (Event 4) --- Channel A (Event 4) --->
 * 
* * To maintain the event order, you must use {@link OrderedMemoryAwareThreadPoolExecutor}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1330 $, $Date: 2009-06-05 00:05:20 -0700 (Fri, 05 Jun 2009) $ * * @apiviz.uses org.jboss.netty.util.ObjectSizeEstimator * @apiviz.uses org.jboss.netty.handler.execution.ChannelEventRunnable */ public class MemoryAwareThreadPoolExecutor extends ThreadPoolExecutor { private static final InternalLogger logger = InternalLoggerFactory.getInstance(MemoryAwareThreadPoolExecutor.class); // I'd say 64 active event thread pools are obvious misuse. private static final int MISUSE_WARNING_THRESHOLD = 64; private static final AtomicInteger activeInstances = new AtomicInteger(); private static final AtomicBoolean loggedMisuseWarning = new AtomicBoolean(); private volatile Settings settings; private final ConcurrentMap channelCounters = new ConcurrentIdentityHashMap(); private final AtomicLong totalCounter = new AtomicLong(); private final Semaphore semaphore = new Semaphore(0); /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. */ public MemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize) { this(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, 30, TimeUnit.SECONDS); } /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. * @param keepAliveTime the amount of time for an inactive thread to shut itself down * @param unit the {@link TimeUnit} of {@code keepAliveTime} */ public MemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize, long keepAliveTime, TimeUnit unit) { this(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, keepAliveTime, unit, Executors.defaultThreadFactory()); } /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. * @param keepAliveTime the amount of time for an inactive thread to shut itself down * @param unit the {@link TimeUnit} of {@code keepAliveTime} * @param threadFactory the {@link ThreadFactory} of this pool */ public MemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize, long keepAliveTime, TimeUnit unit, ThreadFactory threadFactory) { this(corePoolSize, maxChannelMemorySize, maxTotalMemorySize, keepAliveTime, unit, new DefaultObjectSizeEstimator(), threadFactory); } /** * Creates a new instance. * * @param corePoolSize the maximum number of active threads * @param maxChannelMemorySize the maximum total size of the queued events per channel. * Specify {@code 0} to disable. * @param maxTotalMemorySize the maximum total size of the queued events for this pool * Specify {@code 0} to disable. * @param keepAliveTime the amount of time for an inactive thread to shut itself down * @param unit the {@link TimeUnit} of {@code keepAliveTime} * @param threadFactory the {@link ThreadFactory} of this pool * @param objectSizeEstimator the {@link ObjectSizeEstimator} of this pool */ public MemoryAwareThreadPoolExecutor( int corePoolSize, long maxChannelMemorySize, long maxTotalMemorySize, long keepAliveTime, TimeUnit unit, ObjectSizeEstimator objectSizeEstimator, ThreadFactory threadFactory) { super(corePoolSize, corePoolSize, keepAliveTime, unit, new LinkedTransferQueue(), threadFactory, new NewThreadRunsPolicy()); if (objectSizeEstimator == null) { throw new NullPointerException("objectSizeEstimator"); } if (maxChannelMemorySize < 0) { throw new IllegalArgumentException( "maxChannelMemorySize: " + maxChannelMemorySize); } if (maxTotalMemorySize < 0) { throw new IllegalArgumentException( "maxTotalMemorySize: " + maxTotalMemorySize); } // Call allowCoreThreadTimeOut(true) using reflection // because it is not supported in Java 5. try { Method m = getClass().getMethod("allowCoreThreadTimeOut", new Class[] { boolean.class }); m.invoke(this, Boolean.TRUE); } catch (Throwable t) { // Java 5 logger.debug( "ThreadPoolExecutor.allowCoreThreadTimeOut() is not " + "supported in this platform."); } settings = new Settings( objectSizeEstimator, maxChannelMemorySize, maxTotalMemorySize); // Misuse check int activeInstances = MemoryAwareThreadPoolExecutor.activeInstances.incrementAndGet(); if (activeInstances >= MISUSE_WARNING_THRESHOLD && loggedMisuseWarning.compareAndSet(false, true)) { logger.debug( "There are too many active " + MemoryAwareThreadPoolExecutor.class.getSimpleName() + " instances (" + activeInstances + ") - you should share " + "the small number of instances to avoid excessive resource " + "consumption."); } } @Override protected void terminated() { super.terminated(); activeInstances.decrementAndGet(); } /** * Returns the {@link ObjectSizeEstimator} of this pool. */ public ObjectSizeEstimator getObjectSizeEstimator() { return settings.objectSizeEstimator; } /** * Sets the {@link ObjectSizeEstimator} of this pool. */ public void setObjectSizeEstimator(ObjectSizeEstimator objectSizeEstimator) { if (objectSizeEstimator == null) { throw new NullPointerException("objectSizeEstimator"); } settings = new Settings( objectSizeEstimator, settings.maxChannelMemorySize, settings.maxTotalMemorySize); } /** * Returns the maximum total size of the queued events per channel. */ public long getMaxChannelMemorySize() { return settings.maxChannelMemorySize; } /** * Sets the maximum total size of the queued events per channel. * Specify {@code 0} to disable. */ public void setMaxChannelMemorySize(long maxChannelMemorySize) { if (maxChannelMemorySize < 0) { throw new IllegalArgumentException( "maxChannelMemorySize: " + maxChannelMemorySize); } if (getTaskCount() > 0) { throw new IllegalStateException( "can't be changed after a task is executed"); } settings = new Settings( settings.objectSizeEstimator, maxChannelMemorySize, settings.maxTotalMemorySize); } /** * Returns the maximum total size of the queued events for this pool. */ public long getMaxTotalMemorySize() { return settings.maxTotalMemorySize; } /** * Sets the maximum total size of the queued events for this pool. * Specify {@code 0} to disable. */ public void setMaxTotalMemorySize(long maxTotalMemorySize) { if (maxTotalMemorySize < 0) { throw new IllegalArgumentException( "maxTotalMemorySize: " + maxTotalMemorySize); } if (getTaskCount() > 0) { throw new IllegalStateException( "can't be changed after a task is executed"); } settings = new Settings( settings.objectSizeEstimator, settings.maxChannelMemorySize, maxTotalMemorySize); } @Override public void execute(Runnable command) { if (!(command instanceof ChannelEventRunnable)) { command = new MemoryAwareRunnable(command); } boolean pause = increaseCounter(command); doExecute(command); if (pause) { //System.out.println("ACQUIRE: " + command); semaphore.acquireUninterruptibly(); } } /** * Put the actual execution logic here. The default implementation simply * calls {@link #doUnorderedExecute(Runnable)}. */ protected void doExecute(Runnable task) { doUnorderedExecute(task); } /** * Executes the specified task without maintaining the event order. */ protected final void doUnorderedExecute(Runnable task) { super.execute(task); } @Override public boolean remove(Runnable task) { boolean removed = super.remove(task); if (removed) { decreaseCounter(task); } return removed; } @Override protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); decreaseCounter(r); } protected boolean increaseCounter(Runnable task) { if (!shouldCount(task)) { return false; } Settings settings = this.settings; long maxTotalMemorySize = settings.maxTotalMemorySize; long maxChannelMemorySize = settings.maxChannelMemorySize; int increment = settings.objectSizeEstimator.estimateSize(task); long totalCounter = this.totalCounter.addAndGet(increment); if (task instanceof ChannelEventRunnable) { ChannelEventRunnable eventTask = (ChannelEventRunnable) task; eventTask.estimatedSize = increment; Channel channel = eventTask.getEvent().getChannel(); long channelCounter = getChannelCounter(channel).addAndGet(increment); //System.out.println("IC: " + channelCounter + ", " + increment); if (maxChannelMemorySize != 0 && channelCounter >= maxChannelMemorySize && channel.isOpen()) { if (channel.isReadable()) { //System.out.println("UNREADABLE"); ChannelHandlerContext ctx = eventTask.getContext(); if (ctx.getHandler() instanceof ExecutionHandler) { // readSuspended = true; ctx.setAttachment(Boolean.TRUE); } channel.setReadable(false); } } } else { ((MemoryAwareRunnable) task).estimatedSize = increment; } //System.out.println("I: " + totalCounter + ", " + increment); return maxTotalMemorySize != 0 && totalCounter >= maxTotalMemorySize; } protected void decreaseCounter(Runnable task) { if (!shouldCount(task)) { return; } Settings settings = this.settings; long maxTotalMemorySize = settings.maxTotalMemorySize; long maxChannelMemorySize = settings.maxChannelMemorySize; int increment; if (task instanceof ChannelEventRunnable) { increment = ((ChannelEventRunnable) task).estimatedSize; } else { increment = ((MemoryAwareRunnable) task).estimatedSize; } long totalCounter = this.totalCounter.addAndGet(-increment); //System.out.println("D: " + totalCounter + ", " + increment); if (maxTotalMemorySize != 0 && totalCounter + increment >= maxTotalMemorySize) { //System.out.println("RELEASE: " + task); semaphore.release(); } if (task instanceof ChannelEventRunnable) { ChannelEventRunnable eventTask = (ChannelEventRunnable) task; Channel channel = eventTask.getEvent().getChannel(); long channelCounter = getChannelCounter(channel).addAndGet(-increment); //System.out.println("DC: " + channelCounter + ", " + increment); if (maxChannelMemorySize != 0 && channelCounter < maxChannelMemorySize && channel.isOpen()) { if (!channel.isReadable()) { //System.out.println("READABLE"); ChannelHandlerContext ctx = eventTask.getContext(); if (ctx.getHandler() instanceof ExecutionHandler) { // readSuspended = false; ctx.setAttachment(null); } channel.setReadable(true); } } } } private AtomicLong getChannelCounter(Channel channel) { AtomicLong counter = channelCounters.get(channel); if (counter == null) { counter = new AtomicLong(); AtomicLong oldCounter = channelCounters.putIfAbsent(channel, counter); if (oldCounter != null) { counter = oldCounter; } } // Remove the entry when the channel closes. if (!channel.isOpen()) { channelCounters.remove(channel); } return counter; } /** * Returns {@code true} if and only if the specified {@code task} should * be counted to limit the global and per-channel memory consumption. * To override this method, you must call {@code super.shouldCount()} to * make sure important tasks are not counted. */ protected boolean shouldCount(Runnable task) { if (task instanceof ChannelEventRunnable) { ChannelEventRunnable r = (ChannelEventRunnable) task; ChannelEvent e = r.getEvent(); if (e instanceof WriteCompletionEvent) { return false; } else if (e instanceof ChannelStateEvent) { if (((ChannelStateEvent) e).getState() == ChannelState.INTEREST_OPS) { return false; } } } return true; } private static final class Settings { final ObjectSizeEstimator objectSizeEstimator; final long maxChannelMemorySize; final long maxTotalMemorySize; Settings(ObjectSizeEstimator objectSizeEstimator, long maxChannelMemorySize, long maxTotalMemorySize) { this.objectSizeEstimator = objectSizeEstimator; this.maxChannelMemorySize = maxChannelMemorySize; this.maxTotalMemorySize = maxTotalMemorySize; } } private static final class NewThreadRunsPolicy implements RejectedExecutionHandler { NewThreadRunsPolicy() { super(); } public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) { try { final Thread t = new Thread(r, "Temporary task executor"); t.start(); } catch (Throwable e) { throw new RejectedExecutionException( "Failed to start a new thread", e); } } } private static final class MemoryAwareRunnable implements Runnable { final Runnable task; volatile int estimatedSize; MemoryAwareRunnable(Runnable task) { this.task = task; } public void run() { task.run(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/package-info.java0000644000175000017500000000232411046721772031410 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * {@link java.util.concurrent.Executor}-based implementation of various * thread models and memory overload prevention mechanisms. * * @apiviz.exclude ^java\.lang\. */ package org.jboss.netty.handler.execution;././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/ChannelEventRunnable.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/execution/ChannelEventRunnable.ja0000644000175000017500000000511311216077425032573 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.execution; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.util.EstimatableObjectWrapper; /** * a {@link Runnable} which sends the specified {@link ChannelEvent} upstream. * Most users will not see this type at all because it is used by * {@link Executor} implementors only * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1395 $, $Date: 2009-06-16 22:28:53 -0700 (Tue, 16 Jun 2009) $ * */ public class ChannelEventRunnable implements Runnable, EstimatableObjectWrapper { private final ChannelHandlerContext ctx; private final ChannelEvent e; volatile int estimatedSize; /** * Creates a {@link Runnable} which sends the specified {@link ChannelEvent} * upstream via the specified {@link ChannelHandlerContext}. */ public ChannelEventRunnable(ChannelHandlerContext ctx, ChannelEvent e) { this.ctx = ctx; this.e = e; } /** * Returns the {@link ChannelHandlerContext} which will be used to * send the {@link ChannelEvent} upstream. */ public ChannelHandlerContext getContext() { return ctx; } /** * Returns the {@link ChannelEvent} which will be sent upstream. */ public ChannelEvent getEvent() { return e; } /** * Sends the event upstream. */ public void run() { ctx.sendUpstream(e); } public Object unwrap() { return e; } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/ssl/0000755000175000017500000000000011316313144025004 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/ssl/SslBufferPool.java0000644000175000017500000001007411104723515030400 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.ssl; import java.nio.ByteBuffer; import javax.net.ssl.SSLEngine; /** * A {@link ByteBuffer} pool dedicated for {@link SslHandler} performance * improvement. *

* In most cases, you won't need to create a new pool instance because * {@link SslHandler} has a default pool instance internally. *

* The reason why {@link SslHandler} requires a buffer pool is because the * current {@link SSLEngine} implementation always requires a 17KiB buffer for * every 'wrap' and 'unwrap' operation. In most cases, the actual size of the * required buffer is much smaller than that, and therefore allocating a 17KiB * buffer for every 'wrap' and 'unwrap' operation wastes a lot of memory * bandwidth, resulting in the application performance degradation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 442 $, $Date: 2008-11-06 18:26:21 -0800 (Thu, 06 Nov 2008) $ */ public class SslBufferPool { // Add 1024 as a room for compressed data. private static final int MAX_PACKET_SIZE = 16665 + 1024; private static final int DEFAULT_POOL_SIZE = MAX_PACKET_SIZE * 1024; private final ByteBuffer[] pool; private final int maxBufferCount; private int index; /** * Creates a new buffer pool whose size is {@code 18113536}, which can * hold {@code 1024} buffers. */ public SslBufferPool() { this(DEFAULT_POOL_SIZE); } /** * Creates a new buffer pool. * * @param maxPoolSize the maximum number of bytes that this pool can hold */ public SslBufferPool(int maxPoolSize) { if (maxPoolSize <= 0) { throw new IllegalArgumentException("maxPoolSize: " + maxPoolSize); } int maxBufferCount = maxPoolSize / MAX_PACKET_SIZE; if (maxPoolSize % MAX_PACKET_SIZE != 0) { maxBufferCount ++; } pool = new ByteBuffer[maxBufferCount]; this.maxBufferCount = maxBufferCount; } /** * Returns the maximum size of this pool in byte unit. The returned value * can be somewhat different from what was specified in the constructor. */ public int getMaxPoolSize() { return maxBufferCount * MAX_PACKET_SIZE; } /** * Returns the number of bytes which were allocated but have not been * acquired yet. You can estimate how optimal the specified maximum pool * size is from this value. If it keeps returning {@code 0}, it means the * pool is getting exhausted. If it keeps returns a unnecessarily big * value, it means the pool is wasting the heap space. */ public synchronized int getUnacquiredPoolSize() { return index * MAX_PACKET_SIZE; } synchronized ByteBuffer acquire() { if (index == 0) { return ByteBuffer.allocate(MAX_PACKET_SIZE); } else { return (ByteBuffer) pool[-- index].clear(); } } synchronized void release(ByteBuffer buffer) { if (index < maxBufferCount) { pool[index ++] = buffer; } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/ssl/SslHandler.java0000644000175000017500000007753111211705163027723 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.ssl; import static org.jboss.netty.channel.Channels.*; import java.io.IOException; import java.nio.ByteBuffer; import java.nio.channels.ClosedChannelException; import java.util.LinkedList; import java.util.Queue; import java.util.concurrent.Executor; import java.util.concurrent.atomic.AtomicBoolean; import java.util.regex.Pattern; import javax.net.ssl.SSLEngine; import javax.net.ssl.SSLEngineResult; import javax.net.ssl.SSLException; import javax.net.ssl.SSLEngineResult.HandshakeStatus; import javax.net.ssl.SSLEngineResult.Status; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.DownstreamMessageEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.frame.FrameDecoder; import org.jboss.netty.logging.InternalLogger; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.ImmediateExecutor; /** * Adds SSL * · TLS and StartTLS support to a {@link Channel}. Please refer * to the "SecureChat" example in the distribution or the web * site for the detailed usage. * *

Beginning the handshake

*

* A user should make sure not to write a message while the * {@linkplain #handshake(Channel) handshake} is in progress unless it is a * renegotiation. You will be notified by the {@link ChannelFuture} which is * returned by the {@link #handshake(Channel)} method when the handshake * process succeeds or fails. * *

Renegotiation

*

* Once the initial handshake is done successfully. You can always call * {@link #handshake(Channel)} again to renegotiate the SSL session parameters. * *

Closing the session

*

* To close the SSL session, the {@link #close(Channel)} method should be * called to send the {@code close_notify} message to the remote peer. One * exception is when you close the {@link Channel} - {@link SslHandler} * intercepts the close request and send the {@code close_notify} message * before the channel closure automatically. Once the SSL session is closed, * it is not reusable, and consequently you should create a new * {@link SslHandler} with a new {@link SSLEngine} as explained in the * following section. * *

Restarting the session

*

* To restart the SSL session, you must remove the existing closed * {@link SslHandler} from the {@link ChannelPipeline}, insert a new * {@link SslHandler} with a new {@link SSLEngine} into the pipeline, * and start the handshake process as described in the first section. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1325 $, $Date: 2009-06-04 01:48:51 -0700 (Thu, 04 Jun 2009) $ * * @apiviz.landmark * @apiviz.uses org.jboss.netty.handler.ssl.SslBufferPool */ public class SslHandler extends FrameDecoder implements ChannelDownstreamHandler { private static final InternalLogger logger = InternalLoggerFactory.getInstance(SslHandler.class); private static final ByteBuffer EMPTY_BUFFER = ByteBuffer.allocate(0); private static final Pattern IGNORABLE_ERROR_MESSAGE = Pattern.compile( "^.*(?:connection.*reset|connection.*closed|broken.*pipe).*$", Pattern.CASE_INSENSITIVE); private static SslBufferPool defaultBufferPool; /** * Returns the default {@link SslBufferPool} used when no pool is * specified in the constructor. */ public static synchronized SslBufferPool getDefaultBufferPool() { if (defaultBufferPool == null) { defaultBufferPool = new SslBufferPool(); } return defaultBufferPool; } private final SSLEngine engine; private final SslBufferPool bufferPool; private final Executor delegatedTaskExecutor; private final boolean startTls; final Object handshakeLock = new Object(); private boolean initialHandshake; private boolean handshaking; private volatile boolean handshaken; private volatile ChannelFuture handshakeFuture; private final AtomicBoolean sentFirstMessage = new AtomicBoolean(); private final AtomicBoolean sentCloseNotify = new AtomicBoolean(); int ignoreClosedChannelException; final Object ignoreClosedChannelExceptionLock = new Object(); private final Queue pendingUnencryptedWrites = new LinkedList(); private final Queue pendingEncryptedWrites = new LinkedList(); /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use */ public SslHandler(SSLEngine engine) { this(engine, getDefaultBufferPool(), ImmediateExecutor.INSTANCE); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param bufferPool the {@link SslBufferPool} where this handler will * acquire the buffers required by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool) { this(engine, bufferPool, ImmediateExecutor.INSTANCE); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param startTls {@code true} if the first write request shouldn't be * encrypted by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, boolean startTls) { this(engine, getDefaultBufferPool(), startTls); } /** * Creates a new instance. * * @param engine the {@link SSLEngine} this handler will use * @param bufferPool the {@link SslBufferPool} where this handler will * acquire the buffers required by the {@link SSLEngine} * @param startTls {@code true} if the first write request shouldn't be * encrypted by the {@link SSLEngine} */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls) { this(engine, bufferPool, startTls, ImmediateExecutor.INSTANCE); } /** * Creates a new instance. * * @param engine * the {@link SSLEngine} this handler will use * @param delegatedTaskExecutor * the {@link Executor} which will execute the delegated task * that {@link SSLEngine#getDelegatedTask()} will return */ public SslHandler(SSLEngine engine, Executor delegatedTaskExecutor) { this(engine, getDefaultBufferPool(), delegatedTaskExecutor); } /** * Creates a new instance. * * @param engine * the {@link SSLEngine} this handler will use * @param bufferPool * the {@link SslBufferPool} where this handler will acquire * the buffers required by the {@link SSLEngine} * @param delegatedTaskExecutor * the {@link Executor} which will execute the delegated task * that {@link SSLEngine#getDelegatedTask()} will return */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool, Executor delegatedTaskExecutor) { this(engine, bufferPool, false, delegatedTaskExecutor); } /** * Creates a new instance. * * @param engine * the {@link SSLEngine} this handler will use * @param startTls * {@code true} if the first write request shouldn't be encrypted * by the {@link SSLEngine} * @param delegatedTaskExecutor * the {@link Executor} which will execute the delegated task * that {@link SSLEngine#getDelegatedTask()} will return */ public SslHandler(SSLEngine engine, boolean startTls, Executor delegatedTaskExecutor) { this(engine, getDefaultBufferPool(), startTls, delegatedTaskExecutor); } /** * Creates a new instance. * * @param engine * the {@link SSLEngine} this handler will use * @param bufferPool * the {@link SslBufferPool} where this handler will acquire * the buffers required by the {@link SSLEngine} * @param startTls * {@code true} if the first write request shouldn't be encrypted * by the {@link SSLEngine} * @param delegatedTaskExecutor * the {@link Executor} which will execute the delegated task * that {@link SSLEngine#getDelegatedTask()} will return */ public SslHandler(SSLEngine engine, SslBufferPool bufferPool, boolean startTls, Executor delegatedTaskExecutor) { if (engine == null) { throw new NullPointerException("engine"); } if (bufferPool == null) { throw new NullPointerException("bufferPool"); } if (delegatedTaskExecutor == null) { throw new NullPointerException("delegatedTaskExecutor"); } this.engine = engine; this.bufferPool = bufferPool; this.delegatedTaskExecutor = delegatedTaskExecutor; this.startTls = startTls; } /** * Returns the {@link SSLEngine} which is used by this handler. */ public SSLEngine getEngine() { return engine; } /** * Starts an SSL / TLS handshake for the specified channel. * * @return a {@link ChannelFuture} which is notified when the handshake * succeeds or fails. */ public ChannelFuture handshake(Channel channel) throws SSLException { ChannelFuture handshakeFuture; synchronized (handshakeLock) { if (handshaking) { return this.handshakeFuture; } else { engine.beginHandshake(); runDelegatedTasks(); handshakeFuture = this.handshakeFuture = newHandshakeFuture(channel); handshaking = true; } } wrapNonAppData(context(channel), channel); return handshakeFuture; } /** * Sends an SSL {@code close_notify} message to the specified channel and * destroys the underlying {@link SSLEngine}. */ public ChannelFuture close(Channel channel) throws SSLException { ChannelHandlerContext ctx = context(channel); engine.closeOutbound(); return wrapNonAppData(ctx, channel); } private ChannelHandlerContext context(Channel channel) { return channel.getPipeline().getContext(getClass()); } public void handleDownstream( final ChannelHandlerContext context, final ChannelEvent evt) throws Exception { if (evt instanceof ChannelStateEvent) { ChannelStateEvent e = (ChannelStateEvent) evt; switch (e.getState()) { case OPEN: case CONNECTED: case BOUND: if (Boolean.FALSE.equals(e.getValue()) || e.getValue() == null) { closeOutboundAndChannel(context, e); return; } } } if (!(evt instanceof MessageEvent)) { context.sendDownstream(evt); return; } MessageEvent e = (MessageEvent) evt; if (!(e.getMessage() instanceof ChannelBuffer)) { context.sendDownstream(evt); return; } // Do not encrypt the first write request if this handler is // created with startTLS flag turned on. if (startTls && sentFirstMessage.compareAndSet(false, true)) { context.sendDownstream(evt); return; } // Otherwise, all messages are encrypted. ChannelBuffer msg = (ChannelBuffer) e.getMessage(); PendingWrite pendingWrite = new PendingWrite(evt.getFuture(), msg.toByteBuffer(msg.readerIndex(), msg.readableBytes())); synchronized (pendingUnencryptedWrites) { boolean offered = pendingUnencryptedWrites.offer(pendingWrite); assert offered; } wrap(context, evt.getChannel()); } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Make sure the handshake future is notified when a connection has // been closed during handshake. synchronized (handshakeLock) { if (handshaking) { handshakeFuture.setFailure(new ClosedChannelException()); } } try { super.channelDisconnected(ctx, e); } finally { unwrap(ctx, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0); engine.closeOutbound(); if (!sentCloseNotify.get() && handshaken) { try { engine.closeInbound(); } catch (SSLException ex) { logger.debug("Failed to clean up SSLEngine.", ex); } } } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Throwable cause = e.getCause(); if (cause instanceof IOException) { if (cause instanceof ClosedChannelException) { synchronized (ignoreClosedChannelExceptionLock) { if (ignoreClosedChannelException > 0) { ignoreClosedChannelException --; logger.debug( "Swallowing an exception raised while " + "writing non-app data", cause); return; } } } else if (engine.isOutboundDone()) { String message = String.valueOf(cause.getMessage()).toLowerCase(); if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) { // It is safe to ignore the 'connection reset by peer' or // 'broken pipe' error after sending closure_notify. logger.debug( "Swallowing a 'connection reset by peer / " + "broken pipe' error occurred while writing " + "'closure_notify'", cause); // Close the connection explicitly just in case the transport // did not close the connection automatically. Channels.close(ctx, succeededFuture(e.getChannel())); return; } } } ctx.sendUpstream(e); } @Override protected Object decode( final ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (buffer.readableBytes() < 2) { return null; } int packetLength = buffer.getShort(buffer.readerIndex()) & 0xFFFF; if ((packetLength & 0x8000) != 0) { // Detected a SSLv2 packet packetLength &= 0x7FFF; packetLength += 2; } else if (buffer.readableBytes() < 5) { return null; } else { // Detected a SSLv3 / TLSv1 packet packetLength = (buffer.getShort(buffer.readerIndex() + 3) & 0xFFFF) + 5; } if (buffer.readableBytes() < packetLength) { return null; } ChannelBuffer frame; try { frame = unwrap(ctx, channel, buffer, buffer.readerIndex(), packetLength); } finally { buffer.skipBytes(packetLength); } return frame; } private ChannelFuture wrap(ChannelHandlerContext context, Channel channel) throws SSLException { ChannelFuture future = null; ChannelBuffer msg; ByteBuffer outNetBuf = bufferPool.acquire(); boolean success = true; boolean offered = false; boolean needsUnwrap = false; try { loop: for (;;) { // Acquire a lock to make sure unencrypted data is polled // in order and their encrypted counterpart is offered in // order. synchronized (pendingUnencryptedWrites) { PendingWrite pendingWrite = pendingUnencryptedWrites.peek(); if (pendingWrite == null) { break; } ByteBuffer outAppBuf = pendingWrite.outAppBuf; SSLEngineResult result = null; try { synchronized (handshakeLock) { result = engine.wrap(outAppBuf, outNetBuf); } } finally { if (!outAppBuf.hasRemaining()) { pendingUnencryptedWrites.remove(); } } if (result.bytesProduced() > 0) { outNetBuf.flip(); msg = ChannelBuffers.buffer(outNetBuf.remaining()); msg.writeBytes(outNetBuf.array(), 0, msg.capacity()); outNetBuf.clear(); if (pendingWrite.outAppBuf.hasRemaining()) { // pendingWrite's future shouldn't be notified if // only partial data is written. future = succeededFuture(channel); } else { future = pendingWrite.future; } MessageEvent encryptedWrite = new DownstreamMessageEvent( channel, future, msg, channel.getRemoteAddress()); if (Thread.holdsLock(pendingEncryptedWrites)) { offered = pendingEncryptedWrites.offer(encryptedWrite); } else { synchronized (pendingEncryptedWrites) { offered = pendingEncryptedWrites.offer(encryptedWrite); } } assert offered; } else { HandshakeStatus handshakeStatus = result.getHandshakeStatus(); switch (handshakeStatus) { case NEED_WRAP: if (outAppBuf.hasRemaining()) { break; } else { break loop; } case NEED_UNWRAP: needsUnwrap = true; break loop; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: case NOT_HANDSHAKING: if (handshakeStatus == HandshakeStatus.FINISHED) { setHandshakeSuccess(channel); } if (result.getStatus() == Status.CLOSED) { success = false; } break loop; default: throw new IllegalStateException( "Unknown handshake status: " + result.getHandshakeStatus()); } } } } } catch (SSLException e) { success = false; setHandshakeFailure(channel, e); throw e; } finally { bufferPool.release(outNetBuf); if (offered) { flushPendingEncryptedWrites(context); } if (!success) { IllegalStateException cause = new IllegalStateException("SSLEngine already closed"); // Mark all remaining pending writes as failure if anything // wrong happened before the write requests are wrapped. // Please note that we do not call setFailure while a lock is // acquired, to avoid a potential dead lock. for (;;) { PendingWrite pendingWrite; synchronized (pendingUnencryptedWrites) { pendingWrite = pendingUnencryptedWrites.poll(); if (pendingWrite == null) { break; } } pendingWrite.future.setFailure(cause); } } } if (needsUnwrap) { unwrap(context, channel, ChannelBuffers.EMPTY_BUFFER, 0, 0); } if (future == null) { future = succeededFuture(channel); } return future; } private void flushPendingEncryptedWrites(ChannelHandlerContext ctx) { // Avoid possible dead lock and data integrity issue // which is caused by cross communication between more than one channel // in the same VM. if (Thread.holdsLock(pendingEncryptedWrites)) { return; } synchronized (pendingEncryptedWrites) { if (pendingEncryptedWrites.isEmpty()) { return; } } synchronized (pendingEncryptedWrites) { MessageEvent e; while ((e = pendingEncryptedWrites.poll()) != null) { ctx.sendDownstream(e); } } } private ChannelFuture wrapNonAppData(ChannelHandlerContext ctx, Channel channel) throws SSLException { ChannelFuture future = null; ByteBuffer outNetBuf = bufferPool.acquire(); SSLEngineResult result; try { for (;;) { synchronized (handshakeLock) { result = engine.wrap(EMPTY_BUFFER, outNetBuf); } if (result.bytesProduced() > 0) { outNetBuf.flip(); ChannelBuffer msg = ChannelBuffers.buffer(outNetBuf.remaining()); msg.writeBytes(outNetBuf.array(), 0, msg.capacity()); outNetBuf.clear(); future = future(channel); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.getCause() instanceof ClosedChannelException) { synchronized (ignoreClosedChannelExceptionLock) { ignoreClosedChannelException ++; } } } }); write(ctx, future, msg); } switch (result.getHandshakeStatus()) { case FINISHED: setHandshakeSuccess(channel); runDelegatedTasks(); break; case NEED_TASK: runDelegatedTasks(); break; case NEED_UNWRAP: if (!Thread.holdsLock(handshakeLock)) { // unwrap shouldn't be called when this method was // called by unwrap - unwrap will keep running after // this method returns. unwrap(ctx, channel, ChannelBuffers.EMPTY_BUFFER, 0, 0); } break; case NOT_HANDSHAKING: case NEED_WRAP: break; default: throw new IllegalStateException( "Unexpected handshake status: " + result.getHandshakeStatus()); } if (result.bytesProduced() == 0) { break; } } } catch (SSLException e) { setHandshakeFailure(channel, e); throw e; } finally { bufferPool.release(outNetBuf); } if (future == null) { future = succeededFuture(channel); } return future; } private ChannelBuffer unwrap( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, int offset, int length) throws SSLException { ByteBuffer inNetBuf = buffer.toByteBuffer(offset, length); ByteBuffer outAppBuf = bufferPool.acquire(); try { boolean needsWrap = false; loop: for (;;) { SSLEngineResult result; synchronized (handshakeLock) { if (initialHandshake && !engine.getUseClientMode() && !engine.isInboundDone() && !engine.isOutboundDone()) { handshake(channel); initialHandshake = false; } try { result = engine.unwrap(inNetBuf, outAppBuf); } catch (SSLException e) { throw e; } switch (result.getHandshakeStatus()) { case NEED_UNWRAP: if (inNetBuf.hasRemaining() && !engine.isInboundDone()) { break; } else { break loop; } case NEED_WRAP: wrapNonAppData(ctx, channel); break; case NEED_TASK: runDelegatedTasks(); break; case FINISHED: setHandshakeSuccess(channel); needsWrap = true; break loop; case NOT_HANDSHAKING: needsWrap = true; break loop; default: throw new IllegalStateException( "Unknown handshake status: " + result.getHandshakeStatus()); } } } if (needsWrap) { // wrap() acquires pendingUnencryptedWrites first and then // handshakeLock. If handshakeLock is already hold by the // current thread, calling wrap() will lead to a dead lock // i.e. pendingUnencryptedWrites -> handshakeLock vs. // handshakeLock -> pendingUnencryptedLock -> handshakeLock if (!Thread.holdsLock(handshakeLock)) { wrap(ctx, channel); } } outAppBuf.flip(); if (outAppBuf.hasRemaining()) { ChannelBuffer frame = ChannelBuffers.buffer(outAppBuf.remaining()); frame.writeBytes(outAppBuf.array(), 0, frame.capacity()); return frame; } else { return null; } } catch (SSLException e) { setHandshakeFailure(channel, e); throw e; } finally { bufferPool.release(outAppBuf); } } private void runDelegatedTasks() { for (;;) { final Runnable task; synchronized (handshakeLock) { task = engine.getDelegatedTask(); } if (task == null) { break; } delegatedTaskExecutor.execute(new Runnable() { public void run() { synchronized (handshakeLock) { task.run(); } } }); } } private void setHandshakeSuccess(Channel channel) { synchronized (handshakeLock) { handshaking = false; handshaken = true; if (handshakeFuture == null) { handshakeFuture = newHandshakeFuture(channel); } } handshakeFuture.setSuccess(); } private void setHandshakeFailure(Channel channel, SSLException cause) { synchronized (handshakeLock) { if (!handshaking) { return; } handshaking = false; handshaken = false; if (handshakeFuture == null) { handshakeFuture = newHandshakeFuture(channel); } } handshakeFuture.setFailure(cause); } private void closeOutboundAndChannel( final ChannelHandlerContext context, final ChannelStateEvent e) throws SSLException { if (!e.getChannel().isConnected()) { context.sendDownstream(e); return; } unwrap(context, e.getChannel(), ChannelBuffers.EMPTY_BUFFER, 0, 0); if (!engine.isInboundDone()) { if (sentCloseNotify.compareAndSet(false, true)) { engine.closeOutbound(); ChannelFuture closeNotifyFuture = wrapNonAppData(context, e.getChannel()); closeNotifyFuture.addListener( new ClosingChannelFutureListener(context, e)); return; } } context.sendDownstream(e); } private static ChannelFuture newHandshakeFuture(Channel channel) { ChannelFuture future = future(channel); future.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (!future.isSuccess()) { fireExceptionCaught(future.getChannel(), future.getCause()); } } }); return future; } private static final class PendingWrite { final ChannelFuture future; final ByteBuffer outAppBuf; PendingWrite(ChannelFuture future, ByteBuffer outAppBuf) { this.future = future; this.outAppBuf = outAppBuf; } } private static final class ClosingChannelFutureListener implements ChannelFutureListener { private final ChannelHandlerContext context; private final ChannelStateEvent e; ClosingChannelFutureListener( ChannelHandlerContext context, ChannelStateEvent e) { this.context = context; this.e = e; } public void operationComplete(ChannelFuture closeNotifyFuture) throws Exception { if (!(closeNotifyFuture.getCause() instanceof ClosedChannelException)) { Channels.close(context, e.getFuture()); } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/ssl/package-info.java0000644000175000017500000000227011057665104030204 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * SSL · * TLS implementation based on {@link javax.net.ssl.SSLEngine} */ package org.jboss.netty.handler.ssl;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/0000755000175000017500000000000011316313152025257 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/protobuf/0000755000175000017500000000000011316313147027123 5ustar deckerdecker././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufDecoder.ja0000644000175000017500000001046411131122244032521 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.protobuf; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferInputStream; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.frame.FrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; import com.google.protobuf.ExtensionRegistry; import com.google.protobuf.Message; /** * Decodes a received {@link ChannelBuffer} into a * Google Protocol Buffers * {@link Message}. Please note that this decoder must be used with a proper * {@link FrameDecoder} such as {@link LengthFieldBasedFrameDecoder} if you are * using a stream-based transport such as TCP/IP. A typical setup for TCP/IP * would be: *

 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder",
 *                  new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
 * pipeline.addLast("protobufDecoder",
 *                  new {@link ProtobufDecoder}(MyMessage.getDefaultInstance()));
 *
 * // Encoder
 * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4));
 * pipeline.addLast("protobufEncoder", new {@link ProtobufEncoder}());
 * 
* and then you can use a {@code MyMessage} instead of a {@link ChannelBuffer} * as a message: *
 * void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     MyMessage req = (MyMessage) e.getMessage();
 *     MyMessage res = MyMessage.newBuilder().setText(
 *                               "Did you say '" + req.getText() + "'?").build();
 *     ch.write(res);
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ @ChannelPipelineCoverage("all") public class ProtobufDecoder extends OneToOneDecoder { private final Message prototype; private final ExtensionRegistry extensionRegistry; /** * Creates a new instance. */ public ProtobufDecoder(Message prototype) { this(prototype, null); } public ProtobufDecoder(Message prototype, ExtensionRegistry extensionRegistry) { if (prototype == null) { throw new NullPointerException("prototype"); } this.prototype = prototype.getDefaultInstanceForType(); this.extensionRegistry = extensionRegistry; } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof ChannelBuffer)) { return msg; } if (extensionRegistry == null) { return prototype.newBuilderForType().mergeFrom( new ChannelBufferInputStream((ChannelBuffer) msg)).build(); } else { return prototype.newBuilderForType().mergeFrom( new ChannelBufferInputStream((ChannelBuffer) msg), extensionRegistry).build(); } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/protobuf/ProtobufEncoder.ja0000644000175000017500000000642311131122244032533 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.protobuf; import static org.jboss.netty.buffer.ChannelBuffers.*; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; import com.google.protobuf.Message; /** * Encodes the requested Google * Protocol Buffers {@link Message} into a {@link ChannelBuffer}. * A typical setup for TCP/IP would be: *
 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder",
 *                  new {@link LengthFieldBasedFrameDecoder}(1048576, 0, 4, 0, 4));
 * pipeline.addLast("protobufDecoder",
 *                  new {@link ProtobufDecoder}(MyMessage.getDefaultInstance()));
 *
 * // Encoder
 * pipeline.addLast("frameEncoder", new {@link LengthFieldPrepender}(4));
 * pipeline.addLast("protobufEncoder", new {@link ProtobufEncoder}());
 * 
* and then you can use a {@code MyMessage} instead of a {@link ChannelBuffer} * as a message: *
 * void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     MyMessage req = (MyMessage) e.getMessage();
 *     MyMessage res = MyMessage.newBuilder().setText(
 *                               "Did you say '" + req.getText() + "'?").build();
 *     ch.write(res);
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ @ChannelPipelineCoverage("all") public class ProtobufEncoder extends OneToOneEncoder { /** * Creates a new instance. */ public ProtobufEncoder() { super(); } @Override protected Object encode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof Message)) { return msg; } return wrappedBuffer(((Message) msg).toByteArray()); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/protobuf/package-info.java0000644000175000017500000000242311126302065032307 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Encoder and decoder which transform a * Google Protocol Buffers * {@link com.google.protobuf.Message} into a {@link org.jboss.netty.buffer.ChannelBuffer} * and vice versa. */ package org.jboss.netty.handler.codec.protobuf;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/oneone/0000755000175000017500000000000011316313150026540 5ustar deckerdecker././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/oneone/OneToOneEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/oneone/OneToOneEncoder.java0000644000175000017500000000576411172027551032414 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.oneone; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; /** * Transforms a received message into another message. A typical setup for * TCP/IP would be: *
 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
 * pipeline.addLast("customDecoder", new {@link OneToOneDecoder}() { ... });
 *
 * // Encoder
 * pipeline.addLast("customEncoder", new {@link OneToOneEncoder}() { ... });
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ public abstract class OneToOneEncoder implements ChannelDownstreamHandler { protected OneToOneEncoder() { super(); } public void handleDownstream( ChannelHandlerContext ctx, ChannelEvent evt) throws Exception { if (!(evt instanceof MessageEvent)) { ctx.sendDownstream(evt); return; } MessageEvent e = (MessageEvent) evt; Object originalMessage = e.getMessage(); Object encodedMessage = encode(ctx, e.getChannel(), originalMessage); if (originalMessage == encodedMessage) { ctx.sendDownstream(evt); } else { write(ctx, e.getFuture(), encodedMessage, e.getRemoteAddress()); } } protected abstract Object encode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/oneone/package-info.java0000644000175000017500000000231411165344156031743 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Simplistic abstract classes which help implement encoder and decoder that * transform an object into another object and vice versa. * * @apiviz.exclude */ package org.jboss.netty.handler.codec.oneone;././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/oneone/OneToOneDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/oneone/OneToOneDecoder.java0000644000175000017500000000646111172027704032375 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.oneone; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.frame.FrameDecoder; /** * Transforms a received message into another message. Please note that this * decoder must be used with a proper {@link FrameDecoder} such as * {@link DelimiterBasedFrameDecoder} if you are using a stream-based transport * such as TCP/IP. A typical setup for TCP/IP would be: *
 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
 * pipeline.addLast("customDecoder", new {@link OneToOneDecoder}() { ... });
 *
 * // Encoder
 * pipeline.addLast("customEncoder", new {@link OneToOneEncoder}() { ... });
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ public abstract class OneToOneDecoder implements ChannelUpstreamHandler { /** * Creates a new instance with the current system character set. */ protected OneToOneDecoder() { super(); } public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent evt) throws Exception { if (!(evt instanceof MessageEvent)) { ctx.sendUpstream(evt); return; } MessageEvent e = (MessageEvent) evt; Object originalMessage = e.getMessage(); Object decodedMessage = decode(ctx, e.getChannel(), originalMessage); if (originalMessage == decodedMessage) { ctx.sendUpstream(evt); } else { fireMessageReceived(ctx, decodedMessage, e.getRemoteAddress()); } } protected abstract Object decode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception; } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/0000755000175000017500000000000011316313151027025 5ustar deckerdecker././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/CodecEmbedder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/CodecEmbedder.java0000644000175000017500000000542411216420766032354 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; /** * A helper that wraps an encoder or a decoder (codec) so that they can be used * without doing actual I/O in unit tests or higher level codecs. Please refer * to {@link EncoderEmbedder} and {@link DecoderEmbedder} for more information. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1436 $, $Date: 2009-06-18 04:16:06 -0700 (Thu, 18 Jun 2009) $ */ public interface CodecEmbedder { /** * Offers an input object to the pipeline of this embedder. * * @return {@code true} if and only if there is something to read in the * product queue (see {@link #poll()} and {@link #peek()}) */ boolean offer(Object input); /** * Signals the pipeline that the encoding or decoding has been finished and * no more data will be offered. * * @return {@code true} if and only if there is something to read in the * product queue (see {@link #poll()} and {@link #peek()}) */ boolean finish(); /** * Consumes an encoded or decoded output from the product queue. The output * object is generated by the offered input objects. * * @return an encoded or decoded object. * {@code null} if and only if there is no output object left in the * product queue. */ T poll(); /** * Reads an encoded or decoded output from the head of the product queue. * The difference from {@link #poll()} is that it does not remove the * retrieved object from the product queue. * * @return an encoded or decoded object. * {@code null} if and only if there is no output object left in the * product queue. */ T peek(); } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EmbeddedChannel.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EmbeddedChannel.ja0000644000175000017500000000440511150050430032320 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; import java.net.SocketAddress; import org.jboss.netty.channel.AbstractChannel; import org.jboss.netty.channel.ChannelConfig; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.DefaultChannelConfig; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 924 $, $Date: 2009-02-21 11:08:08 -0800 (Sat, 21 Feb 2009) $ */ class EmbeddedChannel extends AbstractChannel { private final ChannelConfig config; private final SocketAddress localAddress = new EmbeddedSocketAddress(); private final SocketAddress remoteAddress = new EmbeddedSocketAddress(); EmbeddedChannel(ChannelPipeline pipeline, ChannelSink sink) { super(null, EmbeddedChannelFactory.INSTANCE, pipeline, sink); config = new DefaultChannelConfig(); } public ChannelConfig getConfig() { return config; } public SocketAddress getLocalAddress() { return localAddress; } public SocketAddress getRemoteAddress() { return remoteAddress; } public boolean isBound() { return true; } public boolean isConnected() { return true; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EmbeddedSocketAddress.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EmbeddedSocketAddr0000644000175000017500000000266511115436262032424 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; import java.net.SocketAddress; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 566 $, $Date: 2008-12-03 00:00:50 -0800 (Wed, 03 Dec 2008) $ */ class EmbeddedSocketAddress extends SocketAddress { private static final long serialVersionUID = 1400788804624980619L; EmbeddedSocketAddress() { super(); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EmbeddedChannelFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EmbeddedChannelFac0000644000175000017500000000336711142471446032366 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelPipeline; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 759 $, $Date: 2009-02-04 21:03:34 -0800 (Wed, 04 Feb 2009) $ */ class EmbeddedChannelFactory implements ChannelFactory { static final ChannelFactory INSTANCE = new EmbeddedChannelFactory(); private EmbeddedChannelFactory() { super(); } public Channel newChannel(ChannelPipeline pipeline) { throw new UnsupportedOperationException(); } public void releaseExternalResources() { // No external resources } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/CodecEmbedderException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/CodecEmbedderExcep0000644000175000017500000000401611216420766032415 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; /** * A {@link RuntimeException} which is thrown when a {@link CodecEmbedder} * failed to encode or decode the specified input. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1436 $, $Date: 2009-06-18 04:16:06 -0700 (Thu, 18 Jun 2009) $ * * @apiviz.exclude */ public class CodecEmbedderException extends RuntimeException { private static final long serialVersionUID = -6283302594160331474L; /** * Creates a new instance. */ public CodecEmbedderException() { super(); } /** * Creates a new instance. */ public CodecEmbedderException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public CodecEmbedderException(String message) { super(message); } /** * Creates a new instance. */ public CodecEmbedderException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EncoderEmbedder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/EncoderEmbedder.ja0000644000175000017500000000611511216652714032365 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.codec.base64.Base64Encoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * A helper that wraps an encoder so that it can be used without doing actual * I/O in unit tests or higher level codecs. For example, you can encode a * {@link String} into a Base64-encoded {@link ChannelBuffer} with * {@link Base64Encoder} and {@link StringEncoder} without setting up the * {@link ChannelPipeline} and other mock objects by yourself: *
 * String data = "foobar";
 *
 * EncoderEmbedder<ChannelBuffer> embedder = new EncoderEmbedder<ChannelBuffer>(
 *         new Base64Encoder(), new StringEncoder());
 *
 * embedded.offer(data);
 *
 * ChannelBuffer encoded = embedded.poll();
 * assert encoded.toString("ASCII").equals("Zm9vYmFy");
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1453 $, $Date: 2009-06-19 02:09:32 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.landmark * @see DecoderEmbedder */ public class EncoderEmbedder extends AbstractCodecEmbedder { /** * Creates a new embedder whose pipeline is composed of the specified * handlers. */ public EncoderEmbedder(ChannelDownstreamHandler... handlers) { super(handlers); } /** * Creates a new embedder whose pipeline is composed of the specified * handlers. * * @param bufferFactory the {@link ChannelBufferFactory} to be used when * creating a new buffer. */ public EncoderEmbedder(ChannelBufferFactory bufferFactory, ChannelDownstreamHandler... handlers) { super(bufferFactory, handlers); } public boolean offer(Object input) { write(getChannel(), input).setSuccess(); return !isEmpty(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/package-info.java0000644000175000017500000000227411216420766032233 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * A helper that wraps an encoder or a decoder so that they can be used without * doing actual I/O in unit tests or higher level codecs. */ package org.jboss.netty.handler.codec.embedder; ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/AbstractCodecEmbedder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/AbstractCodecEmbed0000644000175000017500000001516011216652714032423 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; import static org.jboss.netty.channel.Channels.*; import java.util.LinkedList; import java.util.Queue; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelPipelineException; import org.jboss.netty.channel.ChannelSink; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.DefaultChannelPipeline; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; /** * A skeletal {@link CodecEmbedder} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1453 $, $Date: 2009-06-19 02:09:32 -0700 (Fri, 19 Jun 2009) $ */ abstract class AbstractCodecEmbedder implements CodecEmbedder { private final Channel channel; private final ChannelPipeline pipeline; private final EmbeddedChannelSink sink = new EmbeddedChannelSink(); final Queue productQueue = new LinkedList(); /** * Creates a new embedder whose pipeline is composed of the specified * handlers. */ protected AbstractCodecEmbedder(ChannelHandler... handlers) { pipeline = new EmbeddedChannelPipeline(); configurePipeline(handlers); channel = new EmbeddedChannel(pipeline, sink); fireInitialEvents(); } /** * Creates a new embedder whose pipeline is composed of the specified * handlers. * * @param bufferFactory the {@link ChannelBufferFactory} to be used when * creating a new buffer. */ protected AbstractCodecEmbedder(ChannelBufferFactory bufferFactory, ChannelHandler... handlers) { this(handlers); getChannel().getConfig().setBufferFactory(bufferFactory); } private void fireInitialEvents() { // Fire the typical initial events. fireChannelOpen(channel); fireChannelBound(channel, channel.getLocalAddress()); fireChannelConnected(channel, channel.getRemoteAddress()); } private void configurePipeline(ChannelHandler... handlers) { if (handlers == null) { throw new NullPointerException("handlers"); } if (handlers.length == 0) { throw new IllegalArgumentException( "handlers should contain at least one " + ChannelHandler.class.getSimpleName() + '.'); } for (int i = 0; i < handlers.length; i ++) { ChannelHandler h = handlers[i]; if (h == null) { throw new NullPointerException("handlers[" + i + "]"); } pipeline.addLast(String.valueOf(i), handlers[i]); } pipeline.addLast("SINK", sink); } public boolean finish() { fireChannelDisconnected(channel); fireChannelUnbound(channel); fireChannelClosed(channel); return !productQueue.isEmpty(); } /** * Returns the virtual {@link Channel} which will be used as a mock * during encoding and decoding. */ protected final Channel getChannel() { return channel; } /** * Returns {@code true} if and only if the produce queue is empty and * therefore {@link #poll()} will return {@code null}. */ protected final boolean isEmpty() { return productQueue.isEmpty(); } @SuppressWarnings("unchecked") public final T poll() { return (T) productQueue.poll(); } @SuppressWarnings("unchecked") public final T peek() { return (T) productQueue.peek(); } @ChannelPipelineCoverage("all") private final class EmbeddedChannelSink implements ChannelSink, ChannelUpstreamHandler { EmbeddedChannelSink() { super(); } public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) { handleEvent(e); } public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) { handleEvent(e); } private void handleEvent(ChannelEvent e) { if (e instanceof MessageEvent) { boolean offered = productQueue.offer(((MessageEvent) e).getMessage()); assert offered; } else if (e instanceof ExceptionEvent) { throw new CodecEmbedderException(((ExceptionEvent) e).getCause()); } // Swallow otherwise. } public void exceptionCaught( ChannelPipeline pipeline, ChannelEvent e, ChannelPipelineException cause) throws Exception { Throwable actualCause = cause.getCause(); if (actualCause == null) { actualCause = cause; } throw new CodecEmbedderException(actualCause); } } private static final class EmbeddedChannelPipeline extends DefaultChannelPipeline { EmbeddedChannelPipeline() { super(); } @Override protected void notifyHandlerException(ChannelEvent e, Throwable t) { while (t instanceof ChannelPipelineException && t.getCause() != null) { t = t.getCause(); } if (t instanceof CodecEmbedderException) { throw (CodecEmbedderException) t; } else { throw new CodecEmbedderException(t); } } } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/DecoderEmbedder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/embedder/DecoderEmbedder.ja0000644000175000017500000000611011216652714032346 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.embedder; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.handler.codec.base64.Base64Decoder; import org.jboss.netty.handler.codec.string.StringDecoder; /** * A helper that wraps a decoder so that it can be used without doing actual * I/O in unit tests or higher level codecs. For example, you can decode a * Base64-encoded {@link ChannelBuffer} with {@link Base64Decoder} and * {@link StringDecoder} without setting up the {@link ChannelPipeline} and * other mock objects by yourself: *
 * ChannelBuffer base64Data = ChannelBuffer.copiedBuffer("Zm9vYmFy", "ASCII");
 *
 * DecoderEmbedder<String> embedder = new DecoderEmbedder<String>(
 *         new Base64Decoder(), new StringDecoder());
 *
 * embedded.offer(base64Data);
 *
 * String decoded = embedded.poll();
 * assert decoded.equals("foobar");
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1453 $, $Date: 2009-06-19 02:09:32 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.landmark * @see EncoderEmbedder */ public class DecoderEmbedder extends AbstractCodecEmbedder { /** * Creates a new embedder whose pipeline is composed of the specified * handlers. */ public DecoderEmbedder(ChannelUpstreamHandler... handlers) { super(handlers); } /** * Creates a new embedder whose pipeline is composed of the specified * handlers. * * @param bufferFactory the {@link ChannelBufferFactory} to be used when * creating a new buffer. */ public DecoderEmbedder(ChannelBufferFactory bufferFactory, ChannelUpstreamHandler... handlers) { super(bufferFactory, handlers); } public boolean offer(Object input) { fireMessageReceived(getChannel(), input); return !super.isEmpty(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/0000755000175000017500000000000011316313151026350 5ustar deckerdecker././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/CorruptedFrameException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/CorruptedFrameExcepti0000644000175000017500000000401711122162401032534 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; /** * An {@link Exception} which is thrown when the received frame data can not * be decoded by a {@link FrameDecoder} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.hidden */ public class CorruptedFrameException extends Exception { private static final long serialVersionUID = 3918052232492988408L; /** * Creates a new instance. */ public CorruptedFrameException() { super(); } /** * Creates a new instance. */ public CorruptedFrameException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public CorruptedFrameException(String message) { super(message); } /** * Creates a new instance. */ public CorruptedFrameException(Throwable cause) { super(cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/FrameDecoder.java0000644000175000017500000002752511215374110031546 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import java.net.SocketAddress; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Decodes the received {@link ChannelBuffer}s into a meaningful frame object. *

* In a stream-based transport such as TCP/IP, packets can be fragmented and * reassembled during transmission even in a LAN environment. For example, * let us assume you have received three packets: *

 * +-----+-----+-----+
 * | ABC | DEF | GHI |
 * +-----+-----+-----+
 * 
* because of the packet fragmentation, a server can receive them like the * following: *
 * +----+-------+---+---+
 * | AB | CDEFG | H | I |
 * +----+-------+---+---+
 * 
*

* {@link FrameDecoder} helps you defrag the received packets into one or more * meaningful frames that could be easily understood by the * application logic. In case of the example above, your {@link FrameDecoder} * implementation could defrag the received packets like the following: *

 * +-----+-----+-----+
 * | ABC | DEF | GHI |
 * +-----+-----+-----+
 * 
*

* The following code shows an example handler which decodes a frame whose * first 4 bytes header represents the length of the frame, excluding the * header. *

 * MESSAGE FORMAT
 * ==============
 *
 * Offset:  0        4                   (Length + 4)
 *          +--------+------------------------+
 * Fields:  | Length | Actual message content |
 *          +--------+------------------------+
 *
 * DECODER IMPLEMENTATION
 * ======================
 *
 * public class IntegerHeaderFrameDecoder extends FrameDecoder {
 *
 *   protected Object decode(ChannelHandlerContext ctx,
 *                           Channel channel,
 *                           ChannelBuffer buf) throws Exception {
 *
 *     // Make sure if the length field was received.
 *     if (buf.readableBytes() < 4) {
 *        // The length field was not received yet - return null.
 *        // This method will be invoked again when more packets are
 *        // received and appended to the buffer.
 *        return null;
 *     }
 *
 *     // The length field is in the buffer.
 *
 *     // Mark the current buffer position before reading the length field
 *     // because the whole frame might not be in the buffer yet.
 *     // We will reset the buffer position to the marked position if
 *     // there's not enough bytes in the buffer.
 *     buf.markReaderIndex();
 *
 *     // Read the length field.
 *     int length = buf.readInt();
 *
 *     // Make sure if there's enough bytes in the buffer.
 *     if (buf.readableBytes() < length) {
 *        // The whole bytes were not received yet - return null.
 *        // This method will be invoked again when more packets are
 *        // received and appended to the buffer.
 *
 *        // Reset to the marked position to read the length field again
 *        // next time.
 *        buf.resetReaderIndex();
 *
 *        return null;
 *     }
 *
 *     // There's enough bytes in the buffer. Read it.
 *     ChannelBuffer frame = buf.readBytes(length);
 *
 *     // Successfully decoded a frame.  Return the decoded frame.
 *     return frame;
 *   }
 * }
 * 
* *

Returning a POJO rather than a {@link ChannelBuffer}

*

* Please note that you can return an object of a different type than * {@link ChannelBuffer} in your {@code decode()} and {@code decodeLast()} * implementation. For example, you could return a * POJO so that the next * {@link ChannelUpstreamHandler} receives a {@link MessageEvent} which * contains a POJO rather than a {@link ChannelBuffer}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ @ChannelPipelineCoverage("one") public abstract class FrameDecoder extends SimpleChannelUpstreamHandler { private final boolean unfold; private final AtomicReference cumulation = new AtomicReference(); protected FrameDecoder() { this(false); } protected FrameDecoder(boolean unfold) { this.unfold = unfold; } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object m = e.getMessage(); if (!(m instanceof ChannelBuffer)) { ctx.sendUpstream(e); return; } ChannelBuffer input = (ChannelBuffer) m; if (!input.readable()) { return; } ChannelBuffer cumulation = cumulation(ctx); if (cumulation.readable()) { cumulation.discardReadBytes(); cumulation.writeBytes(input); callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress()); } else { callDecode(ctx, e.getChannel(), input, e.getRemoteAddress()); if (input.readable()) { cumulation.writeBytes(input); } } } @Override public void channelDisconnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { cleanup(ctx, e); } @Override public void channelClosed( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { cleanup(ctx, e); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { ctx.sendUpstream(e); } /** * Decodes the received packets so far into a frame. * * @param ctx the context of this handler * @param channel the current channel * @param buffer the cumulative buffer of received packets so far. * Note that the buffer might be empty, which means you * should not make an assumption that the buffer contains * at least one byte in your decoder implementation. * * @return the decoded frame if a full frame was received and decoded. * {@code null} if there's not enough data in the buffer to decode a frame. */ protected abstract Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception; /** * Decodes the received data so far into a frame when the channel is * disconnected. * * @param ctx the context of this handler * @param channel the current channel * @param buffer the cumulative buffer of received packets so far. * Note that the buffer might be empty, which means you * should not make an assumption that the buffer contains * at least one byte in your decoder implementation. * * @return the decoded frame if a full frame was received and decoded. * {@code null} if there's not enough data in the buffer to decode a frame. */ protected Object decodeLast( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { return decode(ctx, channel, buffer); } private void callDecode( ChannelHandlerContext context, Channel channel, ChannelBuffer cumulation, SocketAddress remoteAddress) throws Exception { while (cumulation.readable()) { int oldReaderIndex = cumulation.readerIndex(); Object frame = decode(context, channel, cumulation); if (frame == null) { if (oldReaderIndex == cumulation.readerIndex()) { // Seems like more data is required. // Let us wait for the next notification. break; } else { // Previous data has been discarded. // Probably it is reading on. continue; } } else if (oldReaderIndex == cumulation.readerIndex()) { throw new IllegalStateException( "decode() method must read at least one byte " + "if it returned a frame."); } unfoldAndFireMessageReceived(context, remoteAddress, frame); } } private void unfoldAndFireMessageReceived(ChannelHandlerContext context, SocketAddress remoteAddress, Object result) { if (unfold) { if (result instanceof Object[]) { for (Object r: (Object[]) result) { Channels.fireMessageReceived(context, r, remoteAddress); } } else if (result instanceof Iterable) { for (Object r: (Iterable) result) { Channels.fireMessageReceived(context, r, remoteAddress); } } else { Channels.fireMessageReceived(context, result, remoteAddress); } } else { Channels.fireMessageReceived(context, result, remoteAddress); } } private void cleanup(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { try { ChannelBuffer cumulation = this.cumulation.getAndSet(null); if (cumulation == null) { return; } if (cumulation.readable()) { // Make sure all frames are read before notifying a closed channel. callDecode(ctx, ctx.getChannel(), cumulation, null); } // Call decodeLast() finally. Please note that decodeLast() is // called even if there's nothing more to read from the buffer to // notify a user that the connection was closed explicitly. Object partialFrame = decodeLast(ctx, ctx.getChannel(), cumulation); if (partialFrame != null) { unfoldAndFireMessageReceived(ctx, null, partialFrame); } } finally { ctx.sendUpstream(e); } } private ChannelBuffer cumulation(ChannelHandlerContext ctx) { ChannelBuffer buf = cumulation.get(); if (buf == null) { buf = ChannelBuffers.dynamicBuffer( ctx.getChannel().getConfig().getBufferFactory()); if (!cumulation.compareAndSet(null, buf)) { buf = cumulation.get(); } } return buf; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/FixedLengthFrameDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/FixedLengthFrameDecod0000644000175000017500000000511511216431556032421 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; /** * A decoder that splits the received {@link ChannelBuffer}s by the fixed number * of bytes. For example, if you received the following four fragmented packets: *

 * +---+----+------+----+
 * | A | BC | DEFG | HI |
 * +---+----+------+----+
 * 
* A {@link FixedLengthFrameDecoder}{@code (3)} will decode them into the * following three packets with the fixed length: *
 * +-----+-----+-----+
 * | ABC | DEF | GHI |
 * +-----+-----+-----+
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ */ public class FixedLengthFrameDecoder extends FrameDecoder { private final int frameLength; /** * Creates a new instance. * * @param frameLength the length of the frame */ public FixedLengthFrameDecoder(int frameLength) { if (frameLength <= 0) { throw new IllegalArgumentException( "frameLength must be a positive integer: " + frameLength); } this.frameLength = frameLength; } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (buffer.readableBytes() < frameLength) { return null; } else { return buffer.readBytes(frameLength); } } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/DelimiterBasedFrameDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/DelimiterBasedFrameDe0000644000175000017500000002343311216431556032412 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; /** * A decoder that splits the received {@link ChannelBuffer}s by one or more * delimiters. It is particularly useful for decoding the frames which ends * with a delimiter such as {@link Delimiters#nulDelimiter() NUL} or * {@linkplain Delimiters#lineDelimiter() newline characters}. * *

Predefined delimiters

*

* {@link Delimiters} defines frequently used delimiters for convenience' sake. * *

Specifying more than one delimiter

*

* {@link DelimiterBasedFrameDecoder} allows you to specify more than one * delimiter. If more than one delimiter is found in the buffer, it chooses * the delimiter which produces the shortest frame. For example, if you have * the following data in the buffer: *

 * +--------------+
 * | ABC\nDEF\r\n |
 * +--------------+
 * 
* a {@link DelimiterBasedFrameDecoder}{@code (}{@link Delimiters#lineDelimiter() Delimiters.lineDelimiter()}{@code )} * will choose {@code '\n'} as the first delimiter and produce two frames: *
 * +-----+-----+
 * | ABC | DEF |
 * +-----+-----+
 * 
* rather than incorrectly choosing {@code '\r\n'} as the first delimiter: *
 * +----------+
 * | ABC\nDEF |
 * +----------+
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark * @apiviz.uses org.jboss.netty.handler.codec.frame.Delimiters - - optional yet useful */ public class DelimiterBasedFrameDecoder extends FrameDecoder { private final ChannelBuffer[] delimiters; private final int maxFrameLength; private final boolean stripDelimiter; private volatile boolean discardingTooLongFrame; private volatile long tooLongFrameLength; /** * Creates a new instance. * * @param maxFrameLength the maximum length of the decoded frame. * A {@link TooLongFrameException} is thrown if * the length of the frame exceeds this value. * @param delimiter the delimiter */ public DelimiterBasedFrameDecoder(int maxFrameLength, ChannelBuffer delimiter) { this(maxFrameLength, true, delimiter); } /** * Creates a new instance. * * @param maxFrameLength the maximum length of the decoded frame. * A {@link TooLongFrameException} is thrown if * the length of the frame exceeds this value. * @param stripDelimiter whether the decoded frame should strip out the * delimiter or not * @param delimiter the delimiter */ public DelimiterBasedFrameDecoder( int maxFrameLength, boolean stripDelimiter, ChannelBuffer delimiter) { validateMaxFrameLength(maxFrameLength); validateDelimiter(delimiter); delimiters = new ChannelBuffer[] { delimiter.slice( delimiter.readerIndex(), delimiter.readableBytes()) }; this.maxFrameLength = maxFrameLength; this.stripDelimiter = stripDelimiter; } /** * Creates a new instance. * * @param maxFrameLength the maximum length of the decoded frame. * A {@link TooLongFrameException} is thrown if * the length of the frame exceeds this value. * @param delimiters the delimiters */ public DelimiterBasedFrameDecoder(int maxFrameLength, ChannelBuffer... delimiters) { this(maxFrameLength, true, delimiters); } /** * Creates a new instance. * * @param maxFrameLength the maximum length of the decoded frame. * A {@link TooLongFrameException} is thrown if * the length of the frame exceeds this value. * @param stripDelimiter whether the decoded frame should strip out the * delimiter or not * @param delimiters the delimiters */ public DelimiterBasedFrameDecoder( int maxFrameLength, boolean stripDelimiter, ChannelBuffer... delimiters) { validateMaxFrameLength(maxFrameLength); if (delimiters == null) { throw new NullPointerException("delimiters"); } if (delimiters.length == 0) { throw new IllegalArgumentException("empty delimiters"); } this.delimiters = new ChannelBuffer[delimiters.length]; for (int i = 0; i < delimiters.length; i ++) { ChannelBuffer d = delimiters[i]; validateDelimiter(d); this.delimiters[i] = d.slice(d.readerIndex(), d.readableBytes()); } this.maxFrameLength = maxFrameLength; this.stripDelimiter = stripDelimiter; } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { // Try all delimiters and choose the delimiter which yields the shortest frame. int minFrameLength = Integer.MAX_VALUE; ChannelBuffer minDelim = null; for (ChannelBuffer delim: delimiters) { int frameLength = indexOf(buffer, delim); if (frameLength >= 0 && frameLength < minFrameLength) { minFrameLength = frameLength; minDelim = delim; } } if (minDelim != null) { int minDelimLength = minDelim.capacity(); ChannelBuffer frame; if (discardingTooLongFrame) { // We've just finished discarding a very large frame. // Throw an exception and go back to the initial state. long tooLongFrameLength = this.tooLongFrameLength; this.tooLongFrameLength = 0L; discardingTooLongFrame = false; buffer.skipBytes(minFrameLength + minDelimLength); fail(tooLongFrameLength + minFrameLength + minDelimLength); } if (minFrameLength > maxFrameLength) { // Discard read frame. buffer.skipBytes(minFrameLength + minDelimLength); fail(minFrameLength); } if (stripDelimiter) { frame = buffer.readBytes(minFrameLength); buffer.skipBytes(minDelimLength); } else { frame = buffer.readBytes(minFrameLength + minDelimLength); } return frame; } else { if (buffer.readableBytes() > maxFrameLength) { // Discard the content of the buffer until a delimiter is found. tooLongFrameLength = buffer.readableBytes(); buffer.skipBytes(buffer.readableBytes()); discardingTooLongFrame = true; } return null; } } private void fail(long frameLength) throws TooLongFrameException { throw new TooLongFrameException( "The frame length exceeds " + maxFrameLength + ": " + frameLength); } /** * Returns the number of bytes between the readerIndex of the haystack and * the first needle found in the haystack. -1 is returned if no needle is * found in the haystack. */ private static int indexOf(ChannelBuffer haystack, ChannelBuffer needle) { for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) { int haystackIndex = i; int needleIndex; for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) { if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) { break; } else { haystackIndex ++; if (haystackIndex == haystack.writerIndex() && needleIndex != needle.capacity() - 1) { return -1; } } } if (needleIndex == needle.capacity()) { // Found the needle from the haystack! return i - haystack.readerIndex(); } } return -1; } private static void validateDelimiter(ChannelBuffer delimiter) { if (delimiter == null) { throw new NullPointerException("delimiter"); } if (!delimiter.readable()) { throw new IllegalArgumentException("empty delimiter"); } } private static void validateMaxFrameLength(int maxFrameLength) { if (maxFrameLength <= 0) { throw new IllegalArgumentException( "maxFrameLength must be a positive integer: " + maxFrameLength); } } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/TooLongFrameException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/TooLongFrameException0000644000175000017500000000402411057647540032524 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; /** * An {@link Exception} which is thrown when the length of the frame * decoded by {@link DelimiterBasedFrameDecoder} is greater than the maximum. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.hidden */ public class TooLongFrameException extends Exception { private static final long serialVersionUID = -1995801950698951640L; /** * Creates a new instance. */ public TooLongFrameException() { super(); } /** * Creates a new instance. */ public TooLongFrameException(String message, Throwable cause) { super(message, cause); } /** * Creates a new instance. */ public TooLongFrameException(String message) { super(message); } /** * Creates a new instance. */ public TooLongFrameException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/LengthFieldBasedFrameDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/LengthFieldBasedFrame0000644000175000017500000003027311216431726032407 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; /** * A decoder that splits the received {@link ChannelBuffer}s dynamically by the * value of the length field in the message. It is particularly useful when you * decode a binary message which has an integer header field that represents the * length of the message body or the whole message. *

* {@link LengthFieldBasedFrameDecoder} has many configuration parameters so * that it can decode any message with a length field, which is often seen in * proprietary client-server protocols. Here are some example that will give * you the basic idea on which option does what. * *

2 bytes length field at offset 0, do not strip header

*
 * lengthFieldOffset   = 0
 * lengthFieldLength   = 2
 * lengthAdjustment    = 0 (default)
 * initialBytesToStrip = 0 (default)
 *
 * BEFORE DECODE (14 bytes)         AFTER DECODE (14 bytes)
 * +--------+----------------+      +--------+----------------+
 * | Length | Actual Content |----->| Length | Actual Content |
 * | 0x000C | "HELLO, WORLD" |      | 0x000C | "HELLO, WORLD" |
 * +--------+----------------+      +--------+----------------+
 * 
* *

2 bytes length field at offset 0, strip header

*
 * lengthFieldOffset   = 0
 * lengthFieldLength   = 2
 * lengthAdjustment    = 0
 * initialBytesToStrip = 2
 *
 * BEFORE DECODE (14 bytes)         AFTER DECODE (12 bytes)
 * +--------+----------------+      +----------------+
 * | Length | Actual Content |----->| Actual Content |
 * | 0x000C | "HELLO, WORLD" |      | "HELLO, WORLD" |
 * +--------+----------------+      +----------------+
 * 
* *

3 bytes length field at the end of 5 bytes header, strip header

*
 * lengthFieldOffset   = 2 (= 5 - 3)
 * lengthFieldLength   = 3
 * lengthAdjustment    = 0
 * initialBytesToStrip = 5
 *
 * BEFORE DECODE (17 bytes)                      AFTER DECODE (12 bytes)
 * +----------+----------+----------------+      +----------------+
 * | Header 1 |  Length  | Actual Content |----->| Actual Content |
 * |  0xCAFE  | 0x00000C | "HELLO, WORLD" |      | "HELLO, WORLD" |
 * +----------+----------+----------------+      +----------------+
 * 
* *

2 bytes length field at offset 1 in the middle of 4 bytes header, * strip the first header field and the length field

*
 * lengthFieldOffset   = 1
 * lengthFieldLength   = 2
 * lengthAdjustment    = 1 (= the length of HDR2)
 * initialBytesToStrip = 3 (= the length of HDR1 + LEN)
 *
 * BEFORE DECODE (16 bytes)                       AFTER DECODE (13 bytes)
 * +------+--------+------+----------------+      +------+----------------+
 * | HDR1 | Length | HDR2 | Actual Content |----->| HDR2 | Actual Content |
 * | 0xCA | 0x000C | 0xFE | "HELLO, WORLD" |      | 0xFE | "HELLO, WORLD" |
 * +------+--------+------+----------------+      +------+----------------+
 * 
* *

2 bytes length field at offset 1 in the middle of 4 bytes header, * strip the first header field and the length field, the length field * includes the header length

*
 * lengthFieldOffset   =  1
 * lengthFieldLength   =  2
 * lengthAdjustment    = -3 (= the length of HDR1 + LEN, negative)
 * initialBytesToStrip =  3
 *
 * BEFORE DECODE (16 bytes)                       AFTER DECODE (13 bytes)
 * +------+--------+------+----------------+      +------+----------------+
 * | HDR1 | Length | HDR2 | Actual Content |----->| HDR2 | Actual Content |
 * | 0xCA | 0x0010 | 0xFE | "HELLO, WORLD" |      | 0xFE | "HELLO, WORLD" |
 * +------+--------+------+----------------+      +------+----------------+
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark * @see LengthFieldPrepender */ public class LengthFieldBasedFrameDecoder extends FrameDecoder { private final int maxFrameLength; private final int lengthFieldOffset; private final int lengthFieldLength; private final int lengthFieldEndOffset; private final int lengthAdjustment; private final int initialBytesToStrip; private volatile boolean discardingTooLongFrame; private volatile long tooLongFrameLength; private volatile long bytesToDiscard; /** * Creates a new instance. * * @param maxFrameLength * the maximum length of the frame. If the length of the frame is * greater than this value, {@link TooLongFrameException} will be * thrown. * @param lengthFieldOffset * the offset of the length field * @param lengthFieldLength * the length of the length field * */ public LengthFieldBasedFrameDecoder( int maxFrameLength, int lengthFieldOffset, int lengthFieldLength) { this(maxFrameLength, lengthFieldOffset, lengthFieldLength, 0, 0); } /** * Creates a new instance. * * @param maxFrameLength * the maximum length of the frame. If the length of the frame is * greater than this value, {@link TooLongFrameException} will be * thrown. * @param lengthFieldOffset * the offset of the length field * @param lengthFieldLength * the length of the length field * @param lengthAdjustment * the compensation value to add to the value of the length field * @param initialBytesToStrip * the number of first bytes to strip out from the decoded frame */ public LengthFieldBasedFrameDecoder( int maxFrameLength, int lengthFieldOffset, int lengthFieldLength, int lengthAdjustment, int initialBytesToStrip) { if (maxFrameLength <= 0) { throw new IllegalArgumentException( "maxFrameLength must be a positive integer: " + maxFrameLength); } if (lengthFieldOffset < 0) { throw new IllegalArgumentException( "lengthFieldOffset must be a non-negative integer: " + lengthFieldOffset); } if (initialBytesToStrip < 0) { throw new IllegalArgumentException( "initialBytesToStrip must be a non-negative integer: " + initialBytesToStrip); } if (lengthFieldLength != 1 && lengthFieldLength != 2 && lengthFieldLength != 3 && lengthFieldLength != 4 && lengthFieldLength != 8) { throw new IllegalArgumentException( "lengthFieldLength must be either 1, 2, 3, 4, or 8: " + lengthFieldLength); } if (lengthFieldOffset > maxFrameLength - lengthFieldLength) { throw new IllegalArgumentException( "maxFrameLength (" + maxFrameLength + ") " + "must be equal to or greater than " + "lengthFieldOffset (" + lengthFieldOffset + ") + " + "lengthFieldLength (" + lengthFieldLength + ")."); } this.maxFrameLength = maxFrameLength; this.lengthFieldOffset = lengthFieldOffset; this.lengthFieldLength = lengthFieldLength; this.lengthAdjustment = lengthAdjustment; lengthFieldEndOffset = lengthFieldOffset + lengthFieldLength; this.initialBytesToStrip = initialBytesToStrip; } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (discardingTooLongFrame) { long bytesToDiscard = this.bytesToDiscard; int localBytesToDiscard = (int) Math.min(bytesToDiscard, buffer.readableBytes()); buffer.skipBytes(localBytesToDiscard); bytesToDiscard -= localBytesToDiscard; this.bytesToDiscard = bytesToDiscard; if (bytesToDiscard == 0) { // Reset to the initial state and tell the handlers that // the frame was too large. discardingTooLongFrame = false; long tooLongFrameLength = this.tooLongFrameLength; this.tooLongFrameLength = 0; throw new TooLongFrameException( "Adjusted frame length exceeds " + maxFrameLength + ": " + tooLongFrameLength); } else { // Keep discarding. return null; } } if (buffer.readableBytes() < lengthFieldEndOffset) { return null; } int actualLengthFieldOffset = buffer.readerIndex() + lengthFieldOffset; long frameLength; switch (lengthFieldLength) { case 1: frameLength = buffer.getUnsignedByte(actualLengthFieldOffset); break; case 2: frameLength = buffer.getUnsignedShort(actualLengthFieldOffset); break; case 3: frameLength = buffer.getUnsignedMedium(actualLengthFieldOffset); break; case 4: frameLength = buffer.getUnsignedInt(actualLengthFieldOffset); break; case 8: frameLength = buffer.getLong(actualLengthFieldOffset); break; default: throw new Error("should not reach here"); } if (frameLength < 0) { buffer.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException( "negative pre-adjustment length field: " + frameLength); } frameLength += lengthAdjustment + lengthFieldEndOffset; if (frameLength < lengthFieldEndOffset) { buffer.skipBytes(lengthFieldEndOffset); throw new CorruptedFrameException( "Adjusted frame length (" + frameLength + ") is less " + "than lengthFieldEndOffset: " + lengthFieldEndOffset); } if (frameLength > maxFrameLength) { // Enter the discard mode and discard everything received so far. discardingTooLongFrame = true; tooLongFrameLength = frameLength; bytesToDiscard = frameLength - buffer.readableBytes(); buffer.skipBytes(buffer.readableBytes()); return null; } // never overflows because it's less than maxFrameLength int frameLengthInt = (int) frameLength; if (buffer.readableBytes() < frameLengthInt) { return null; } if (initialBytesToStrip > frameLengthInt) { buffer.skipBytes(frameLengthInt); throw new CorruptedFrameException( "Adjusted frame length (" + frameLength + ") is less " + "than initialBytesToStrip: " + initialBytesToStrip); } buffer.skipBytes(initialBytesToStrip); return buffer.readBytes(frameLengthInt - initialBytesToStrip); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/package-info.java0000644000175000017500000000233011046721772031551 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Extensible decoder and its common implementations which deal with the * packet fragmentation and reassembly issue found in a stream-based transport * such as TCP/IP. */ package org.jboss.netty.handler.codec.frame;././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/LengthFieldPrepender.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/LengthFieldPrepender.0000644000175000017500000001325311216422431032410 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import static org.jboss.netty.buffer.ChannelBuffers.*; import java.nio.ByteOrder; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * An encoder that prepends the length of the message. The length value is * prepended as a binary form. It is encoded in either big endian or little * endian depending on the default {@link ByteOrder} of the current * {@link ChannelBufferFactory}. *

* For example, {@link LengthFieldPrepender}(2) will encode the * following 12-bytes string: *

 * +----------------+
 * | "HELLO, WORLD" |
 * +----------------+
 * 
* into the following: *
 * +--------+----------------+
 * + 0x000C | "HELLO, WORLD" |
 * +--------+----------------+
 * 
* If you turned on the {@code lengthIncludesLengthFieldLength} flag in the * constructor, the encoded data would look like the following * (12 (original data) + 2 (prepended data) = 14 (0xE)): *
 * +--------+----------------+
 * + 0x000E | "HELLO, WORLD" |
 * +--------+----------------+
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1437 $, $Date: 2009-06-18 04:29:29 -0700 (Thu, 18 Jun 2009) $ */ @ChannelPipelineCoverage("all") public class LengthFieldPrepender extends OneToOneEncoder { private final int lengthFieldLength; private final boolean lengthIncludesLengthFieldLength; /** * Creates a new instance. * * @param lengthFieldLength the length of the prepended length field. * Only 1, 2, 3, 4, and 8 are allowed. * * @throws IllegalArgumentException * if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8 */ public LengthFieldPrepender(int lengthFieldLength) { this(lengthFieldLength, false); } /** * Creates a new instance. * * @param lengthFieldLength the length of the prepended length field. * Only 1, 2, 3, 4, and 8 are allowed. * @param lengthIncludesLengthFieldLength * if {@code true}, the length of the prepended * length field is added to the value of the * prepended length field. * * @throws IllegalArgumentException * if {@code lengthFieldLength} is not 1, 2, 3, 4, or 8 */ public LengthFieldPrepender( int lengthFieldLength, boolean lengthIncludesLengthFieldLength) { if (lengthFieldLength != 1 && lengthFieldLength != 2 && lengthFieldLength != 3 && lengthFieldLength != 4 && lengthFieldLength != 8) { throw new IllegalArgumentException( "lengthFieldLength must be either 1, 2, 3, 4, or 8: " + lengthFieldLength); } this.lengthFieldLength = lengthFieldLength; this.lengthIncludesLengthFieldLength = lengthIncludesLengthFieldLength; } @Override protected Object encode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { ChannelBuffer header = channel.getConfig().getBufferFactory().getBuffer(lengthFieldLength); ChannelBuffer body = (ChannelBuffer) msg; int length = lengthIncludesLengthFieldLength? body.readableBytes() + lengthFieldLength : body.readableBytes(); switch (lengthFieldLength) { case 1: if (length >= 256) { throw new IllegalArgumentException( "length does not fit into a byte: " + length); } header.writeByte((byte) length); break; case 2: if (length >= 65536) { throw new IllegalArgumentException( "length does not fit into a short integer: " + length); } header.writeShort((short) length); break; case 3: if (length >= 16777216) { throw new IllegalArgumentException( "length does not fit into a medium integer: " + length); } header.writeMedium(length); break; case 4: header.writeInt(length); break; case 8: header.writeLong(length); break; default: throw new Error("should not reach here"); } return wrappedBuffer(header, body); } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/frame/Delimiters.java0000644000175000017500000000421611216653013031322 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.frame; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; /** * A set of commonly used delimiters for {@link DelimiterBasedFrameDecoder}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * */ public class Delimiters { /** * Returns a {@code NUL (0x00)} delimiter, which could be used for * Flash XML socket or any similar protocols. */ public static ChannelBuffer[] nulDelimiter() { return new ChannelBuffer[] { ChannelBuffers.wrappedBuffer(new byte[] { 0 }) }; } /** * Returns {@code CR ('\r')} and {@code LF ('\n')} delimiters, which could * be used for text-based line protocols. */ public static ChannelBuffer[] lineDelimiter() { return new ChannelBuffer[] { ChannelBuffers.wrappedBuffer(new byte[] { '\r', '\n' }), ChannelBuffers.wrappedBuffer(new byte[] { '\n' }), }; } private Delimiters() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/0000755000175000017500000000000011316313147026242 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpHeaders.java0000644000175000017500000002456111216747541031340 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * Standard HTTP header names and values. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public final class HttpHeaders { /** * Standard HTTP header names. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public static final class Names { /** * {@code "Accept"} */ public static final String ACCEPT = "Accept"; /** * {@code "Accept-Charset"} */ public static final String ACCEPT_CHARSET = "Accept-Charset"; /** * {@code "Accept-Encoding"} */ public static final String ACCEPT_ENCODING= "Accept-Encoding"; /** * {@code "Accept-Language"} */ public static final String ACCEPT_LANGUAGE = "Accept-Language"; /** * {@code "Accept-Ranges"} */ public static final String ACCEPT_RANGES= "Accept-Ranges"; /** * {@code "Age"} */ public static final String AGE = "Age"; /** * {@code "Allow"} */ public static final String ALLOW = "Allow"; /** * {@code "Authorization"} */ public static final String AUTHORIZATION = "Authorization"; /** * {@code "Cache-Control"} */ public static final String CACHE_CONTROL = "Cache-Control"; /** * {@code "Connection"} */ public static final String CONNECTION = "Connection"; /** * {@code "Content-Encoding"} */ public static final String CONTENT_ENCODING = "Content-Encoding"; /** * {@code "Content-Language"} */ public static final String CONTENT_LANGUAGE= "Content-Language"; /** * {@code "Content-Length"} */ public static final String CONTENT_LENGTH = "Content-Length"; /** * {@code "Content-Location"} */ public static final String CONTENT_LOCATION = "Content-Location"; /** * {@code "Content-MD5"} */ public static final String CONTENT_MD5 = "Content-MD5"; /** * {@code "Content-Range"} */ public static final String CONTENT_RANGE = "Content-Range"; /** * {@code "Content-Type"} */ public static final String CONTENT_TYPE= "Content-Type"; /** * {@code "Cookie"} */ public static final String COOKIE = "Cookie"; /** * {@code "Date"} */ public static final String DATE = "Date"; /** * {@code "ETag"} */ public static final String ETAG = "ETag"; /** * {@code "Expect"} */ public static final String EXPECT = "Expect"; /** * {@code "Expires"} */ public static final String EXPIRES = "Expires"; /** * {@code "From"} */ public static final String FROM = "From"; /** * {@code "Host"} */ public static final String HOST = "Host"; /** * {@code "If-Match"} */ public static final String IF_MATCH = "If-Match"; /** * {@code "If-Modified-Since"} */ public static final String IF_MODIFIED_SINCE = "If-Modified-Since"; /** * {@code "If-None-Match"} */ public static final String IF_NONE_MATCH = "If-None-Match"; /** * {@code "If-Range"} */ public static final String IF_RANGE= "If-Range"; /** * {@code "If-Unmodified-Since"} */ public static final String IF_UNMODIFIED_SINCE = "If-Unmodified-Since"; /** * {@code "Last-Modified"} */ public static final String LAST_MODIFIED = "Last-Modified"; /** * {@code "Location"} */ public static final String LOCATION = "Location"; /** * {@code "Max-Forwards"} */ public static final String MAX_FORWARDS = "Max-Forwards"; /** * {@code "Pragma"} */ public static final String PRAGMA = "Pragma"; /** * {@code "Proxy-Authenticate"} */ public static final String PROXY_AUTHENTICATE = "Proxy-Authenticate"; /** * {@code "Proxy-Authorization"} */ public static final String PROXY_AUTHORIZATION = "Proxy-Authorization"; /** * {@code "Range"} */ public static final String RANGE = "Range"; /** * {@code "Referer"} */ public static final String REFERER = "Referer"; /** * {@code "Retry-After"} */ public static final String RETRY_AFTER = "Retry-After"; /** * {@code "Server"} */ public static final String SERVER = "Server"; /** * {@code "Set-Cookie"} */ public static final String SET_COOKIE = "Set-Cookie"; /** * {@code "TE"} */ public static final String TE = "TE"; /** * {@code "Trailer"} */ public static final String TRAILER = "Trailer"; /** * {@code "Transfer-Encoding"} */ public static final String TRANSFER_ENCODING = "Transfer-Encoding"; /** * {@code "Upgrade"} */ public static final String UPGRADE = "Upgrade"; /** * {@code "User-Agent"} */ public static final String USER_AGENT = "User-Agent"; /** * {@code "Vary"} */ public static final String VARY = "Vary"; /** * {@code "Via"} */ public static final String VIA = "Via"; /** * {@code "Warning"} */ public static final String WARNING = "Warning"; /** * {@code "WWW-Authenticate"} */ public static final String WWW_AUTHENTICATE = "WWW-Authenticate"; private Names() { super(); } } /** * Standard HTTP header values. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public static final class Values { /** * {@code "bytes"} */ public static final String BYTES = "bytes"; /** * {@code "charset"} */ public static final String CHARSET = "charset"; /** * {@code "chunked"} */ public static final String CHUNKED = "chunked"; /** * {@code "close"} */ public static final String CLOSE = "close"; /** * {@code "compress"} */ public static final String COMPRESS = "compress"; /** * {@code "100-continue"} */ public static final String CONTINUE = "100-continue"; /** * {@code "deflate"} */ public static final String DEFLATE = "deflate"; /** * {@code "gzip"} */ public static final String GZIP = "gzip"; /** * {@code "identity"} */ public static final String IDENTITY = "identity"; /** * {@code "keep-alive"} */ public static final String KEEP_ALIVE = "keep-alive"; /** * {@code "max-age"} */ public static final String MAX_AGE = "max-age"; /** * {@code "max-fresh"} */ public static final String MAX_FRESH = "max-fresh"; /** * {@code "max-stale"} */ public static final String MAX_STALE = "max-stale"; /** * {@code "must-revalidate"} */ public static final String MUST_REVALIDATE = "must-revalidate"; /** * {@code "no-cache"} */ public static final String NO_CACHE = "no-cache"; /** * {@code "no-store"} */ public static final String NO_STORE = "no-store"; /** * {@code "no-transform"} */ public static final String NO_TRANSFORM = "no-transform"; /** * {@code "none"} */ public static final String NONE = "none"; /** * {@code "only-if-cached"} */ public static final String ONLY_IF_CACHED = "only-if-cached"; /** * {@code "private"} */ public static final String PRIVATE = "private"; /** * {@code "proxy-revalidate"} */ public static final String PROXY_REVALIDATE = "proxy-revalidate"; /** * {@code "public"} */ public static final String PUBLIC = "public"; /** * {@code "s-maxage"} */ public static final String S_MAXAGE = "s-maxage"; /** * {@code "trailers"} */ public static final String TRAILERS = "trailers"; private Values() { super(); } } private HttpHeaders() { super(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/Cookie.java0000644000175000017500000000707011216747541030332 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.Set; /** * An HTTP Cookie. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public interface Cookie extends Comparable { /** * Returns the name of this cookie. */ String getName(); /** * Returns the value of this cookie. */ String getValue(); /** * Sets the value of this cookie. */ void setValue(String value); /** * Returns the domain of this cookie. */ String getDomain(); /** * Sets the domain of this cookie. */ void setDomain(String domain); /** * Returns the path of this cookie. */ String getPath(); /** * Sets the path of this cookie. */ void setPath(String path); /** * Returns the comment of this cookie. */ String getComment(); /** * Sets the comment of this cookie. */ void setComment(String comment); /** * Returns the max age of this cookie in seconds. */ int getMaxAge(); /** * Sets the max age of this cookie in seconds. If {@code 0} is specified, * this cookie will be removed by browser because it will be expired * immediately. If {@code -1} is specified, this cookie will be removed * when a user terminates browser. */ void setMaxAge(int maxAge); /** * Returns the version of this cookie. */ int getVersion(); /** * Sets the version of this cookie. */ void setVersion(int version); /** * Returns the secure flag of this cookie. */ boolean isSecure(); /** * Sets the secure flag of this cookie. */ void setSecure(boolean secure); /** * Returns the comment URL of this cookie. */ String getCommentUrl(); /** * Sets the comment URL of this cookie. */ void setCommentUrl(String commentUrl); /** * Returns the discard flag of this cookie. */ boolean isDiscard(); /** * Sets the discard flag of this cookie. */ void setDiscard(boolean discard); /** * Returns the ports of this cookie. */ Set getPorts(); /** * Sets the ports of this cookie. */ void setPorts(int... ports); /** * Sets the ports of this cookie. */ void setPorts(Iterable ports); }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpResponse.java0000644000175000017500000000272511216747541031561 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * An HTTP response. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @see HttpRequest */ public interface HttpResponse extends HttpMessage { /** * Returns the status of this response. */ HttpResponseStatus getStatus(); } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultHttpMessage.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultHttpMessage.jav0000644000175000017500000001617611216747541032520 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.ArrayList; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Set; import java.util.TreeMap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.util.internal.CaseIgnoringComparator; /** * The default {@link HttpMessage} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultHttpMessage implements HttpMessage { private final HttpVersion version; private final Map> headers = new TreeMap>(CaseIgnoringComparator.INSTANCE); private ChannelBuffer content = ChannelBuffers.EMPTY_BUFFER; /** * Creates a new instance. */ protected DefaultHttpMessage(final HttpVersion version) { if (version == null) { throw new NullPointerException("version"); } this.version = version; } public void addHeader(final String name, final String value) { validateHeaderName(name); validateHeaderValue(value); if (value == null) { throw new NullPointerException("value is null"); } if (headers.get(name) == null) { headers.put(name, new ArrayList(1)); } headers.get(name).add(value); } public void setHeader(final String name, final String value) { validateHeaderName(name); validateHeaderValue(value); if (value == null) { throw new NullPointerException("value"); } List values = new ArrayList(1); values.add(value); headers.put(name, values); } public void setHeader(final String name, final Iterable values) { validateHeaderName(name); if (values == null) { throw new NullPointerException("values"); } int nValues = 0; for (String v: values) { validateHeaderValue(v); nValues ++; } if (nValues == 0) { throw new IllegalArgumentException("values is empty."); } if (values instanceof List) { headers.put(name, (List) values); } else { List valueList = new LinkedList(); for (String v: values) { valueList.add(v); } headers.put(name, valueList); } } private static void validateHeaderName(String name) { if (name == null) { throw new NullPointerException("name"); } for (int i = 0; i < name.length(); i ++) { char c = name.charAt(i); if (c > 127) { throw new IllegalArgumentException( "name contains non-ascii character: " + name); } // Check prohibited characters. switch (c) { case '=': case ',': case ';': case ' ': case ':': case '\t': case '\r': case '\n': case '\f': case 0x0b: // Vertical tab throw new IllegalArgumentException( "name contains one of the following prohibited characters: " + "=,;: \\t\\r\\n\\v\\f: " + name); } } } private static void validateHeaderValue(String value) { if (value == null) { throw new NullPointerException("value"); } for (int i = 0; i < value.length(); i ++) { char c = value.charAt(i); // Check prohibited characters. switch (c) { case '\r': case '\n': case '\f': case 0x0b: // Vertical tab throw new IllegalArgumentException( "value contains one of the following prohibited characters: " + "\\r\\n\\v\\f: " + value); } } } public void removeHeader(final String name) { headers.remove(name); } public long getContentLength() { return getContentLength(0); } public long getContentLength(long defaultValue) { List contentLength = headers.get(HttpHeaders.Names.CONTENT_LENGTH); if (contentLength != null && contentLength.size() > 0) { return Long.parseLong(contentLength.get(0)); } return defaultValue; } public boolean isChunked() { List chunked = headers.get(HttpHeaders.Names.TRANSFER_ENCODING); if (chunked == null || chunked.isEmpty()) { return false; } for (String v: chunked) { if (v.equalsIgnoreCase(HttpHeaders.Values.CHUNKED)) { return true; } } return false; } public boolean isKeepAlive() { if (HttpHeaders.Values.CLOSE.equalsIgnoreCase(getHeader(HttpHeaders.Names.CONNECTION))) { return false; } if (getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(getHeader(HttpHeaders.Names.CONNECTION))) { return false; } return true; } public void clearHeaders() { headers.clear(); } public void setContent(ChannelBuffer content) { if (content == null) { content = ChannelBuffers.EMPTY_BUFFER; } this.content = content; } public String getHeader(final String name) { List header = headers.get(name); return header != null && header.size() > 0 ? headers.get(name).get(0) : null; } public List getHeaders(final String name) { return headers.get(name); } public boolean containsHeader(final String name) { return headers.containsKey(name); } public Set getHeaderNames() { return headers.keySet(); } public HttpVersion getProtocolVersion() { return version; } public ChannelBuffer getContent() { return content; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpResponseEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpResponseEncoder.ja0000644000175000017500000000451511216747541032531 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import static org.jboss.netty.handler.codec.http.HttpCodecUtil.*; import java.io.UnsupportedEncodingException; import org.jboss.netty.buffer.ChannelBuffer; /** * Encodes an {@link HttpResponse} or an {@link HttpChunk} into * a {@link ChannelBuffer}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpResponseEncoder extends HttpMessageEncoder { /** * Creates a new instance. */ public HttpResponseEncoder() { super(); } @Override protected void encodeInitialLine(ChannelBuffer buf, HttpMessage message) { HttpResponse response = (HttpResponse) message; try { buf.writeBytes(response.getProtocolVersion().toString().getBytes("ASCII")); buf.writeByte(SP); buf.writeBytes(String.valueOf(response.getStatus().getCode()).getBytes("ASCII")); buf.writeByte(SP); buf.writeBytes(String.valueOf(response.getStatus().getReasonPhrase()).getBytes("ASCII")); buf.writeBytes(CRLF); } catch (UnsupportedEncodingException e) { throw (Error) new Error().initCause(e); } } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/CookieHeaderNames.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/CookieHeaderNames.java0000644000175000017500000000345511216747541032432 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ final class CookieHeaderNames { static final String PATH = "Path"; static final String EXPIRES = "Expires"; static final String MAX_AGE = "Max-Age"; static final String DOMAIN = "Domain"; static final String SECURE = "Secure"; static final String COMMENT = "Comment"; static final String COMMENTURL = "CommentURL"; static final String DISCARD = "Discard"; static final String PORT = "Port"; static final String VERSION = "Version"; private CookieHeaderNames() { // Unused. } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultHttpRequest.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultHttpRequest.jav0000644000175000017500000000446411216747541032561 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * The default {@link HttpRequest} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultHttpRequest extends DefaultHttpMessage implements HttpRequest { private final HttpMethod method; private final String uri; /** * Creates a new instance. * * @param httpVersion the HTTP version of the request * @param method the HTTP method of the request * @param uri the URI or path of the request */ public DefaultHttpRequest(HttpVersion httpVersion, HttpMethod method, String uri) { super(httpVersion); if (method == null) { throw new NullPointerException("method"); } if (uri == null) { throw new NullPointerException("uri"); } this.method = method; this.uri = uri; } public HttpMethod getMethod() { return method; } public String getUri() { return uri; } @Override public String toString() { return getMethod().toString() + ' ' + getUri() + ' ' + getProtocolVersion().getText(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpMessage.java0000644000175000017500000001135011216747541031341 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.List; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; /** * An HTTP message which provides common properties for {@link HttpRequest} and * {@link HttpResponse}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public interface HttpMessage { /** * Returns the header value with the specified header name. If there are * more than one header value for the specified header name, the first * value is returned. * * @return the header value or {@code null} if there is no such header * */ String getHeader(String name); /** * Returns the header values with the specified header name. * * @return the {@link List} of header values of {@code null} if there is * no such header */ List getHeaders(String name); /** * Returns {@code true} if and only if there is a header with the specified * header name. */ boolean containsHeader(String name); /** * Returns the {@link Set} of all header names that this message contains. */ Set getHeaderNames(); /** * Returns the protocol version of this message. */ HttpVersion getProtocolVersion(); /** * Returns the content of this message. If there is no content, an * {@link ChannelBuffers#EMPTY_BUFFER} is returned. */ ChannelBuffer getContent(); /** * Sets the content of this message. If {@code null} is specified, * the content of this message will be set to {@link ChannelBuffers#EMPTY_BUFFER}. */ void setContent(ChannelBuffer content); /** * Adds a new header with the specified name and value. */ void addHeader(String name, String value); /** * Sets a new header with the specified name and value. If there is an * existing header with the same name, the existing header is removed. */ void setHeader(String name, String value); /** * Sets a new header with the specified name and values. If there is an * existing header with the same name, the existing header is removed. */ void setHeader(String name, Iterable values); /** * Removes the header with the specified name. */ void removeHeader(String name); /** * Removes all headers from this message. */ void clearHeaders(); /** * Returns the length of the content. Please note that this value is * not retrieved from {@link #getContent()} but from the * {@code "Content-Length"} header, and thus they are independent from each * other. * * @return the content length or {@code 0} if this message does not have * the {@code "Content-Length"} header */ long getContentLength(); /** * Returns the length of the content. Please note that this value is * not retrieved from {@link #getContent()} but from the * {@code "Content-Length"} header, and thus they are independent from each * other. * * @return the content length or {@code defaultValue} if this message does * not have the {@code "Content-Length"} header */ long getContentLength(long defaultValue); /** * Returns {@code true} if and only if the {@code "Transfer-Encoding"} of * this message is {@code "chunked"}. */ boolean isChunked(); /** * Returns {@code true} if and only if the connection can remain open and * thus 'kept alive'. */ boolean isKeepAlive(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/CookieDecoder.java0000644000175000017500000001646211216747541031625 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.text.ParseException; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Set; import java.util.TreeSet; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Decodes an HTTP header value into {@link Cookie}s. This decoder can decode * the HTTP cookie version 0, 1, and 2. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * @see CookieEncoder */ public class CookieDecoder { private final static Pattern PATTERN = Pattern.compile("(?:\\s|[;,])*\\$*([^;=]+)(?:=(?:[\"']((?:\\\\.|[^\"])*)[\"']|([^;,]*)))?\\s*(?:[;,]+|$)"); private final static String COMMA = ","; /** * Creates a new decoder. */ public CookieDecoder() { super(); } /** * Decodes the specified HTTP header value into {@link Cookie}s. * * @return the decoded {@link Cookie}s */ public Set decode(String header) { Matcher m = PATTERN.matcher(header); List names = new ArrayList(8); List values = new ArrayList(8); int pos = 0; int version = 0; while (m.find(pos)) { pos = m.end(); // Extract name and value pair from the match. String name = m.group(1); String value = m.group(3); if (value == null) { value = decodeValue(m.group(2)); } // An exceptional case: // 'Expires' attribute can contain a comma without surrounded with quotes. if (name.equalsIgnoreCase(CookieHeaderNames.EXPIRES) && value.length() <= 3) { // value contains comma, but not surrounded with quotes. if (m.find(pos)) { value = value + ", " + m.group(1); pos = m.end(); } else { continue; } } names.add(name); values.add(value); } if (names.isEmpty()) { return Collections.emptySet(); } int i; // $Version is the only attribute that can appear before the actual // cookie name-value pair. if (names.get(0).equalsIgnoreCase(CookieHeaderNames.VERSION)) { try { version = Integer.parseInt(values.get(0)); } catch (NumberFormatException e) { // Ignore. } i = 1; } else { i = 0; } if (names.size() <= i) { // There's a version attribute, but nothing more. return Collections.emptySet(); } Set cookies = new TreeSet(); for (; i < names.size(); i ++) { String name = names.get(i); String value = values.get(i); if (value == null) { value = ""; } Cookie c = new DefaultCookie(name, value); cookies.add(c); boolean discard = false; boolean secure = false; String comment = null; String commentURL = null; String domain = null; String path = null; int maxAge = -1; List ports = new ArrayList(2); for (int j = i + 1; j < names.size(); j++, i++) { name = names.get(j); value = values.get(j); if (CookieHeaderNames.DISCARD.equalsIgnoreCase(name)) { discard = true; } else if (CookieHeaderNames.SECURE.equalsIgnoreCase(name)) { secure = true; } else if (CookieHeaderNames.COMMENT.equalsIgnoreCase(name)) { comment = value; } else if (CookieHeaderNames.COMMENTURL.equalsIgnoreCase(name)) { commentURL = value; } else if (CookieHeaderNames.DOMAIN.equalsIgnoreCase(name)) { domain = value; } else if (CookieHeaderNames.PATH.equalsIgnoreCase(name)) { path = value; } else if (CookieHeaderNames.EXPIRES.equalsIgnoreCase(name)) { try { long maxAgeMillis = new CookieDateFormat().parse(value).getTime() - System.currentTimeMillis(); if (maxAgeMillis <= 0) { maxAge = 0; } else { maxAge = (int) (maxAgeMillis / 1000) + (maxAgeMillis % 1000 != 0? 1 : 0); } } catch (ParseException e) { // Ignore. } } else if (CookieHeaderNames.MAX_AGE.equalsIgnoreCase(name)) { maxAge = Integer.parseInt(value); } else if (CookieHeaderNames.VERSION.equalsIgnoreCase(name)) { version = Integer.parseInt(value); } else if (CookieHeaderNames.PORT.equalsIgnoreCase(name)) { String[] portList = value.split(COMMA); for (String s1: portList) { try { ports.add(Integer.valueOf(s1)); } catch (NumberFormatException e) { // Ignore. } } } else { break; } } c.setVersion(version); c.setMaxAge(maxAge); c.setPath(path); c.setDomain(domain); c.setSecure(secure); if (version > 0) { c.setComment(comment); } if (version > 1) { c.setCommentUrl(commentURL); c.setPorts(ports); c.setDiscard(discard); } } return cookies; } private String decodeValue(String value) { if (value == null) { return value; } return value.replace("\\\"", "\"").replace("\\\\", "\\"); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpVersion.java0000644000175000017500000001613111216747541031404 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * The version of HTTP or its derived protocols, such as * RTSP and * ICAP. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.exclude */ public class HttpVersion implements Comparable { private static final Pattern VERSION_PATTERN = Pattern.compile("(\\S+)/(\\d+)\\.(\\d+)"); /** * HTTP/1.0 */ public static final HttpVersion HTTP_1_0 = new HttpVersion("HTTP", 1, 0); /** * HTTP/1.1 */ public static final HttpVersion HTTP_1_1 = new HttpVersion("HTTP", 1, 1); /** * Returns an existing or new {@link HttpVersion} instance which matches to * the specified protocol version string. If the specified {@code text} is * equal to {@code "HTTP/1.0"}, {@link #HTTP_1_0} will be returned. If the * specified {@code text} is equal to {@code "HTTP/1.1"}, {@link #HTTP_1_1} * will be returned. Otherwise, a new {@link HttpVersion} instance will be * returned. */ public static HttpVersion valueOf(String text) { if (text == null) { throw new NullPointerException("text"); } text = text.trim().toUpperCase(); if (text.equals("HTTP/1.1")) { return HTTP_1_1; } if (text.equals("HTTP/1.0")) { return HTTP_1_0; } return new HttpVersion(text); } private final String protocolName; private final int majorVersion; private final int minorVersion; private final String text; /** * Creates a new HTTP version with the specified version string. You will * not need to create a new instance unless you are implementing a protocol * derived from HTTP, such as * RTSP and * ICAP. */ public HttpVersion(String text) { if (text == null) { throw new NullPointerException("text"); } text = text.trim().toUpperCase(); if (text.length() == 0) { throw new IllegalArgumentException("empty text"); } Matcher m = VERSION_PATTERN.matcher(text); if (!m.matches()) { throw new IllegalArgumentException("invalid version format: " + text); } protocolName = m.group(1); majorVersion = Integer.parseInt(m.group(2)); minorVersion = Integer.parseInt(m.group(3)); this.text = protocolName + '/' + majorVersion + '.' + minorVersion; } /** * Creates a new HTTP version with the specified protocol name and version * numbers. You will not need to create a new instance unless you are * implementing a protocol derived from HTTP, such as * RTSP and * ICAP */ public HttpVersion( String protocolName, int majorVersion, int minorVersion) { if (protocolName == null) { throw new NullPointerException("protocolName"); } protocolName = protocolName.trim().toUpperCase(); if (protocolName.length() == 0) { throw new IllegalArgumentException("empty protocolName"); } for (int i = 0; i < protocolName.length(); i ++) { if (Character.isISOControl(protocolName.charAt(i)) || Character.isWhitespace(protocolName.charAt(i))) { throw new IllegalArgumentException("invalid character in protocolName"); } } if (majorVersion < 0) { throw new IllegalArgumentException("negative majorVersion"); } if (minorVersion < 0) { throw new IllegalArgumentException("negative minorVersion"); } this.protocolName = protocolName; this.majorVersion = majorVersion; this.minorVersion = minorVersion; text = protocolName + '/' + majorVersion + '.' + minorVersion; } /** * Returns the name of the protocol such as {@code "HTTP"} in {@code "HTTP/1.0"}. */ public String getProtocolName() { return protocolName; } /** * Returns the name of the protocol such as {@code 1} in {@code "HTTP/1.0"}. */ public int getMajorVersion() { return majorVersion; } /** * Returns the name of the protocol such as {@code 0} in {@code "HTTP/1.0"}. */ public int getMinorVersion() { return minorVersion; } /** * Returns the full protocol version text such as {@code "HTTP/1.0"}. */ public String getText() { return text; } /** * Returns the full protocol version text such as {@code "HTTP/1.0"}. */ @Override public String toString() { return getText(); } @Override public int hashCode() { return (getProtocolName().hashCode() * 31 + getMajorVersion()) * 31 + getMinorVersion(); } @Override public boolean equals(Object o) { if (!(o instanceof HttpVersion)) { return false; } HttpVersion that = (HttpVersion) o; return getMinorVersion() == that.getMinorVersion() && getMajorVersion() == that.getMajorVersion() && getProtocolName().equals(that.getProtocolName()); } public int compareTo(HttpVersion o) { int v = getProtocolName().compareTo(o.getProtocolName()); if (v != 0) { return v; } v = getMajorVersion() - o.getMajorVersion(); if (v != 0) { return v; } return getMinorVersion() - o.getMinorVersion(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpRequest.java0000644000175000017500000000306011216747541031404 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * An HTTP request. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @see HttpResponse * @see QueryStringEncoder * @see QueryStringDecoder */ public interface HttpRequest extends HttpMessage { /** * Returns the method of this request. */ HttpMethod getMethod(); /** * Returns the URI (or path) of this request. */ String getUri(); } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpResponseDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpResponseDecoder.ja0000644000175000017500000000717411216747541032523 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.codec.frame.TooLongFrameException; /** * Decodes {@link ChannelBuffer}s into {@link HttpResponse}s and * {@link HttpChunk}s. * *

Parameters that prevents excessive memory consumption

* * * * * * * * * * * * * * * * *
NameMeaning
{@code maxInitialLineLength}The maximum length of the initial line (e.g. {@code "HTTP/1.0 200 OK"}) * If the length of the initial line exceeds this value, a * {@link TooLongFrameException} will be raised.
{@code maxHeaderSize}The maximum length of all headers. If the sum of the length of each * header exceeds this value, a {@link TooLongFrameException} will be raised.
{@code maxChunkSize}The maximum length of the content or each chunk. If the content length * exceeds this value, the transfer encoding of the decoded response will be * converted to 'chunked' and the content will be split into multiple * {@link HttpChunk}s. If the transfer encoding of the HTTP response is * 'chunked' already, each chunk will be split into smaller chunks if the * length of the chunk exceeds this value. If you prefer not to handle * {@link HttpChunk}s in your handler, insert {@link HttpChunkAggregator} * after this decoder in the {@link ChannelPipeline}.
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpResponseDecoder extends HttpMessageDecoder { /** * Creates a new instance with the default * {@code maxInitialLineLength (4096}}, {@code maxHeaderSize (4096)}, and * {@code maxChunkSize (4096)}. */ public HttpResponseDecoder() { super(); } /** * Creates a new instance with the specified parameters. */ public HttpResponseDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) { super(maxInitialLineLength, maxHeaderSize, maxChunkSize); } @Override protected HttpMessage createMessage(String[] initialLine) { return new DefaultHttpResponse(HttpVersion.valueOf(initialLine[0]), new HttpResponseStatus(Integer.valueOf(initialLine[1]), initialLine[2])); } @Override protected boolean isDecodingRequest() { return false; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultCookie.java0000644000175000017500000002317111216747541031637 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.Collections; import java.util.Set; import java.util.TreeSet; import org.jboss.netty.util.internal.CaseIgnoringComparator; /** * The default {@link Cookie} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultCookie implements Cookie { private static final Set RESERVED_NAMES = new TreeSet(CaseIgnoringComparator.INSTANCE); static { RESERVED_NAMES.add("Domain"); RESERVED_NAMES.add("Path"); RESERVED_NAMES.add("Comment"); RESERVED_NAMES.add("CommentURL"); RESERVED_NAMES.add("Discard"); RESERVED_NAMES.add("Port"); RESERVED_NAMES.add("Max-Age"); RESERVED_NAMES.add("Expires"); RESERVED_NAMES.add("Version"); RESERVED_NAMES.add("Secure"); } private final String name; private String value; private String domain; private String path; private String comment; private String commentUrl; private boolean discard; private Set ports = Collections.emptySet(); private Set unmodifiablePorts = ports; private int maxAge = -1; private int version; private boolean secure; /** * Creates a new cookie with the specified name and value. */ public DefaultCookie(String name, String value) { if (name == null) { throw new NullPointerException("name"); } name = name.trim(); if (name.length() == 0) { throw new IllegalArgumentException("empty name"); } for (int i = 0; i < name.length(); i ++) { char c = name.charAt(i); if (c > 127) { throw new IllegalArgumentException( "name contains non-ascii character: " + name); } // Check prohibited characters. switch (c) { case '=': case ',': case ';': case ' ': case '\t': case '\r': case '\n': case '\f': case 0x0b: // Vertical tab throw new IllegalArgumentException( "name contains one of the following prohibited characters: " + "=,; \\t\\r\\n\\v\\f: " + name); } } if (RESERVED_NAMES.contains(name)) { throw new IllegalArgumentException("reserved name: " + name); } this.name = name; setValue(value); } public String getName() { return name; } public String getValue() { return value; } public void setValue(String value) { if (value == null) { throw new NullPointerException("value"); } this.value = value; } public String getDomain() { return domain; } public void setDomain(String domain) { this.domain = validateValue("domain", domain); } public String getPath() { return path; } public void setPath(String path) { this.path = validateValue("path", path); } public String getComment() { return comment; } public void setComment(String comment) { this.comment = validateValue("comment", comment); } public String getCommentUrl() { return commentUrl; } public void setCommentUrl(String commentUrl) { this.commentUrl = validateValue("commentUrl", commentUrl); } public boolean isDiscard() { return discard; } public void setDiscard(boolean discard) { this.discard = discard; } public Set getPorts() { if (unmodifiablePorts == null) { unmodifiablePorts = Collections.unmodifiableSet(ports); } return unmodifiablePorts; } public void setPorts(int... ports) { if (ports == null) { throw new NullPointerException("ports"); } int[] portsCopy = ports.clone(); if (portsCopy.length == 0) { unmodifiablePorts = this.ports = Collections.emptySet(); } else { Set newPorts = new TreeSet(); for (int p: portsCopy) { if (p <= 0 || p > 65535) { throw new IllegalArgumentException("port out of range: " + p); } newPorts.add(Integer.valueOf(p)); } this.ports = newPorts; unmodifiablePorts = null; } } public void setPorts(Iterable ports) { Set newPorts = new TreeSet(); for (int p: ports) { if (p <= 0 || p > 65535) { throw new IllegalArgumentException("port out of range: " + p); } newPorts.add(Integer.valueOf(p)); } if (newPorts.isEmpty()) { unmodifiablePorts = this.ports = Collections.emptySet(); } else { this.ports = newPorts; unmodifiablePorts = null; } } public int getMaxAge() { return maxAge; } public void setMaxAge(int maxAge) { if (maxAge < -1) { throw new IllegalArgumentException( "maxAge must be either -1, 0, or a positive integer: " + maxAge); } this.maxAge = maxAge; } public int getVersion() { return version; } public void setVersion(int version) { this.version = version; } public boolean isSecure() { return secure; } public void setSecure(boolean secure) { this.secure = secure; } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof Cookie)) { return false; } Cookie that = (Cookie) o; if (!getName().equalsIgnoreCase(that.getName())) { return false; } if (getPath() == null && that.getPath() != null) { return false; } else if (that.getPath() == null) { return false; } if (!getPath().equals(that.getPath())) { return false; } if (getDomain() == null && that.getDomain() != null) { return false; } else if (that.getDomain() == null) { return false; } if (!getDomain().equalsIgnoreCase(that.getDomain())) { return false; } return true; } public int compareTo(Cookie c) { int v; v = getName().compareToIgnoreCase(c.getName()); if (v != 0) { return v; } if (getPath() == null && c.getPath() != null) { return -1; } else if (c.getPath() == null) { return 1; } v = getPath().compareTo(c.getPath()); if (v != 0) { return v; } if (getDomain() == null && c.getDomain() != null) { return -1; } else if (c.getDomain() == null) { return 1; } v = getDomain().compareToIgnoreCase(c.getDomain()); return v; } @Override public String toString() { StringBuilder buf = new StringBuilder(); buf.append(getName()); buf.append('='); buf.append(getValue()); if (getDomain() != null) { buf.append(", domain="); buf.append(getDomain()); } if (getPath() != null) { buf.append(", path="); buf.append(getPath()); } if (getComment() != null) { buf.append(", comment="); buf.append(getComment()); } if (getMaxAge() >= 0) { buf.append(", maxAge="); buf.append(getMaxAge()); buf.append('s'); } if (isSecure()) { buf.append(", secure"); } return buf.toString(); } private static String validateValue(String name, String value) { if (value == null) { return null; } value = value.trim(); if (value.length() == 0) { return null; } for (int i = 0; i < value.length(); i ++) { char c = value.charAt(i); switch (c) { case '\r': case '\n': case '\f': case 0x0b: case ';': throw new IllegalArgumentException( name + " contains one of the following prohibited characters: " + ";\\r\\n\\f\\v (" + value + ')'); } } return value; } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultHttpChunk.java0000644000175000017500000000371311216722566032336 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import org.jboss.netty.buffer.ChannelBuffer; /** * The default {@link HttpChunk} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1469 $, $Date: 2009-06-19 07:49:26 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultHttpChunk implements HttpChunk { private final ChannelBuffer content; private final boolean last; /** * Creates a new instance with the specified chunk content. If an empty * buffer is specified, this chunk becomes the 'end of content' marker. */ public DefaultHttpChunk(ChannelBuffer content) { if (content == null) { throw new NullPointerException("content"); } last = !content.readable(); this.content = content; } public ChannelBuffer getContent() { return content; } public boolean isLast() { return last; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageDecoder.jav0000644000175000017500000005434411216747541032500 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.List; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.codec.frame.TooLongFrameException; import org.jboss.netty.handler.codec.replay.ReplayingDecoder; /** * Decodes {@link ChannelBuffer}s into {@link HttpMessage}s and * {@link HttpChunk}s. * *

Parameters that prevents excessive memory consumption

* * * * * * * * * * * * * * * * *
NameMeaning
{@code maxInitialLineLength}The maximum length of the initial line * (e.g. {@code "GET / HTTP/1.0"} or {@code "HTTP/1.0 200 OK"}) * If the length of the initial line exceeds this value, a * {@link TooLongFrameException} will be raised.
{@code maxHeaderSize}The maximum length of all headers. If the sum of the length of each * header exceeds this value, a {@link TooLongFrameException} will be raised.
{@code maxChunkSize}The maximum length of the content or each chunk. If the content length * exceeds this value, the transfer encoding of the decoded message will be * converted to 'chunked' and the content will be split into multiple * {@link HttpChunk}s. If the transfer encoding of the HTTP message is * 'chunked' already, each chunk will be split into smaller chunks if the * length of the chunk exceeds this value. If you prefer not to handle * {@link HttpChunk}s in your handler, insert {@link HttpChunkAggregator} * after this decoder in the {@link ChannelPipeline}.
* *

Extensibility

* * Please note that this decoder is designed to be extended to implement * a protocol derived from HTTP, such as * RTSP and * ICAP. * To implement the decoder of such a derived protocol, extend this class and * implement all abstract methods properly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public abstract class HttpMessageDecoder extends ReplayingDecoder { private final int maxInitialLineLength; private final int maxHeaderSize; private final int maxChunkSize; protected volatile HttpMessage message; private volatile ChannelBuffer content; private volatile long chunkSize; private int headerSize; /** * The internal state of {@link HttpMessageDecoder}. * Internal use only. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.exclude */ protected enum State { SKIP_CONTROL_CHARS, READ_INITIAL, READ_HEADER, READ_VARIABLE_LENGTH_CONTENT, READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS, READ_FIXED_LENGTH_CONTENT, READ_FIXED_LENGTH_CONTENT_AS_CHUNKS, READ_CHUNK_SIZE, READ_CHUNKED_CONTENT, READ_CHUNKED_CONTENT_AS_CHUNKS, READ_CHUNK_DELIMITER, READ_CHUNK_FOOTER; } /** * Creates a new instance with the default * {@code maxInitialLineLength (4096}}, {@code maxHeaderSize (4096)}, and * {@code maxChunkSize (4096)}. */ protected HttpMessageDecoder() { this(4096, 8192, 8192); } /** * Creates a new instance with the specified parameters. */ protected HttpMessageDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) { super(State.SKIP_CONTROL_CHARS, true); if (maxInitialLineLength <= 0) { throw new IllegalArgumentException( "maxInitialLineLength must be a positive integer: " + maxInitialLineLength); } if (maxHeaderSize <= 0) { throw new IllegalArgumentException( "maxHeaderSize must be a positive integer: " + maxChunkSize); } if (maxChunkSize < 0) { throw new IllegalArgumentException( "maxChunkSize must be a positive integer: " + maxChunkSize); } this.maxInitialLineLength = maxInitialLineLength; this.maxHeaderSize = maxHeaderSize; this.maxChunkSize = maxChunkSize; } @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, State state) throws Exception { switch (state) { case SKIP_CONTROL_CHARS: { try { skipControlCharacters(buffer); checkpoint(State.READ_INITIAL); } finally { checkpoint(); } } case READ_INITIAL: { String[] initialLine = splitInitialLine(readLine(buffer, maxInitialLineLength)); if (initialLine.length < 3) { // Invalid initial line - ignore. checkpoint(State.SKIP_CONTROL_CHARS); return null; } message = createMessage(initialLine); checkpoint(State.READ_HEADER); } case READ_HEADER: { State nextState = readHeaders(buffer); checkpoint(nextState); if (nextState == State.READ_CHUNK_SIZE) { // Chunked encoding // Generate HttpMessage first. HttpChunks will follow. return message; } else if (nextState == State.SKIP_CONTROL_CHARS) { // No content is expected. // Remove the headers which are not supposed to be present not // to confuse subsequent handlers. message.removeHeader(HttpHeaders.Names.CONTENT_LENGTH); message.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); return message; } else { long contentLength = message.getContentLength(-1); if (contentLength == 0 || contentLength == -1 && isDecodingRequest()) { content = ChannelBuffers.EMPTY_BUFFER; return reset(); } switch (nextState) { case READ_FIXED_LENGTH_CONTENT: if (contentLength > maxChunkSize) { // Generate HttpMessage first. HttpChunks will follow. checkpoint(State.READ_FIXED_LENGTH_CONTENT_AS_CHUNKS); message.addHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); // chunkSize will be decreased as the READ_FIXED_LENGTH_CONTENT_AS_CHUNKS // state reads data chunk by chunk. chunkSize = message.getContentLength(-1); return message; } break; case READ_VARIABLE_LENGTH_CONTENT: if (buffer.readableBytes() > maxChunkSize) { // Generate HttpMessage first. HttpChunks will follow. checkpoint(State.READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS); message.addHeader(HttpHeaders.Names.TRANSFER_ENCODING, HttpHeaders.Values.CHUNKED); return message; } break; } } // We return null here, this forces decode to be called again where we will decode the content return null; } case READ_VARIABLE_LENGTH_CONTENT: { if (content == null) { content = ChannelBuffers.dynamicBuffer(channel.getConfig().getBufferFactory()); } //this will cause a replay error until the channel is closed where this will read what's left in the buffer content.writeBytes(buffer.readBytes(buffer.readableBytes())); return reset(); } case READ_VARIABLE_LENGTH_CONTENT_AS_CHUNKS: { // Keep reading data as a chunk until the end of connection is reached. int chunkSize = Math.min(maxChunkSize, buffer.readableBytes()); HttpChunk chunk = new DefaultHttpChunk(buffer.readBytes(chunkSize)); if (!buffer.readable()) { // Reached to the end of the connection. reset(); if (!chunk.isLast()) { // Append the last chunk. return new Object[] { chunk, HttpChunk.LAST_CHUNK }; } } return chunk; } case READ_FIXED_LENGTH_CONTENT: { //we have a content-length so we just read the correct number of bytes readFixedLengthContent(buffer); return reset(); } case READ_FIXED_LENGTH_CONTENT_AS_CHUNKS: { long chunkSize = this.chunkSize; HttpChunk chunk; if (chunkSize > maxChunkSize) { chunk = new DefaultHttpChunk(buffer.readBytes(maxChunkSize)); chunkSize -= maxChunkSize; } else { assert chunkSize <= Integer.MAX_VALUE; chunk = new DefaultHttpChunk(buffer.readBytes((int) chunkSize)); chunkSize = 0; } this.chunkSize = chunkSize; if (chunkSize == 0) { // Read all content. reset(); if (!chunk.isLast()) { // Append the last chunk. return new Object[] { chunk, HttpChunk.LAST_CHUNK }; } } return chunk; } /** * everything else after this point takes care of reading chunked content. basically, read chunk size, * read chunk, read and ignore the CRLF and repeat until 0 */ case READ_CHUNK_SIZE: { String line = readLine(buffer, maxInitialLineLength); int chunkSize = getChunkSize(line); this.chunkSize = chunkSize; if (chunkSize == 0) { checkpoint(State.READ_CHUNK_FOOTER); return null; } else if (chunkSize > maxChunkSize) { // A chunk is too large. Split them into multiple chunks again. checkpoint(State.READ_CHUNKED_CONTENT_AS_CHUNKS); } else { checkpoint(State.READ_CHUNKED_CONTENT); } } case READ_CHUNKED_CONTENT: { assert chunkSize <= Integer.MAX_VALUE; HttpChunk chunk = new DefaultHttpChunk(buffer.readBytes((int) chunkSize)); checkpoint(State.READ_CHUNK_DELIMITER); return chunk; } case READ_CHUNKED_CONTENT_AS_CHUNKS: { long chunkSize = this.chunkSize; HttpChunk chunk; if (chunkSize > maxChunkSize) { chunk = new DefaultHttpChunk(buffer.readBytes(maxChunkSize)); chunkSize -= maxChunkSize; } else { assert chunkSize <= Integer.MAX_VALUE; chunk = new DefaultHttpChunk(buffer.readBytes((int) chunkSize)); chunkSize = 0; } this.chunkSize = chunkSize; if (chunkSize == 0) { // Read all content. checkpoint(State.READ_CHUNK_DELIMITER); } if (!chunk.isLast()) { return chunk; } } case READ_CHUNK_DELIMITER: { for (;;) { byte next = buffer.readByte(); if (next == HttpCodecUtil.CR) { if (buffer.readByte() == HttpCodecUtil.LF) { checkpoint(State.READ_CHUNK_SIZE); return null; } } else if (next == HttpCodecUtil.LF) { checkpoint(State.READ_CHUNK_SIZE); return null; } } } case READ_CHUNK_FOOTER: { // Skip the footer; does anyone use it? try { if (!skipLine(buffer)) { if (maxChunkSize == 0) { // Chunked encoding disabled. return reset(); } else { reset(); // The last chunk, which is empty return HttpChunk.LAST_CHUNK; } } } finally { checkpoint(); } return null; } default: { throw new Error("Shouldn't reach here."); } } } protected boolean isContentAlwaysEmpty(HttpMessage msg) { if (msg instanceof HttpResponse) { HttpResponse res = (HttpResponse) msg; int code = res.getStatus().getCode(); if (code < 200) { return true; } switch (code) { case 204: case 205: case 304: return true; } } return false; } private Object reset() { HttpMessage message = this.message; ChannelBuffer content = this.content; if (content != null) { message.setContent(content); this.content = null; } this.message = null; checkpoint(State.SKIP_CONTROL_CHARS); return message; } private void skipControlCharacters(ChannelBuffer buffer) { for (;;) { char c = (char) buffer.readUnsignedByte(); if (!Character.isISOControl(c) && !Character.isWhitespace(c)) { buffer.readerIndex(buffer.readerIndex() - 1); break; } } } private void readFixedLengthContent(ChannelBuffer buffer) { long length = message.getContentLength(-1); assert length <= Integer.MAX_VALUE; if (content == null) { content = buffer.readBytes((int) length); } else { content.writeBytes(buffer.readBytes((int) length)); } } private State readHeaders(ChannelBuffer buffer) throws TooLongFrameException { headerSize = 0; final HttpMessage message = this.message; String line = readHeader(buffer); String lastHeader = null; if (line.length() != 0) { message.clearHeaders(); do { char firstChar = line.charAt(0); if (lastHeader != null && (firstChar == ' ' || firstChar == '\t')) { List current = message.getHeaders(lastHeader); int lastPos = current.size() - 1; String newString = current.get(lastPos) + line.trim(); current.set(lastPos, newString); } else { String[] header = splitHeader(line); message.addHeader(header[0], header[1]); lastHeader = header[0]; } line = readHeader(buffer); } while (line.length() != 0); } State nextState; if (isContentAlwaysEmpty(message)) { nextState = State.SKIP_CONTROL_CHARS; } else if (message.isChunked()) { nextState = State.READ_CHUNK_SIZE; } else if (message.getContentLength(-1) >= 0) { nextState = State.READ_FIXED_LENGTH_CONTENT; } else { nextState = State.READ_VARIABLE_LENGTH_CONTENT; } return nextState; } private String readHeader(ChannelBuffer buffer) throws TooLongFrameException { StringBuilder sb = new StringBuilder(64); int headerSize = this.headerSize; loop: for (;;) { char nextByte = (char) buffer.readByte(); headerSize ++; switch (nextByte) { case HttpCodecUtil.CR: nextByte = (char) buffer.readByte(); headerSize ++; if (nextByte == HttpCodecUtil.LF) { break loop; } break; case HttpCodecUtil.LF: break loop; } // Abort decoding if the header part is too large. if (headerSize >= maxHeaderSize) { throw new TooLongFrameException( "HTTP header is larger than " + maxHeaderSize + " bytes."); } sb.append(nextByte); } this.headerSize = headerSize; return sb.toString(); } protected abstract boolean isDecodingRequest(); protected abstract HttpMessage createMessage(String[] initialLine) throws Exception; private int getChunkSize(String hex) { hex = hex.trim(); for (int i = 0; i < hex.length(); i ++) { char c = hex.charAt(i); if (c == ';' || Character.isWhitespace(c) || Character.isISOControl(c)) { hex = hex.substring(0, i); break; } } return Integer.parseInt(hex, 16); } private String readLine(ChannelBuffer buffer, int maxLineLength) throws TooLongFrameException { StringBuilder sb = new StringBuilder(64); int lineLength = 0; while (true) { byte nextByte = buffer.readByte(); if (nextByte == HttpCodecUtil.CR) { nextByte = buffer.readByte(); if (nextByte == HttpCodecUtil.LF) { return sb.toString(); } } else if (nextByte == HttpCodecUtil.LF) { return sb.toString(); } else { if (lineLength >= maxLineLength) { throw new TooLongFrameException( "An HTTP line is larger than " + maxLineLength + " bytes."); } lineLength ++; sb.append((char) nextByte); } } } /** * Returns {@code true} if only if the skipped line was not empty. * Please note that an empty line is also skipped, while {@code} false is * returned. */ private boolean skipLine(ChannelBuffer buffer) { int lineLength = 0; while (true) { byte nextByte = buffer.readByte(); if (nextByte == HttpCodecUtil.CR) { nextByte = buffer.readByte(); if (nextByte == HttpCodecUtil.LF) { return lineLength != 0; } } else if (nextByte == HttpCodecUtil.LF) { return lineLength != 0; } else if (!Character.isWhitespace((char) nextByte)) { lineLength ++; } } } private String[] splitInitialLine(String sb) { int aStart; int aEnd; int bStart; int bEnd; int cStart; int cEnd; aStart = findNonWhitespace(sb, 0); aEnd = findWhitespace(sb, aStart); bStart = findNonWhitespace(sb, aEnd); bEnd = findWhitespace(sb, bStart); cStart = findNonWhitespace(sb, bEnd); cEnd = findEndOfString(sb); return new String[] { sb.substring(aStart, aEnd), sb.substring(bStart, bEnd), sb.substring(cStart, cEnd) }; } private String[] splitHeader(String sb) { int nameStart; int nameEnd; int colonEnd; int valueStart; int valueEnd; nameStart = findNonWhitespace(sb, 0); for (nameEnd = nameStart; nameEnd < sb.length(); nameEnd ++) { char ch = sb.charAt(nameEnd); if (ch == ':' || Character.isWhitespace(ch)) { break; } } for (colonEnd = nameEnd; colonEnd < sb.length(); colonEnd ++) { if (sb.charAt(colonEnd) == ':') { colonEnd ++; break; } } valueStart = findNonWhitespace(sb, colonEnd); valueEnd = findEndOfString(sb); return new String[] { sb.substring(nameStart, nameEnd), sb.substring(valueStart, valueEnd) }; } private int findNonWhitespace(String sb, int offset) { int result; for (result = offset; result < sb.length(); result ++) { if (!Character.isWhitespace(sb.charAt(result))) { break; } } return result; } private int findWhitespace(String sb, int offset) { int result; for (result = offset; result < sb.length(); result ++) { if (Character.isWhitespace(sb.charAt(result))) { break; } } return result; } private int findEndOfString(String sb) { int result; for (result = sb.length(); result > 0; result --) { if (!Character.isWhitespace(sb.charAt(result - 1))) { break; } } return result; } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultHttpResponse.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/DefaultHttpResponse.ja0000644000175000017500000000404311216747541032532 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * The default {@link HttpResponse} implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class DefaultHttpResponse extends DefaultHttpMessage implements HttpResponse { private final HttpResponseStatus status; /** * Creates a new instance. * * @param version the HTTP version of this response * @param status the status of this response */ public DefaultHttpResponse(HttpVersion version, HttpResponseStatus status) { super(version); if (status == null) { throw new NullPointerException("status"); } this.status = status; } public HttpResponseStatus getStatus() { return status; } @Override public String toString() { return getProtocolVersion().getText() + ' ' + getStatus().toString(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpResponseStatus.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpResponseStatus.jav0000644000175000017500000002140311216747541032616 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * The response code and its description of HTTP or its derived protocols, such as * RTSP and * ICAP. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.exclude */ public class HttpResponseStatus implements Comparable { /** * 100 Continue */ public static final HttpResponseStatus CONTINUE = new HttpResponseStatus(100, "Continue"); /** * 101 Switching Protocols */ public static final HttpResponseStatus SWITCHING_PROTOCOLS = new HttpResponseStatus(101, "Switching Protocols"); /** * 200 OK */ public static final HttpResponseStatus OK = new HttpResponseStatus(200, "OK"); /** * 201 Created */ public static final HttpResponseStatus CREATED = new HttpResponseStatus(201, "Created"); /** * 202 Accepted */ public static final HttpResponseStatus ACCEPTED = new HttpResponseStatus(202, "Accepted"); /** * 203 Non-Authoritative Information */ public static final HttpResponseStatus NON_AUTHORITATIVE_INFORMATION = new HttpResponseStatus(203, "Non-Authoritative Information"); /** * 204 No Content */ public static final HttpResponseStatus NO_CONTENT = new HttpResponseStatus(204, "No Content"); /** * 205 Reset Content */ public static final HttpResponseStatus RESET_CONTENT = new HttpResponseStatus(205, "Reset Content"); /** * 206 Partial Content */ public static final HttpResponseStatus PARTIAL_CONTENT = new HttpResponseStatus(206, "Partial Content"); /** * 300 Multiple Choices */ public static final HttpResponseStatus MULTIPLE_CHOICES = new HttpResponseStatus(300, "Multiple Choices"); /** * 301 Moved Permanently */ public static final HttpResponseStatus MOVED_PERMANENTLY = new HttpResponseStatus(301, "Moved Permanently"); /** * 302 Found */ public static final HttpResponseStatus FOUND = new HttpResponseStatus(302, "Found"); /** * 303 See Other */ public static final HttpResponseStatus SEE_OTHER = new HttpResponseStatus(303, "See Other"); /** * 304 Not Modified */ public static final HttpResponseStatus NOT_MODIFIED = new HttpResponseStatus(304, "Not Modified"); /** * 305 Use Proxy */ public static final HttpResponseStatus USE_PROXY = new HttpResponseStatus(305, "Use Proxy"); /** * 307 Temporary Redirect */ public static final HttpResponseStatus TEMPORARY_REDIRECT = new HttpResponseStatus(307, "Temporary Redirect"); /** * 400 Bad Request */ public static final HttpResponseStatus BAD_REQUEST = new HttpResponseStatus(400, "Bad Request"); /** * 401 Unauthorized */ public static final HttpResponseStatus UNUATHORIZED = new HttpResponseStatus(401, "Unauthorized"); /** * 402 Payment Required */ public static final HttpResponseStatus PAYMENT_REQUIRED = new HttpResponseStatus(402, "Payment Required"); /** * 403 Forbidden */ public static final HttpResponseStatus FORBIDDEN = new HttpResponseStatus(403, "Forbidden"); /** * 404 Not Found */ public static final HttpResponseStatus NOT_FOUND = new HttpResponseStatus(404, "Not Found"); /** * 405 Method Not Allowed */ public static final HttpResponseStatus METHOD_NOT_ALLOWED = new HttpResponseStatus(405, "Method Not Allowed"); /** * 406 Not Acceptable */ public static final HttpResponseStatus NOT_ACCEPTABLE = new HttpResponseStatus(406, "Not Acceptable"); /** * 407 Proxy Authentication Required */ public static final HttpResponseStatus PROXY_AUTHENTICATION_REQUIRED = new HttpResponseStatus(407, "Proxy Authentication Required"); /** * 408 Request Timeout */ public static final HttpResponseStatus REQUEST_TIMEOUT = new HttpResponseStatus(408, "Request Timeout"); /** * 409 Conflict */ public static final HttpResponseStatus CONFLICT = new HttpResponseStatus(409, "Conflict"); /** * 410 Gone */ public static final HttpResponseStatus GONE = new HttpResponseStatus(410, "Gone"); /** * 411 Length Required */ public static final HttpResponseStatus LENGTH_REQUIRED = new HttpResponseStatus(411, "Length Required"); /** * 412 Precondition Failed */ public static final HttpResponseStatus PRECONDITION_FAILED = new HttpResponseStatus(412, "Precondition Failed"); /** * 413 Request Entity Too Large */ public static final HttpResponseStatus REQUEST_ENTITY_TOO_LARGE = new HttpResponseStatus(413, "Request Entity Too Large"); /** * 414 Request-URI Too Long */ public static final HttpResponseStatus REQUEST_URI_TOO_LONG = new HttpResponseStatus(414, "Request-URI Too Long"); /** * 415 Unsupported Media Type */ public static final HttpResponseStatus UNSUPPORTED_MEDIA_TYPE = new HttpResponseStatus(415, "Unsupported Media Type"); /** * 416 Requested Range Not Satisfiable */ public static final HttpResponseStatus REQUESTED_RANGE_NOT_SATISFIABLE = new HttpResponseStatus(416, "Requested Range Not Satisfiable"); /** * 417 Expectation Failed */ public static final HttpResponseStatus EXPECTATION_FAILED = new HttpResponseStatus(417, "Expectation Failed"); /** * 500 Internal Server Error */ public static final HttpResponseStatus INTERNAL_SERVER_ERROR = new HttpResponseStatus(500, "Internal Server Error"); /** * 501 Not Implemented */ public static final HttpResponseStatus NOT_IMPLEMENTED = new HttpResponseStatus(501, "Not Implemented"); /** * 502 Bad Gateway */ public static final HttpResponseStatus BAD_GATEWAY = new HttpResponseStatus(502, "Bad Gateway"); /** * 503 Service Unavailable */ public static final HttpResponseStatus SERVICE_UNAVAILABLE = new HttpResponseStatus(503, "Service Unavailable"); /** * 504 Gateway Timeout */ public static final HttpResponseStatus GATEWAY_TIMEOUT = new HttpResponseStatus(504, "Gateway Timeout"); /** * 505 HTTP Version Not Supported */ public static final HttpResponseStatus HTTP_VERSION_NOT_SUPPORTED = new HttpResponseStatus(505, "HTTP Version Not Supported"); private final int code; private final String reasonPhrase; /** * Creates a new instance with the specified {@code code} and its * {@code reasonPhrase}. */ public HttpResponseStatus(int code, String reasonPhrase) { this.code = code; this.reasonPhrase = reasonPhrase; } /** * Returns the code of this status. */ public int getCode() { return code; } /** * Returns the reason phrase of this status. */ public String getReasonPhrase() { return reasonPhrase; } @Override public int hashCode() { return getCode(); } @Override public boolean equals(Object o) { if (!(o instanceof HttpResponseStatus)) { return false; } return getCode() == ((HttpResponseStatus) o).getCode(); } public int compareTo(HttpResponseStatus o) { return getCode() - o.getCode(); } @Override public String toString() { StringBuilder buf = new StringBuilder(reasonPhrase.length() + 5); buf.append(code); buf.append(' '); buf.append(reasonPhrase); return buf.toString(); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/QueryStringEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/QueryStringEncoder.jav0000644000175000017500000001132111216747541032546 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.net.URLEncoder; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.List; /** * Creates an URL-encoded URI from a path string and key-value parameter pairs. * This encoder is for one time use only. Create a new instance for each URI. * *
 * QueryStringEncoder encoder = new QueryStringDecoder("/hello");
 * encoder.addParam("recipient", "world");
 * assert encoder.toString().equals("/hello?recipient=world");
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.stereotype utility * @see QueryStringDecoder */ public class QueryStringEncoder { private final String charset; private final String uri; private final List params = new ArrayList(); /** * Creates a new encoder that encodes a URI that starts with the specified * path string. The encoder will encode the URI in UTF-8. */ public QueryStringEncoder(String uri) { this(uri, HttpCodecUtil.DEFAULT_CHARSET); } /** * Creates a new encoder that encodes a URI that starts with the specified * path string in the specified charset. */ public QueryStringEncoder(String uri, String charset) { if (uri == null) { throw new NullPointerException("uri"); } if (charset == null) { throw new NullPointerException("charset"); } this.uri = uri; this.charset = charset; } /** * Adds a parameter with the specified name and value to this encoder. */ public void addParam(String name, String value) { if (name == null) { throw new NullPointerException("name"); } if (value == null) { throw new NullPointerException("value"); } params.add(new Param(name, value)); } /** * Returns the URL-encoded URI object which was created from the path string * specified in the constructor and the parameters added by * {@link #addParam(String, String)} method. */ public URI toUri() throws URISyntaxException { return new URI(toString()); } /** * Returns the URL-encoded URI which was created from the path string * specified in the constructor and the parameters added by * {@link #addParam(String, String)} method. */ @Override public String toString() { if (params.isEmpty()) { return uri; } else { StringBuilder sb = new StringBuilder(uri).append("?"); for (int i = 0; i < params.size(); i++) { Param param = params.get(i); sb.append(encodeComponent(param.name, charset)); sb.append("="); sb.append(encodeComponent(param.value, charset)); if(i != params.size() - 1) { sb.append("&"); } } return sb.toString(); } } private static String encodeComponent(String s, String charset) { try { return URLEncoder.encode(s, charset).replaceAll("\\+", "%20"); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(charset); } } private static final class Param { final String name; final String value; Param(String name, String value) { this.value = value; this.name = name; } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpCodecUtil.java0000644000175000017500000000377511216747541031644 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ class HttpCodecUtil { //space ' ' static final byte SP = 32; //tab ' ' static final byte HT = 9; /** * Carriage return */ static final byte CR = 13; /** * Equals '=' */ static final byte EQUALS = 61; /** * Line feed character */ static final byte LF = 10; /** * carriage return line feed */ static final byte[] CRLF = new byte[] { CR, LF }; /** * Colon ':' */ static final byte COLON = 58; /** * Semicolon ';' */ static final byte SEMICOLON = 59; /** * comma ',' */ static final byte COMMA = 44; static final byte DOUBLE_QUOTE = '"'; static final String DEFAULT_CHARSET = "UTF-8"; private HttpCodecUtil() { super(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/CookieEncoder.java0000644000175000017500000002122311216747541031626 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.Date; import java.util.Set; import java.util.TreeSet; /** * Encodes {@link Cookie}s into an HTTP header value. This encoder can encode * the HTTP cookie version 0, 1, and 2. *

* This encoder is stateful. It maintains an internal data structure that * holds the {@link Cookie}s added by the {@link #addCookie(String, String)} * method. Once {@link #encode()} is called, all added {@link Cookie}s are * encoded into an HTTP header value and all {@link Cookie}s in the internal * data structure are removed so that the encoder can start over. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * @see CookieDecoder */ public class CookieEncoder { private final Set cookies = new TreeSet(); private final boolean server; /** * Creates a new encoder. * * @param server {@code true} if and only if this encoder is supposed to * encode server-side cookies. {@code false} if and only if * this encoder is supposed to encode client-side cookies. */ public CookieEncoder(boolean server) { this.server = server; } /** * Adds a new {@link Cookie} created with the specified name and value to * this encoder. */ public void addCookie(String name, String value) { cookies.add(new DefaultCookie(name, value)); } /** * Adds the specified {@link Cookie} to this encoder. */ public void addCookie(Cookie cookie) { cookies.add(cookie); } /** * Encodes the {@link Cookie}s which were added by {@link #addCookie(Cookie)} * so far into an HTTP header value. If no {@link Cookie}s were added, * an empty string is returned. */ public String encode() { String answer; if (server) { answer = encodeServerSide(); } else { answer = encodeClientSide(); } cookies.clear(); return answer; } private String encodeServerSide() { StringBuilder sb = new StringBuilder(); for (Cookie cookie: cookies) { add(sb, cookie.getName(), cookie.getValue()); if (cookie.getMaxAge() >= 0) { if (cookie.getVersion() == 0) { addUnquoted(sb, CookieHeaderNames.EXPIRES, new CookieDateFormat().format( new Date(System.currentTimeMillis() + cookie.getMaxAge() * 1000L))); } else { add(sb, CookieHeaderNames.MAX_AGE, cookie.getMaxAge()); } } if (cookie.getPath() != null) { if (cookie.getVersion() > 0) { add(sb, CookieHeaderNames.PATH, cookie.getPath()); } else { addUnquoted(sb, CookieHeaderNames.PATH, cookie.getPath()); } } if (cookie.getDomain() != null) { if (cookie.getVersion() > 0) { add(sb, CookieHeaderNames.DOMAIN, cookie.getDomain()); } else { addUnquoted(sb, CookieHeaderNames.DOMAIN, cookie.getDomain()); } } if (cookie.isSecure()) { sb.append(CookieHeaderNames.SECURE); sb.append((char) HttpCodecUtil.SEMICOLON); } if (cookie.getVersion() >= 1) { if (cookie.getComment() != null) { add(sb, CookieHeaderNames.COMMENT, cookie.getComment()); } add(sb, CookieHeaderNames.VERSION, 1); if (cookie.getCommentUrl() != null) { addQuoted(sb, CookieHeaderNames.COMMENTURL, cookie.getCommentUrl()); } if(!cookie.getPorts().isEmpty()) { sb.append(CookieHeaderNames.PORT); sb.append((char) HttpCodecUtil.EQUALS); sb.append((char) HttpCodecUtil.DOUBLE_QUOTE); for (int port: cookie.getPorts()) { sb.append(port); sb.append((char) HttpCodecUtil.COMMA); } sb.setCharAt(sb.length() - 1, (char) HttpCodecUtil.DOUBLE_QUOTE); sb.append((char) HttpCodecUtil.SEMICOLON); } if (cookie.isDiscard()) { sb.append(CookieHeaderNames.DISCARD); sb.append((char) HttpCodecUtil.SEMICOLON); } } } sb.setLength(sb.length() - 1); return sb.toString(); } private String encodeClientSide() { StringBuilder sb = new StringBuilder(); for (Cookie cookie: cookies) { if (cookie.getVersion() >= 1) { add(sb, '$' + CookieHeaderNames.VERSION, 1); } add(sb, cookie.getName(), cookie.getValue()); if (cookie.getPath() != null) { add(sb, '$' + CookieHeaderNames.PATH, cookie.getPath()); } if (cookie.getDomain() != null) { add(sb, '$' + CookieHeaderNames.DOMAIN, cookie.getDomain()); } if (cookie.getVersion() >= 1) { if(!cookie.getPorts().isEmpty()) { sb.append('$'); sb.append(CookieHeaderNames.PORT); sb.append((char) HttpCodecUtil.EQUALS); sb.append((char) HttpCodecUtil.DOUBLE_QUOTE); for (int port: cookie.getPorts()) { sb.append(port); sb.append((char) HttpCodecUtil.COMMA); } sb.setCharAt(sb.length() - 1, (char) HttpCodecUtil.DOUBLE_QUOTE); sb.append((char) HttpCodecUtil.SEMICOLON); } } } sb.setLength(sb.length() - 1); return sb.toString(); } private static void add(StringBuilder sb, String name, String val) { if (val == null) { addQuoted(sb, name, ""); return; } for (int i = 0; i < val.length(); i ++) { char c = val.charAt(i); switch (c) { case '(': case ')': case '<': case '>': case '@': case ',': case ';': case ':': case '"': case '/': case '[': case ']': case '?': case '=': case '{': case '}': case ' ': case '\t': case '\\': addQuoted(sb, name, val); return; } } addUnquoted(sb, name, val); } private static void addUnquoted(StringBuilder sb, String name, String val) { sb.append(name); sb.append((char) HttpCodecUtil.EQUALS); sb.append(val); sb.append((char) HttpCodecUtil.SEMICOLON); } private static void addQuoted(StringBuilder sb, String name, String val) { if (val == null) { val = ""; } sb.append(name); sb.append((char) HttpCodecUtil.EQUALS); sb.append((char) HttpCodecUtil.DOUBLE_QUOTE); sb.append(val.replace("\\", "\\\\").replace("\"", "\\\"")); sb.append((char) HttpCodecUtil.DOUBLE_QUOTE); sb.append((char) HttpCodecUtil.SEMICOLON); } private static void add(StringBuilder sb, String name, int val) { sb.append(name); sb.append((char) HttpCodecUtil.EQUALS); sb.append(val); sb.append((char) HttpCodecUtil.SEMICOLON); } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestDecoder.jav0000644000175000017500000000717411216747541032543 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.codec.frame.TooLongFrameException; /** * Decodes {@link ChannelBuffer}s into {@link HttpRequest}s and {@link HttpChunk}s. * *

Parameters that prevents excessive memory consumption

* * * * * * * * * * * * * * * * *
NameMeaning
{@code maxInitialLineLength}The maximum length of the initial line (e.g. {@code "GET / HTTP/1.0"}) * If the length of the initial line exceeds this value, a * {@link TooLongFrameException} will be raised.
{@code maxHeaderSize}The maximum length of all headers. If the sum of the length of each * header exceeds this value, a {@link TooLongFrameException} will be raised.
{@code maxChunkSize}The maximum length of the content or each chunk. If the content length * exceeds this value, the transfer encoding of the decoded request will be * converted to 'chunked' and the content will be split into multiple * {@link HttpChunk}s. If the transfer encoding of the HTTP request is * 'chunked' already, each chunk will be split into smaller chunks if the * length of the chunk exceeds this value. If you prefer not to handle * {@link HttpChunk}s in your handler, insert {@link HttpChunkAggregator} * after this decoder in the {@link ChannelPipeline}.
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpRequestDecoder extends HttpMessageDecoder { /** * Creates a new instance with the default * {@code maxInitialLineLength (4096}}, {@code maxHeaderSize (4096)}, and * {@code maxChunkSize (4096)}. */ public HttpRequestDecoder() { super(); } /** * Creates a new instance with the specified parameters. */ public HttpRequestDecoder( int maxInitialLineLength, int maxHeaderSize, int maxChunkSize) { super(maxInitialLineLength, maxHeaderSize, maxChunkSize); } @Override protected HttpMessage createMessage(String[] initialLine) throws Exception{ return new DefaultHttpRequest( HttpVersion.valueOf(initialLine[2]), HttpMethod.valueOf(initialLine[0]), initialLine[1]); } @Override protected boolean isDecodingRequest() { return true; } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpRequestEncoder.jav0000644000175000017500000000413411216747541032546 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import static org.jboss.netty.handler.codec.http.HttpCodecUtil.*; import org.jboss.netty.buffer.ChannelBuffer; /** * Encodes an {@link HttpRequest} or an {@link HttpChunk} into * a {@link ChannelBuffer}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpRequestEncoder extends HttpMessageEncoder { /** * Creates a new instance. */ public HttpRequestEncoder() { super(); } @Override protected void encodeInitialLine(ChannelBuffer buf, HttpMessage message) throws Exception { HttpRequest request = (HttpRequest) message; buf.writeBytes(request.getMethod().toString().getBytes("ASCII")); buf.writeByte(SP); buf.writeBytes(request.getUri().getBytes("ASCII")); buf.writeByte(SP); buf.writeBytes(request.getProtocolVersion().toString().getBytes("ASCII")); buf.writeBytes(CRLF); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/package-info.java0000644000175000017500000000226611115445255031442 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Encoder, decoder and their related message types for HTTP. * * @apiviz.exclude \.HttpHeaders.*$ * @apiviz.exclude \.QueryString.*$ */ package org.jboss.netty.handler.codec.http; ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpChunkAggregator.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpChunkAggregator.ja0000644000175000017500000001232711216730466032504 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.List; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.frame.TooLongFrameException; /** * A {@link ChannelHandler} that aggregates an {@link HttpMessage} * and its following {@link HttpChunk}s into a single {@link HttpMessage} with * no following {@link HttpChunk}s. It is useful when you don't want to take * care of HTTP messages whose transfer encoding is 'chunked'. Insert this * handler after {@link HttpMessageDecoder} in the {@link ChannelPipeline}: *
 * ChannelPipeline p = ...;
 * ...
 * p.addLast("decoder", new HttpRequestDecoder());
 * p.addLast("aggregator", new HttpChunkAggregator(1048576));
 * ...
 * p.addLast("encoder", new HttpResponseEncoder());
 * p.addLast("handler", new HttpRequestHandler());
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1476 $, $Date: 2009-06-19 08:39:34 -0700 (Fri, 19 Jun 2009) $ */ @ChannelPipelineCoverage("one") public class HttpChunkAggregator extends SimpleChannelUpstreamHandler { private final int maxContentLength; private volatile HttpMessage currentMessage; /** * Creates a new instance. * * @param maxContentLength * the maximum length of the aggregated content. * If the length of the aggregated content exceeds this value, * a {@link TooLongFrameException} will be raised. */ public HttpChunkAggregator(int maxContentLength) { if (maxContentLength <= 0) { throw new IllegalArgumentException( "maxContentLength must be a positive integer: " + maxContentLength); } this.maxContentLength = maxContentLength; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object msg = e.getMessage(); if (!(msg instanceof HttpMessage) && !(msg instanceof HttpChunk)) { ctx.sendUpstream(e); return; } HttpMessage currentMessage = this.currentMessage; if (currentMessage == null) { HttpMessage m = (HttpMessage) msg; if (m.isChunked()) { // A chunked message - remove 'Transfer-Encoding' header, // initialize the cumulative buffer, and wait for incoming chunks. List encodings = m.getHeaders(HttpHeaders.Names.TRANSFER_ENCODING); encodings.remove(HttpHeaders.Values.CHUNKED); if (encodings.isEmpty()) { m.removeHeader(HttpHeaders.Names.TRANSFER_ENCODING); } m.setContent(ChannelBuffers.dynamicBuffer(e.getChannel().getConfig().getBufferFactory())); this.currentMessage = m; } else { // Not a chunked message - pass through. ctx.sendUpstream(e); } } else { // Merge the received chunk into the content of the current message. HttpChunk chunk = (HttpChunk) msg; ChannelBuffer content = currentMessage.getContent(); if (content.readableBytes() > maxContentLength - chunk.getContent().readableBytes()) { throw new TooLongFrameException( "HTTP content length exceeded " + maxContentLength + " bytes."); } content.writeBytes(chunk.getContent()); if (chunk.isLast()) { this.currentMessage = null; currentMessage.setHeader( HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(content.readableBytes())); Channels.fireMessageReceived(ctx, currentMessage, e.getRemoteAddress()); } } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpMessageEncoder.jav0000644000175000017500000001135211216747541032502 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import static org.jboss.netty.buffer.ChannelBuffers.*; import static org.jboss.netty.handler.codec.http.HttpCodecUtil.*; import java.io.UnsupportedEncodingException; import java.util.List; import java.util.Set; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * Encodes an {@link HttpMessage} or an {@link HttpChunk} into * a {@link ChannelBuffer}. * *

Extensibility

* * Please note that this encoder is designed to be extended to implement * a protocol derived from HTTP, such as * RTSP and * ICAP. * To implement the encoder of such a derived protocol, extend this class and * implement all abstract methods properly. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ @ChannelPipelineCoverage("all") public abstract class HttpMessageEncoder extends OneToOneEncoder { private static final ChannelBuffer LAST_CHUNK = copiedBuffer("0\r\n\r\n", "ASCII"); /** * Creates a new instance. */ protected HttpMessageEncoder() { super(); } @Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (msg instanceof HttpMessage) { HttpMessage request = (HttpMessage) msg; ChannelBuffer header = ChannelBuffers.dynamicBuffer( channel.getConfig().getBufferFactory()); encodeInitialLine(header, request); encodeHeaders(header, request); header.writeBytes(CRLF); ChannelBuffer content = request.getContent(); if (!content.readable()) { return header; // no content } else { return wrappedBuffer(header, content); } } if (msg instanceof HttpChunk) { HttpChunk chunk = (HttpChunk) msg; if (chunk.isLast()) { return LAST_CHUNK.duplicate(); } else { ChannelBuffer content = chunk.getContent(); int contentLength = content.readableBytes(); return wrappedBuffer( copiedBuffer(Integer.toHexString(contentLength), "ASCII"), wrappedBuffer(CRLF), content.slice(content.readerIndex(), contentLength), wrappedBuffer(CRLF)); } } // Unknown message type. return msg; } private void encodeHeaders(ChannelBuffer buf, HttpMessage message) { Set headers = message.getHeaderNames(); try { for (String header : headers) { List values = message.getHeaders(header); for (String value : values) { buf.writeBytes(header.getBytes("ASCII")); buf.writeByte(COLON); buf.writeByte(SP); buf.writeBytes(value.getBytes("ASCII")); buf.writeBytes(CRLF); } } } catch (UnsupportedEncodingException e) { throw (Error) new Error().initCause(e); } } protected abstract void encodeInitialLine(ChannelBuffer buf, HttpMessage message) throws Exception; } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/QueryStringDecoder.jav0000644000175000017500000001256111216747541032543 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URLDecoder; import java.nio.charset.UnsupportedCharsetException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.regex.Matcher; import java.util.regex.Pattern; /** * Splits an HTTP query string into a path string and key-value parameter pairs. * This decoder is for one time use only. Create a new instance for each URI: *
 * QueryStringDecoder decoder = new QueryStringDecoder("/hello?recipient=world");
 * assert decoder.getPath().equals("/hello");
 * assert decoder.getParameters().get("recipient").equals("world");
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.stereotype utility * @see QueryStringEncoder */ public class QueryStringDecoder { private static final Pattern PARAM_PATTERN = Pattern.compile("([^=]*)=([^&]*)&*"); private final String charset; private final String uri; private String path; private final Map> params = new HashMap>(); /** * Creates a new decoder that decodes the specified URI. The decoder will * assume that the query string is encoded in UTF-8. */ public QueryStringDecoder(String uri) { this(uri, HttpCodecUtil.DEFAULT_CHARSET); } /** * Creates a new decoder that decodes the specified URI encoded in the * specified charset. */ public QueryStringDecoder(String uri, String charset) { if (uri == null) { throw new NullPointerException("uri"); } if (charset == null) { throw new NullPointerException("charset"); } this.uri = uri; this.charset = charset; } /** * Creates a new decoder that decodes the specified URI. The decoder will * assume that the query string is encoded in UTF-8. */ public QueryStringDecoder(URI uri) { this(uri, HttpCodecUtil.DEFAULT_CHARSET); } /** * Creates a new decoder that decodes the specified URI encoded in the * specified charset. */ public QueryStringDecoder(URI uri, String charset){ if (uri == null) { throw new NullPointerException("uri"); } if (charset == null) { throw new NullPointerException("charset"); } this.uri = uri.toASCIIString(); this.charset = charset; } /** * Returns the decoded path string of the URI. */ public String getPath() { //decode lazily if(path == null) { if(uri.contains("?")) { decode(); } else { path = uri; } } return path; } /** * Returns the decoded key-value parameter pairs of the URI. */ public Map> getParameters() { if(path == null){ if(uri.contains("?")) { decode(); } else { path = uri; } } return params; } private void decode() { int pathEndPos = uri.indexOf('?'); if (pathEndPos < 0) { path = uri; } else { path = uri.substring(0, pathEndPos); decodeParams(uri.substring(pathEndPos + 1)); } } private void decodeParams(String s) { Matcher m = PARAM_PATTERN.matcher(s); int pos = 0; while (m.find(pos)) { pos = m.end(); String key = decodeComponent(m.group(1), charset); String value = decodeComponent(m.group(2), charset); List values = params.get(key); if(values == null) { values = new ArrayList(); params.put(key,values); } values.add(value); } } private static String decodeComponent(String s, String charset) { if (s == null) { return ""; } try { return URLDecoder.decode(s, charset); } catch (UnsupportedEncodingException e) { throw new UnsupportedCharsetException(charset); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpMethod.java0000644000175000017500000001474711216747541031212 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.util.HashMap; import java.util.Map; /** * The request method of HTTP or its derived protocols, such as * RTSP and * ICAP. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ * * @apiviz.exclude */ public class HttpMethod implements Comparable { /** * The OPTIONS method represents a request for information about the communication options available on the request/response * chain identified by the Request-URI. This method allows the client to determine the options and/or requirements * associated with a resource, or the capabilities of a server, without implying a resource action or initiating a * resource retrieval. */ public static final HttpMethod OPTIONS = new HttpMethod("OPTIONS"); /** * The GET method means retrieve whatever information (in the form of an entity) is identified by the Request-URI. * If the Request-URI refers to a data-producing process, it is the produced data which shall be returned as the entity * in the response and not the source text of the process, unless that text happens to be the output of the process. */ public static final HttpMethod GET = new HttpMethod("GET"); /** * The HEAD method is identical to GET except that the server MUST NOT return a message-body in the response. */ public static final HttpMethod HEAD = new HttpMethod("HEAD"); /** * The POST method is used to request that the origin server accept the entity enclosed in the request as a new * subordinate of the resource identified by the Request-URI in the Request-Line. */ public static final HttpMethod POST = new HttpMethod("POST"); /** * The PUT method requests that the enclosed entity be stored under the supplied Request-URI. */ public static final HttpMethod PUT = new HttpMethod("PUT"); /** * The DELETE method requests that the origin server delete the resource identified by the Request-URI. */ public static final HttpMethod DELETE = new HttpMethod("DELETE"); /** * The TRACE method is used to invoke a remote, application-layer loop- back of the request message. */ public static final HttpMethod TRACE = new HttpMethod("TRACE"); /** * This specification reserves the method name CONNECT for use with a proxy that can dynamically switch to being a tunnel */ public static final HttpMethod CONNECT = new HttpMethod("CONNECT"); private static final Map methodMap = new HashMap(); static { methodMap.put(OPTIONS.toString(), OPTIONS); methodMap.put(GET.toString(), GET); methodMap.put(HEAD.toString(), HEAD); methodMap.put(POST.toString(), POST); methodMap.put(PUT.toString(), PUT); methodMap.put(DELETE.toString(), DELETE); methodMap.put(TRACE.toString(), TRACE); methodMap.put(CONNECT.toString(), CONNECT); } /** * Returns the {@link HttpMethod} represented by the specified name. * If the specified name is a standard HTTP method name, a cached instance * will be returned. Otherwise, a new instance will be returned. */ public static HttpMethod valueOf(String name) { if (name == null) { throw new NullPointerException("name"); } name = name.trim().toUpperCase(); if (name.length() == 0) { throw new IllegalArgumentException("empty name"); } HttpMethod result = methodMap.get(name); if (result != null) { return result; } else { return new HttpMethod(name); } } private final String name; /** * Creates a new HTTP method with the specified name. You will not need to * create a new method unless you are implementing a protocol derived from * HTTP, such as * RTSP and * ICAP */ public HttpMethod(String name) { if (name == null) { throw new NullPointerException("name"); } name = name.trim().toUpperCase(); if (name.length() == 0) { throw new IllegalArgumentException("empty name"); } for (int i = 0; i < name.length(); i ++) { if (Character.isISOControl(name.charAt(i)) || Character.isWhitespace(name.charAt(i))) { throw new IllegalArgumentException("invalid character in name"); } } this.name = name; } /** * Returns the name of this method. */ public String getName() { return name; } @Override public int hashCode() { return getName().hashCode(); } @Override public boolean equals(Object o) { if (!(o instanceof HttpMethod)) { return false; } HttpMethod that = (HttpMethod) o; return getName().equals(that.getName()); } @Override public String toString() { return getName(); } public int compareTo(HttpMethod o) { return getName().compareTo(o.getName()); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/CookieDateFormat.java0000644000175000017500000000310311157220475032266 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import java.text.SimpleDateFormat; import java.util.Locale; import java.util.TimeZone; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1063 $, $Date: 2009-03-15 08:39:41 -0700 (Sun, 15 Mar 2009) $ */ final class CookieDateFormat extends SimpleDateFormat { private static final long serialVersionUID = 1789486337887402640L; CookieDateFormat() { super("E, d-MMM-y HH:mm:ss z", Locale.ENGLISH); setTimeZone(TimeZone.getTimeZone("GMT")); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/http/HttpChunk.java0000644000175000017500000000360111216724133031015 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.http; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; /** * An HTTP chunk which is used for HTTP chunked transfer-encoding. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1472 $, $Date: 2009-06-19 08:01:47 -0700 (Fri, 19 Jun 2009) $ */ public interface HttpChunk { /** * The 'end of content' maker in chunked encoding. */ static HttpChunk LAST_CHUNK = new DefaultHttpChunk(ChannelBuffers.EMPTY_BUFFER); /** * Returns {@code true} if and only if this chunk is the 'end of content' * marker. */ boolean isLast(); /** * Returns the content of this chunk. If this is the 'end of content' * maker, {@link ChannelBuffers#EMPTY_BUFFER} will be returned. */ ChannelBuffer getContent(); } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/string/0000755000175000017500000000000011316313150026563 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/string/StringEncoder.java0000644000175000017500000000654411126301650032206 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.string; import static org.jboss.netty.buffer.ChannelBuffers.*; import java.nio.charset.Charset; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * Encodes the requested {@link String} into a {@link ChannelBuffer}. * A typical setup for a text-based line protocol in a TCP/IP socket would be: *
 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}({@link Delimiters#lineDelimiter()}));
 * pipeline.addLast("stringDecoder", new {@link StringDecoder}("UTF-8"));
 *
 * // Encoder
 * pipeline.addLast("stringEncoder", new {@link StringEncoder}("UTF-8"));
 * 
* and then you can use a {@link String} instead of a {@link ChannelBuffer} * as a message: *
 * void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     String msg = (String) e.getMessage();
 *     ch.write("Did you say '" + msg + "'?\n");
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ @ChannelPipelineCoverage("all") public class StringEncoder extends OneToOneEncoder { private final String charsetName; /** * Creates a new instance with the current system character set. */ public StringEncoder() { this(Charset.defaultCharset()); } public StringEncoder(String charsetName) { this(Charset.forName(charsetName)); } public StringEncoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } charsetName = charset.name(); } @Override protected Object encode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof String)) { return msg; } return copiedBuffer(String.valueOf(msg), charsetName); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/string/StringDecoder.java0000644000175000017500000000743611126301650032175 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.string; import java.nio.charset.Charset; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.frame.FrameDecoder; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; /** * Decodes a received {@link ChannelBuffer} into a {@link String}. Please * note that this decoder must be used with a proper {@link FrameDecoder} * such as {@link DelimiterBasedFrameDecoder} if you are using a stream-based * transport such as TCP/IP. A typical setup for a text-based line protocol * in a TCP/IP socket would be: *
 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#lineDelimiter()}));
 * pipeline.addLast("stringDecoder", new {@link StringDecoder}("UTF-8"));
 *
 * // Encoder
 * pipeline.addLast("stringEncoder", new {@link StringEncoder}("UTF-8"));
 * 
* and then you can use a {@link String} instead of a {@link ChannelBuffer} * as a message: *
 * void messageReceived(ChannelHandlerContext ctx, MessageEvent e) {
 *     String msg = (String) e.getMessage();
 *     ch.write("Did you say '" + msg + "'?\n");
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ @ChannelPipelineCoverage("all") public class StringDecoder extends OneToOneDecoder { private final String charsetName; /** * Creates a new instance with the current system character set. */ public StringDecoder() { this(Charset.defaultCharset()); } /** * Creates a new instance. * * @param charsetName the name of the character set to use for decoding */ public StringDecoder(String charsetName) { this(Charset.forName(charsetName)); } /** * Creates a new instance. * * @param charset the character set to use for decoding */ public StringDecoder(Charset charset) { if (charset == null) { throw new NullPointerException("charset"); } charsetName = charset.name(); } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof ChannelBuffer)) { return msg; } return ((ChannelBuffer) msg).toString(charsetName); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/string/package-info.java0000644000175000017500000000226711057673271032000 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Encoder and decoder which transform a {@link java.lang.String} into a * {@link org.jboss.netty.buffer.ChannelBuffer} and vice versa. */ package org.jboss.netty.handler.codec.string;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/0000755000175000017500000000000011316313152030134 5ustar deckerdecker././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompatibleObjectDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompatibleObj0000644000175000017500000001164211211663220032573 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.ObjectStreamConstants; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferInputStream; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.replay.ReplayingDecoder; import org.jboss.netty.util.internal.SwitchableInputStream; /** * A decoder which deserializes the received {@link ChannelBuffer}s into Java * objects (interoperability version). *

* This decoder is interoperable with the standard Java object * streams such as {@link ObjectInputStream} and {@link ObjectOutputStream}. *

* However, this decoder might perform worse than {@link ObjectDecoder} if * the serialized object is big and complex. Also, it does not limit the * maximum size of the object, and consequently your application might face * the risk of DoS attack. * Please use {@link ObjectEncoder} and {@link ObjectDecoder} if you are not * required to keep the interoperability with the standard object streams. * * @deprecated This decoder has a known critical bug which fails to decode and * raises a random exception in some circumstances. Avoid to use * it whenever you can. The only workaround is to replace * {@link CompatibleObjectEncoder}, {@link CompatibleObjectDecoder}, * {@link ObjectInputStream}, and {@link ObjectOutputStream} with * {@link ObjectEncoder}, {@link ObjectDecoder}, * {@link ObjectEncoderOutputStream}, and * {@link ObjectDecoderInputStream} respectively. This workaround * requires both a client and a server to be modified. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1324 $, $Date: 2009-06-03 23:15:44 -0700 (Wed, 03 Jun 2009) $ */ @Deprecated public class CompatibleObjectDecoder extends ReplayingDecoder { private final SwitchableInputStream bin = new SwitchableInputStream(); private volatile ObjectInputStream oin; /** * Creates a new decoder. */ public CompatibleObjectDecoder() { super(CompatibleObjectDecoderState.READ_HEADER); } /** * Creates a new {@link ObjectInputStream} which wraps the specified * {@link InputStream}. Override this method to use a subclass of the * {@link ObjectInputStream}. */ protected ObjectInputStream newObjectInputStream(InputStream in) throws Exception { return new ObjectInputStream(in); } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, CompatibleObjectDecoderState state) throws Exception { bin.switchStream(new ChannelBufferInputStream(buffer)); switch (state) { case READ_HEADER: oin = newObjectInputStream(bin); checkpoint(CompatibleObjectDecoderState.READ_OBJECT); case READ_OBJECT: return oin.readObject(); default: throw new IllegalStateException("Unknown state: " + state); } } @Override protected Object decodeLast(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, CompatibleObjectDecoderState state) throws Exception { switch (buffer.readableBytes()) { case 0: return null; case 1: // Ignore the last TC_RESET if (buffer.getByte(buffer.readerIndex()) == ObjectStreamConstants.TC_RESET) { buffer.skipBytes(1); oin.close(); return null; } } Object decoded = decode(ctx, channel, buffer, state); oin.close(); return decoded; } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompactObjectOutputStream.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompactObject0000644000175000017500000000415011216447237032607 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.io.IOException; import java.io.ObjectOutputStream; import java.io.ObjectStreamClass; import java.io.OutputStream; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1445 $, $Date: 2009-06-18 07:26:39 -0700 (Thu, 18 Jun 2009) $ * */ class CompactObjectOutputStream extends ObjectOutputStream { static final int TYPE_FAT_DESCRIPTOR = 0; static final int TYPE_THIN_DESCRIPTOR = 1; CompactObjectOutputStream(OutputStream out) throws IOException { super(out); } @Override protected void writeStreamHeader() throws IOException { writeByte(STREAM_VERSION); } @Override protected void writeClassDescriptor(ObjectStreamClass desc) throws IOException { Class clazz = desc.forClass(); if (clazz.isPrimitive() || clazz.isArray()) { write(TYPE_FAT_DESCRIPTOR); super.writeClassDescriptor(desc); } else { write(TYPE_THIN_DESCRIPTOR); writeUTF(desc.getName()); } } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectEncoderOutputStream.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectEncoder0000644000175000017500000001260411117161251032570 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.io.DataOutputStream; import java.io.IOException; import java.io.ObjectOutput; import java.io.ObjectOutputStream; import java.io.OutputStream; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferOutputStream; import org.jboss.netty.buffer.ChannelBuffers; /** * An {@link ObjectOutput} which is interoperable with {@link ObjectDecoder} * and {@link ObjectDecoderInputStream}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 595 $, $Date: 2008-12-08 01:02:33 -0800 (Mon, 08 Dec 2008) $ * */ public class ObjectEncoderOutputStream extends OutputStream implements ObjectOutput { private final DataOutputStream out; private final int estimatedLength; /** * Creates a new {@link ObjectOutput} with the estimated length of 512 * bytes. * * @param out * the {@link OutputStream} where the serialized form will be * written out */ public ObjectEncoderOutputStream(OutputStream out) { this(out, 512); } /** * Creates a new {@link ObjectOutput}. * * @param out * the {@link OutputStream} where the serialized form will be * written out * * @param estimatedLength * the estimated byte length of the serialized form of an object. * If the length of the serialized form exceeds this value, the * internal buffer will be expanded automatically at the cost of * memory bandwidth. If this value is too big, it will also waste * memory bandwidth. To avoid unnecessary memory copy or allocation * cost, please specify the properly estimated value. */ public ObjectEncoderOutputStream(OutputStream out, int estimatedLength) { if (out == null) { throw new NullPointerException("out"); } if (estimatedLength < 0) { throw new IllegalArgumentException("estimatedLength: " + estimatedLength); } if (out instanceof DataOutputStream) { this.out = (DataOutputStream) out; } else { this.out = new DataOutputStream(out); } this.estimatedLength = estimatedLength; } public void writeObject(Object obj) throws IOException { ChannelBufferOutputStream bout = new ChannelBufferOutputStream( ChannelBuffers.dynamicBuffer(estimatedLength)); ObjectOutputStream oout = new CompactObjectOutputStream(bout); oout.writeObject(obj); oout.flush(); oout.close(); ChannelBuffer buffer = bout.buffer(); int objectSize = buffer.readableBytes(); writeInt(objectSize); buffer.getBytes(0, this, objectSize); } @Override public void write(int b) throws IOException { out.write(b); } @Override public void close() throws IOException { out.close(); } @Override public void flush() throws IOException { out.flush(); } public final int size() { return out.size(); } @Override public void write(byte[] b, int off, int len) throws IOException { out.write(b, off, len); } @Override public void write(byte[] b) throws IOException { out.write(b); } public final void writeBoolean(boolean v) throws IOException { out.writeBoolean(v); } public final void writeByte(int v) throws IOException { out.writeByte(v); } public final void writeBytes(String s) throws IOException { out.writeBytes(s); } public final void writeChar(int v) throws IOException { out.writeChar(v); } public final void writeChars(String s) throws IOException { out.writeChars(s); } public final void writeDouble(double v) throws IOException { out.writeDouble(v); } public final void writeFloat(float v) throws IOException { out.writeFloat(v); } public final void writeInt(int v) throws IOException { out.writeInt(v); } public final void writeLong(long v) throws IOException { out.writeLong(v); } public final void writeShort(int v) throws IOException { out.writeShort(v); } public final void writeUTF(String str) throws IOException { out.writeUTF(str); } } ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompactObjectInputStream.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompactObject0000644000175000017500000000706311216447237032615 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.io.EOFException; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInputStream; import java.io.ObjectStreamClass; import java.io.StreamCorruptedException; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1445 $, $Date: 2009-06-18 07:26:39 -0700 (Thu, 18 Jun 2009) $ * */ class CompactObjectInputStream extends ObjectInputStream { private final ClassLoader classLoader; CompactObjectInputStream(InputStream in) throws IOException { this(in, null); } CompactObjectInputStream(InputStream in, ClassLoader classLoader) throws IOException { super(in); this.classLoader = classLoader; } @Override protected void readStreamHeader() throws IOException, StreamCorruptedException { int version = readByte() & 0xFF; if (version != STREAM_VERSION) { throw new StreamCorruptedException( "Unsupported version: " + version); } } @Override protected ObjectStreamClass readClassDescriptor() throws IOException, ClassNotFoundException { int type = read(); if (type < 0) { throw new EOFException(); } switch (type) { case CompactObjectOutputStream.TYPE_FAT_DESCRIPTOR: return super.readClassDescriptor(); case CompactObjectOutputStream.TYPE_THIN_DESCRIPTOR: String className = readUTF(); Class clazz = loadClass(className); return ObjectStreamClass.lookup(clazz); default: throw new StreamCorruptedException( "Unexpected class descriptor type: " + type); } } @Override protected Class resolveClass(ObjectStreamClass desc) throws IOException, ClassNotFoundException { String className = desc.getName(); try { return loadClass(className); } catch (ClassNotFoundException ex) { return super.resolveClass(desc); } } protected Class loadClass(String className) throws ClassNotFoundException { Class clazz; ClassLoader classLoader = this.classLoader; if (classLoader == null) { classLoader = Thread.currentThread().getContextClassLoader(); } if (classLoader != null) { clazz = classLoader.loadClass(className); } else { clazz = Class.forName(className); } return clazz; } } ././@LongLink0000000000000000000000000000017100000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompatibleObjectDecoderState.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompatibleObj0000644000175000017500000000246311046721772032611 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 6 $, $Date: 2008-08-07 18:40:10 -0700 (Thu, 07 Aug 2008) $ * */ enum CompatibleObjectDecoderState { READ_HEADER, READ_OBJECT, } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/package-info.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/package-info.0000644000175000017500000000237711046721772032505 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Encoder, decoder and their compatibility stream implementations which * transform a {@link java.io.Serializable} object into a byte buffer and * vice versa. * * @apiviz.exclude ^java\..*Stream$ */ package org.jboss.netty.handler.codec.serialization; ././@LongLink0000000000000000000000000000016500000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectDecoderInputStream.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectDecoder0000644000175000017500000001544111130536210032554 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.io.DataInputStream; import java.io.IOException; import java.io.InputStream; import java.io.ObjectInput; import java.io.StreamCorruptedException; /** * An {@link ObjectInput} which is interoperable with {@link ObjectEncoder} * and {@link ObjectEncoderOutputStream}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 628 $, $Date: 2009-01-05 18:06:00 -0800 (Mon, 05 Jan 2009) $ * */ public class ObjectDecoderInputStream extends InputStream implements ObjectInput { private final DataInputStream in; private final ClassLoader classLoader; private final int maxObjectSize; /** * Creates a new {@link ObjectInput}. * * @param in * the {@link InputStream} where the serialized form will be * read from */ public ObjectDecoderInputStream(InputStream in) { this(in, null); } /** * Creates a new {@link ObjectInput}. * * @param in * the {@link InputStream} where the serialized form will be * read from * @param classLoader * the {@link ClassLoader} which will load the class of the * serialized object */ public ObjectDecoderInputStream(InputStream in, ClassLoader classLoader) { this(in, classLoader, 1048576); } /** * Creates a new {@link ObjectInput}. * * @param in * the {@link InputStream} where the serialized form will be * read from * @param maxObjectSize * the maximum byte length of the serialized object. if the length * of the received object is greater than this value, * a {@link StreamCorruptedException} will be raised. */ public ObjectDecoderInputStream(InputStream in, int maxObjectSize) { this(in, null, maxObjectSize); } /** * Creates a new {@link ObjectInput}. * * @param in * the {@link InputStream} where the serialized form will be * read from * @param classLoader * the {@link ClassLoader} which will load the class of the * serialized object * @param maxObjectSize * the maximum byte length of the serialized object. if the length * of the received object is greater than this value, * a {@link StreamCorruptedException} will be raised. */ public ObjectDecoderInputStream(InputStream in, ClassLoader classLoader, int maxObjectSize) { if (in == null) { throw new NullPointerException("in"); } if (maxObjectSize <= 0) { throw new IllegalArgumentException("maxObjectSize: " + maxObjectSize); } if (in instanceof DataInputStream) { this.in = (DataInputStream) in; } else { this.in = new DataInputStream(in); } this.classLoader = classLoader; this.maxObjectSize = maxObjectSize; } public Object readObject() throws ClassNotFoundException, IOException { int dataLen = readInt(); if (dataLen <= 0) { throw new StreamCorruptedException("invalid data length: " + dataLen); } if (dataLen > maxObjectSize) { throw new StreamCorruptedException( "data length too big: " + dataLen + " (max: " + maxObjectSize + ')'); } return new CompactObjectInputStream(in, classLoader).readObject(); } @Override public int available() throws IOException { return in.available(); } @Override public void close() throws IOException { in.close(); } @Override public void mark(int readlimit) { in.mark(readlimit); } @Override public boolean markSupported() { return in.markSupported(); } @Override public int read() throws IOException { return in.read(); } @Override public final int read(byte[] b, int off, int len) throws IOException { return in.read(b, off, len); } @Override public final int read(byte[] b) throws IOException { return in.read(b); } public final boolean readBoolean() throws IOException { return in.readBoolean(); } public final byte readByte() throws IOException { return in.readByte(); } public final char readChar() throws IOException { return in.readChar(); } public final double readDouble() throws IOException { return in.readDouble(); } public final float readFloat() throws IOException { return in.readFloat(); } public final void readFully(byte[] b, int off, int len) throws IOException { in.readFully(b, off, len); } public final void readFully(byte[] b) throws IOException { in.readFully(b); } public final int readInt() throws IOException { return in.readInt(); } @Deprecated public final String readLine() throws IOException { return in.readLine(); } public final long readLong() throws IOException { return in.readLong(); } public final short readShort() throws IOException { return in.readShort(); } public final int readUnsignedByte() throws IOException { return in.readUnsignedByte(); } public final int readUnsignedShort() throws IOException { return in.readUnsignedShort(); } public final String readUTF() throws IOException { return in.readUTF(); } @Override public void reset() throws IOException { in.reset(); } @Override public long skip(long n) throws IOException { return in.skip(n); } public final int skipBytes(int n) throws IOException { return in.skipBytes(n); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectEncoder0000644000175000017500000000733411157402463032603 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import static org.jboss.netty.buffer.ChannelBuffers.*; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferOutputStream; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * An encoder which serializes a Java object into a {@link ChannelBuffer}. *

* Please note that the serialized form this encoder produces is not * compatible with the standard {@link ObjectInputStream}. Please use * {@link ObjectDecoder} or {@link ObjectDecoderInputStream} to ensure the * interoperability with this encoder. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ * * @apiviz.landmark */ @ChannelPipelineCoverage("all") public class ObjectEncoder extends OneToOneEncoder { private static final byte[] LENGTH_PLACEHOLDER = new byte[4]; private final int estimatedLength; /** * Creates a new encoder with the estimated length of 512 bytes. */ public ObjectEncoder() { this(512); } /** * Creates a new encoder. * * @param estimatedLength * the estimated byte length of the serialized form of an object. * If the length of the serialized form exceeds this value, the * internal buffer will be expanded automatically at the cost of * memory bandwidth. If this value is too big, it will also waste * memory bandwidth. To avoid unnecessary memory copy or allocation * cost, please specify the properly estimated value. */ public ObjectEncoder(int estimatedLength) { if (estimatedLength < 0) { throw new IllegalArgumentException( "estimatedLength: " + estimatedLength); } this.estimatedLength = estimatedLength; } @Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { ChannelBufferOutputStream bout = new ChannelBufferOutputStream(dynamicBuffer( estimatedLength, ctx.getChannel().getConfig().getBufferFactory())); bout.write(LENGTH_PLACEHOLDER); ObjectOutputStream oout = new CompactObjectOutputStream(bout); oout.writeObject(msg); oout.flush(); oout.close(); ChannelBuffer encoded = bout.buffer(); encoded.setInt(0, encoded.writerIndex() - 4); return encoded; } } ././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompatibleObjectEncoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/CompatibleObj0000644000175000017500000001165111122126170032572 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.io.OutputStream; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.ChannelBufferOutputStream; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * An encoder which serializes a Java object into a {@link ChannelBuffer} * (interoperability version). *

* This encoder is interoperable with the standard Java object streams such as * {@link ObjectInputStream} and {@link ObjectOutputStream}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev:231 $, $Date:2008-06-12 16:44:50 +0900 (목, 12 6월 2008) $ */ @ChannelPipelineCoverage("one") public class CompatibleObjectEncoder extends OneToOneEncoder { private final AtomicReference buffer = new AtomicReference(); private final int resetInterval; private volatile ObjectOutputStream oout; private int writtenObjects; /** * Creates a new instance with the reset interval of {@code 16}. */ public CompatibleObjectEncoder() { this(16); // Reset at every sixteen writes } /** * Creates a new instance. * * @param resetInterval * the number of objects between {@link ObjectOutputStream#reset()}. * {@code 0} will disable resetting the stream, but the remote * peer will be at the risk of getting {@link OutOfMemoryError} in * the long term. */ public CompatibleObjectEncoder(int resetInterval) { if (resetInterval < 0) { throw new IllegalArgumentException( "resetInterval: " + resetInterval); } this.resetInterval = resetInterval; } /** * Creates a new {@link ObjectOutputStream} which wraps the specified * {@link OutputStream}. Override this method to use a subclass of the * {@link ObjectOutputStream}. */ protected ObjectOutputStream newObjectOutputStream(OutputStream out) throws Exception { return new ObjectOutputStream(out); } @Override protected Object encode(ChannelHandlerContext context, Channel channel, Object msg) throws Exception { ChannelBuffer buffer = buffer(context); ObjectOutputStream oout = this.oout; if (resetInterval != 0) { // Resetting will prevent OOM on the receiving side. writtenObjects ++; if (writtenObjects % resetInterval == 0) { oout.reset(); // Also discard the byproduct to avoid OOM on the sending side. buffer.discardReadBytes(); } } oout.writeObject(msg); oout.flush(); ChannelBuffer encoded = buffer.readBytes(buffer.readableBytes()); return encoded; } private ChannelBuffer buffer(ChannelHandlerContext ctx) throws Exception { ChannelBuffer buf = buffer.get(); if (buf == null) { ChannelBufferFactory factory = ctx.getChannel().getConfig().getBufferFactory(); buf = ChannelBuffers.dynamicBuffer(factory); if (buffer.compareAndSet(null, buf)) { boolean success = false; try { oout = newObjectOutputStream(new ChannelBufferOutputStream(buf)); success = true; } finally { if (!success) { oout = null; } } } else { buf = buffer.get(); } } return buf; } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/serialization/ObjectDecoder0000644000175000017500000001062711157402463032570 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.serialization; import java.io.ObjectOutputStream; import java.io.StreamCorruptedException; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferInputStream; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.frame.FrameDecoder; /** * A decoder which deserializes the received {@link ChannelBuffer}s into Java * objects. *

* Please note that the serialized form this decoder expects is not * compatible with the standard {@link ObjectOutputStream}. Please use * {@link ObjectEncoder} or {@link ObjectEncoderOutputStream} to ensure the * interoperability with this decoder. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1072 $, $Date: 2009-03-16 00:52:19 -0700 (Mon, 16 Mar 2009) $ * * @apiviz.landmark */ public class ObjectDecoder extends FrameDecoder { private final int maxObjectSize; private final ClassLoader classLoader; /** * Creates a new decoder whose maximum object size is {@code 1048576} * bytes. If the size of the received object is greater than * {@code 1048576} bytes, a {@link StreamCorruptedException} will be * raised. */ public ObjectDecoder() { this(1048576); } /** * Creates a new decoder with the specified maximum object size. * * @param maxObjectSize the maximum byte length of the serialized object. * if the length of the received object is greater * than this value, {@link StreamCorruptedException} * will be raised. */ public ObjectDecoder(int maxObjectSize) { this(maxObjectSize, null); } /** * Creates a new decoder with the specified maximum object size. * * @param maxObjectSize the maximum byte length of the serialized object. * if the length of the received object is greater * than this value, {@link StreamCorruptedException} * will be raised. * @param classLoader the {@link ClassLoader} which will load the class * of the serialized object */ public ObjectDecoder(int maxObjectSize, ClassLoader classLoader) { if (maxObjectSize <= 0) { throw new IllegalArgumentException("maxObjectSize: " + maxObjectSize); } this.maxObjectSize = maxObjectSize; this.classLoader = classLoader; } @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { if (buffer.readableBytes() < 4) { return null; } int dataLen = buffer.getInt(buffer.readerIndex()); if (dataLen <= 0) { throw new StreamCorruptedException("invalid data length: " + dataLen); } if (dataLen > maxObjectSize) { throw new StreamCorruptedException( "data length too big: " + dataLen + " (max: " + maxObjectSize + ')'); } if (buffer.readableBytes() < dataLen + 4) { return null; } buffer.skipBytes(4); return new CompactObjectInputStream( new ChannelBufferInputStream(buffer, dataLen), classLoader).readObject(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/0000755000175000017500000000000011316313152026553 5ustar deckerdecker././@LongLink0000000000000000000000000000016000000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/UnsafeDynamicChannelBuffer.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/UnsafeDynamicChannel0000644000175000017500000000324611117161251032522 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.replay; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.DynamicChannelBuffer; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 595 $, $Date: 2008-12-08 01:02:33 -0800 (Mon, 08 Dec 2008) $ * */ class UnsafeDynamicChannelBuffer extends DynamicChannelBuffer { UnsafeDynamicChannelBuffer(ChannelBufferFactory factory) { super(factory.getDefaultOrder(), 256, factory); } @Override protected void checkReadableBytes(int minReaderRemaining) { // Do not check here - ReplayingDecoderBuffer will check. } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/ReplayError.java0000644000175000017500000000257411046721772031707 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.replay; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 6 $, $Date: 2008-08-07 18:40:10 -0700 (Thu, 07 Aug 2008) $ * */ class ReplayError extends Error { private static final long serialVersionUID = 2666698631187527681L; ReplayError() { super(); } }././@LongLink0000000000000000000000000000016400000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/UnreplayableOperationException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/UnreplayableOperatio0000644000175000017500000000420411216653504032633 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.replay; import org.jboss.netty.buffer.ChannelBuffer; /** * An {@link Exception} which is thrown when a user calls an unsupported * operation on a {@link ChannelBuffer} in a {@link ReplayingDecoder} * implementation. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1455 $, $Date: 2009-06-19 02:15:48 -0700 (Fri, 19 Jun 2009) $ */ public class UnreplayableOperationException extends UnsupportedOperationException { private static final long serialVersionUID = 8577363912862364021L; /** * Creates a new instance. */ public UnreplayableOperationException() { super(); } /** * Creates a new instance. */ public UnreplayableOperationException(String message) { super(message); } /** * Creates a new instance. */ public UnreplayableOperationException(Throwable cause) { super(cause); } /** * Creates a new instance. */ public UnreplayableOperationException(String message, Throwable cause) { super(message, cause); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/package-info.java0000644000175000017500000000234011057700632031746 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Specialized variation of {@link org.jboss.netty.handler.codec.frame.FrameDecoder} * which enables implementation of a non-blocking decoder in the blocking I/O * paradigm. */ package org.jboss.netty.handler.codec.replay; ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/ReplayingDecoder.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/ReplayingDecoder.jav0000644000175000017500000004437411215374110032510 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.replay; import java.net.SocketAddress; import java.util.concurrent.atomic.AtomicReference; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.Channels; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.frame.FrameDecoder; /** * A specialized variation of {@link FrameDecoder} which enables implementation * of a non-blocking decoder in the blocking I/O paradigm. *

* The biggest difference between {@link ReplayingDecoder} and * {@link FrameDecoder} is that {@link ReplayingDecoder} allows you to * implement the {@code decode()} and {@code decodeLast()} methods just like * all required bytes were received already, rather than checking the * availability of the required bytes. For example, the following * {@link FrameDecoder} implementation: *

 * public class IntegerHeaderFrameDecoder extends FrameDecoder {
 *
 *   protected Object decode(ChannelHandlerContext ctx,
 *                           Channel channel,
 *                           ChannelBuffer buf) throws Exception {
 *
 *     if (buf.readableBytes() < 4) {
 *        return null;
 *     }
 *
 *     buf.markReaderIndex();
 *     int length = buf.readInt();
 *
 *     if (buf.readableBytes() < length) {
 *        buf.resetReaderIndex();
 *        return null;
 *     }
 *
 *     return buf.readBytes(length);
 *   }
 * }
 * 
* is simplified like the following with {@link ReplayingDecoder}: *
 * public class IntegerHeaderFrameDecoder
 *      extends ReplayingDecoder<VoidEnum> {
 *
 *   protected Object decode(ChannelHandlerContext ctx,
 *                           Channel channel,
 *                           ChannelBuffer buf,
 *                           VoidEnum state) throws Exception {
 *
 *     return buf.readBytes(buf.readInt());
 *   }
 * }
 * 
* *

How does this work?

*

* {@link ReplayingDecoder} passes a specialized {@link ChannelBuffer} * implementation which throws an {@link Error} of certain type when there's not * enough data in the buffer. In the {@code IntegerHeaderFrameDecoder} above, * you just assumed that there will be 4 or more bytes in the buffer when * you call {@code buf.readInt()}. If there's really 4 bytes in the buffer, * it will return the integer header as you expected. Otherwise, the * {@link Error} will be raised and the control will be returned to * {@link ReplayingDecoder}. If {@link ReplayingDecoder} catches the * {@link Error}, then it will rewind the {@code readerIndex} of the buffer * back to the 'initial' position (i.e. the beginning of the buffer) and call * the {@code decode(..)} method again when more data is received into the * buffer. *

* Please note that the overhead of throwing an {@link Error} is minimal unlike * throwing a new {@link Exception} in an ordinary way. {@link ReplayingDecoder} * reuses the same {@link Error} instance so that it does not need to fill its * stack trace, which takes most of {@link Exception} initialization time. * *

Limitations

*

* At the cost of the simplicity, {@link ReplayingDecoder} enforces you a few * limitations: *

    *
  • Some buffer operations are prohibited.
  • *
  • Performance can be worse if the network is slow and the message * format is complicated unlike the example above. In this case, your * decoder might have to decode the same part of the message over and over * again.
  • *
  • You must keep in mind that {@code decode(..)} method can be called many * times to decode a single message. For example, the following code will * not work: *
     public class MyDecoder extends ReplayingDecoder<VoidEnum> {
     *
     *   private final Queue<Integer> values = new LinkedList<Integer>();
     *
     *   public Object decode(.., ChannelBuffer buffer, ..) throws Exception {
     *
     *     // A message contains 2 integers.
     *     values.offer(buffer.readInt());
     *     values.offer(buffer.readInt());
     *
     *     // This assertion will fail intermittently since values.offer()
     *     // can be called more than two times!
     *     assert values.size() == 2;
     *     return values.poll() + values.poll();
     *   }
     * }
    * The correct implementation looks like the following, and you can also * utilize the 'checkpoint' feature which is explained in detail in the * next section. *
     public class MyDecoder extends ReplayingDecoder<VoidEnum> {
     *
     *   private final Queue<Integer> values = new LinkedList<Integer>();
     *
     *   public Object decode(.., ChannelBuffer buffer, ..) throws Exception {
     *
     *     // Revert the state of the variable that might have been changed
     *     // since the last partial decode.
     *     values.clear();
     *
     *     // A message contains 2 integers.
     *     values.offer(buffer.readInt());
     *     values.offer(buffer.readInt());
     *
     *     // Now we know this assertion will never fail.
     *     assert values.size() == 2;
     *     return values.poll() + values.poll();
     *   }
     * }
    *
  • *
* *

Improving the performance

*

* Fortunately, the performance of a complex decoder implementation can be * improved significantly with the {@code checkpoint()} method. The * {@code checkpoint()} method updates the 'initial' position of the buffer so * that {@link ReplayingDecoder} rewinds the {@code readerIndex} of the buffer * to the last position where you called the {@code checkpoint()} method. * *

Calling {@code checkpoint(T)} with an {@link Enum}

*

* Although you can just use {@code checkpoint()} method and manage the state * of the decoder by yourself, the easiest way to manage the state of the * decoder is to create an {@link Enum} type which represents the current state * of the decoder and to call {@code checkpoint(T)} method whenever the state * changes. You can have as many states as you want depending on the * complexity of the message you want to decode: * *

 * public enum MyDecoderState {
 *   READ_LENGTH,
 *   READ_CONTENT;
 * }
 *
 * public class IntegerHeaderFrameDecoder
 *      extends ReplayingDecoder<MyDecoderState> {
 *
 *   private int length;
 *
 *   public IntegerHeaderFrameDecoder() {
 *     // Set the initial state.
 *     super(MyDecoderState.READ_LENGTH);
 *   }
 *
 *   protected Object decode(ChannelHandlerContext ctx,
 *                           Channel channel,
 *                           ChannelBuffer buf,
 *                           MyDecoderState state) throws Exception {
 *     switch (state) {
 *     case READ_LENGTH:
 *       length = buf.readInt();
 *       checkpoint(MyDecoderState.READ_CONTENT);
 *     case READ_CONTENT:
 *       ChannelBuffer frame = buf.readBytes(length);
 *       checkpoint(MyDecoderState.READ_LENGTH);
 *       return frame;
 *     default:
 *       throw new Error("Shouldn't reach here.");
 *     }
 *   }
 * }
 * 
* *

Calling {@code checkpoint()} with no parameter

*

* An alternative way to manage the decoder state is to manage it by yourself. *

 * public class IntegerHeaderFrameDecoder
 *      extends ReplayingDecoder<VoidEnum> {
 *
 *   private boolean readLength;
 *   private int length;
 *
 *   protected Object decode(ChannelHandlerContext ctx,
 *                           Channel channel,
 *                           ChannelBuffer buf,
 *                           MyDecoderState state) throws Exception {
 *     if (!readLength) {
 *       length = buf.readInt();
 *       readLength = true;
 *       checkpoint();
 *     }
 *
 *     if (readLength) {
 *       ChannelBuffer frame = buf.readBytes(length);
 *       readLength = false;
 *       checkpoint();
 *       return frame;
 *     }
 *   }
 * }
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1367 $, $Date: 2009-06-15 00:29:12 -0700 (Mon, 15 Jun 2009) $ * * @param * the state type; use {@link VoidEnum} if state management is unused * * @apiviz.landmark */ @ChannelPipelineCoverage("one") public abstract class ReplayingDecoder> extends SimpleChannelUpstreamHandler { private final AtomicReference cumulation = new AtomicReference(); private final boolean unfold; private volatile ReplayingDecoderBuffer replayable; private volatile T state; private volatile int checkpoint; /** * Creates a new instance with no initial state (i.e: {@code null}). */ protected ReplayingDecoder() { this(null); } protected ReplayingDecoder(boolean unfold) { this(null, unfold); } /** * Creates a new instance with the specified initial state. */ protected ReplayingDecoder(T initialState) { this(initialState, false); } protected ReplayingDecoder(T initialState, boolean unfold) { this.state = initialState; this.unfold = unfold; } /** * Stores the internal cumulative buffer's reader position. */ protected void checkpoint() { ChannelBuffer cumulation = this.cumulation.get(); if (cumulation != null) { checkpoint = cumulation.readerIndex(); } else { checkpoint = -1; // buffer not available (already cleaned up) } } /** * Stores the internal cumulative buffer's reader position and updates * the current decoder state. */ protected void checkpoint(T state) { checkpoint(); setState(state); } /** * Returns the current state of this decoder. * @return the current state of this decoder */ protected T getState() { return state; } /** * Sets the current state of this decoder. * @return the old state of this decoder */ protected T setState(T newState) { T oldState = state; state = newState; return oldState; } /** * Decodes the received packets so far into a frame. * * @param ctx the context of this handler * @param channel the current channel * @param buffer the cumulative buffer of received packets so far. * Note that the buffer might be empty, which means you * should not make an assumption that the buffer contains * at least one byte in your decoder implementation. * @param state the current decoder state ({@code null} if unused) * * @return the decoded frame */ protected abstract Object decode(ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, T state) throws Exception; /** * Decodes the received data so far into a frame when the channel is * disconnected. * * @param ctx the context of this handler * @param channel the current channel * @param buffer the cumulative buffer of received packets so far. * Note that the buffer might be empty, which means you * should not make an assumption that the buffer contains * at least one byte in your decoder implementation. * @param state the current decoder state ({@code null} if unused) * * @return the decoded frame */ protected Object decodeLast( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer, T state) throws Exception { return decode(ctx, channel, buffer, state); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { Object m = e.getMessage(); if (!(m instanceof ChannelBuffer)) { ctx.sendUpstream(e); return; } ChannelBuffer input = (ChannelBuffer) m; if (!input.readable()) { return; } ChannelBuffer cumulation = cumulation(ctx); cumulation.discardReadBytes(); cumulation.writeBytes(input); callDecode(ctx, e.getChannel(), cumulation, e.getRemoteAddress()); } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { cleanup(ctx, e); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { cleanup(ctx, e); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { ctx.sendUpstream(e); } private void callDecode(ChannelHandlerContext context, Channel channel, ChannelBuffer cumulation, SocketAddress remoteAddress) throws Exception { while (cumulation.readable()) { int oldReaderIndex = checkpoint = cumulation.readerIndex(); Object result = null; T oldState = state; try { result = decode(context, channel, replayable, state); if (result == null) { if (oldReaderIndex == cumulation.readerIndex() && oldState == state) { throw new IllegalStateException( "null cannot be returned if no data is consumed and state didn't change."); } else { // Previous data has been discarded or caused state transition. // Probably it is reading on. continue; } } } catch (ReplayError replay) { // Return to the checkpoint (or oldPosition) and retry. int checkpoint = this.checkpoint; if (checkpoint >= 0) { cumulation.readerIndex(checkpoint); } else { // Called by cleanup() - no need to maintain the readerIndex // anymore because the buffer has been released already. } } if (result == null) { // Seems like more data is required. // Let us wait for the next notification. break; } if (oldReaderIndex == cumulation.readerIndex() && oldState == state) { throw new IllegalStateException( "decode() method must consume at least one byte " + "if it returned a decoded message."); } // A successful decode unfoldAndfireMessageReceived(context, result, remoteAddress); } } private void unfoldAndfireMessageReceived( ChannelHandlerContext context, Object result, SocketAddress remoteAddress) { if (unfold) { if (result instanceof Object[]) { for (Object r: (Object[]) result) { Channels.fireMessageReceived(context, r, remoteAddress); } } else if (result instanceof Iterable) { for (Object r: (Iterable) result) { Channels.fireMessageReceived(context, r, remoteAddress); } } else { Channels.fireMessageReceived(context, result, remoteAddress); } } else { Channels.fireMessageReceived(context, result, remoteAddress); } } private void cleanup(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { try { ChannelBuffer cumulation = this.cumulation.getAndSet(null); if (cumulation == null) { return; } replayable.terminate(); if (cumulation.readable()) { // Make sure all data was read before notifying a closed channel. callDecode(ctx, e.getChannel(), cumulation, null); } // Call decodeLast() finally. Please note that decodeLast() is // called even if there's nothing more to read from the buffer to // notify a user that the connection was closed explicitly. Object partiallyDecoded = decodeLast(ctx, e.getChannel(), replayable, state); if (partiallyDecoded != null) { unfoldAndfireMessageReceived(ctx, partiallyDecoded, null); } } catch (ReplayError replay) { // Ignore } finally { ctx.sendUpstream(e); } } private ChannelBuffer cumulation(ChannelHandlerContext ctx) { ChannelBuffer buf = cumulation.get(); if (buf == null) { ChannelBufferFactory factory = ctx.getChannel().getConfig().getBufferFactory(); buf = new UnsafeDynamicChannelBuffer(factory); if (cumulation.compareAndSet(null, buf)) { replayable = new ReplayingDecoderBuffer(buf); } else { buf = cumulation.get(); } } return buf; } } ././@LongLink0000000000000000000000000000015400000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/ReplayingDecoderBuffer.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/ReplayingDecoderBuff0000644000175000017500000003704711211635475032545 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.replay; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.channels.GatheringByteChannel; import java.nio.channels.ScatteringByteChannel; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.ChannelBufferIndexFinder; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1317 $, $Date: 2009-06-03 20:10:53 -0700 (Wed, 03 Jun 2009) $ * */ class ReplayingDecoderBuffer implements ChannelBuffer { private static final Error REPLAY = new ReplayError(); private final ChannelBuffer buffer; private boolean terminated; ReplayingDecoderBuffer(ChannelBuffer buffer) { this.buffer = buffer; } void terminate() { terminated = true; } public int capacity() { if (terminated) { return buffer.capacity(); } else { return Integer.MAX_VALUE; } } public void clear() { throw new UnreplayableOperationException(); } @Override public boolean equals(Object obj) { return this == obj; } public int compareTo(ChannelBuffer buffer) { throw new UnreplayableOperationException(); } public ChannelBuffer copy() { throw new UnreplayableOperationException(); } public ChannelBuffer copy(int index, int length) { checkIndex(index, length); return buffer.copy(index, length); } public void discardReadBytes() { throw new UnreplayableOperationException(); } public ChannelBuffer duplicate() { throw new UnreplayableOperationException(); } public byte getByte(int index) { checkIndex(index); return buffer.getByte(index); } public short getUnsignedByte(int index) { checkIndex(index); return buffer.getUnsignedByte(index); } public void getBytes(int index, byte[] dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, byte[] dst) { checkIndex(index, dst.length); buffer.getBytes(index, dst); } public void getBytes(int index, ByteBuffer dst) { throw new UnreplayableOperationException(); } public void getBytes(int index, ChannelBuffer dst, int dstIndex, int length) { checkIndex(index, length); buffer.getBytes(index, dst, dstIndex, length); } public void getBytes(int index, ChannelBuffer dst, int length) { throw new UnreplayableOperationException(); } public void getBytes(int index, ChannelBuffer dst) { throw new UnreplayableOperationException(); } public int getBytes(int index, GatheringByteChannel out, int length) throws IOException { throw new UnreplayableOperationException(); } public void getBytes(int index, OutputStream out, int length) throws IOException { throw new UnreplayableOperationException(); } public int getInt(int index) { checkIndex(index, 4); return buffer.getInt(index); } public long getUnsignedInt(int index) { checkIndex(index, 4); return buffer.getUnsignedInt(index); } public long getLong(int index) { checkIndex(index, 8); return buffer.getLong(index); } public int getMedium(int index) { checkIndex(index, 3); return buffer.getMedium(index); } public int getUnsignedMedium(int index) { checkIndex(index, 3); return buffer.getUnsignedMedium(index); } public short getShort(int index) { checkIndex(index, 2); return buffer.getShort(index); } public int getUnsignedShort(int index) { checkIndex(index, 2); return buffer.getUnsignedShort(index); } @Override public int hashCode() { throw new UnreplayableOperationException(); } public int indexOf(int fromIndex, int toIndex, byte value) { int endIndex = buffer.indexOf(fromIndex, toIndex, value); if (endIndex < 0) { throw REPLAY; } return endIndex; } public int indexOf(int fromIndex, int toIndex, ChannelBufferIndexFinder indexFinder) { int endIndex = buffer.indexOf(fromIndex, toIndex, indexFinder); if (endIndex < 0) { throw REPLAY; } return endIndex; } public void markReaderIndex() { buffer.markReaderIndex(); } public void markWriterIndex() { throw new UnreplayableOperationException(); } public ChannelBufferFactory factory() { return buffer.factory(); } public ByteOrder order() { return buffer.order(); } public boolean readable() { return terminated? buffer.readable() : true; } public int readableBytes() { if (terminated) { return buffer.readableBytes(); } else { return Integer.MAX_VALUE - buffer.readerIndex(); } } public byte readByte() { checkReadableBytes(1); return buffer.readByte(); } public short readUnsignedByte() { checkReadableBytes(1); return buffer.readUnsignedByte(); } public void readBytes(byte[] dst, int dstIndex, int length) { checkReadableBytes(length); buffer.readBytes(dst, dstIndex, length); } public void readBytes(byte[] dst) { checkReadableBytes(dst.length); buffer.readBytes(dst); } public void readBytes(ByteBuffer dst) { throw new UnreplayableOperationException(); } public void readBytes(ChannelBuffer dst, int dstIndex, int length) { checkReadableBytes(length); buffer.readBytes(dst, dstIndex, length); } public void readBytes(ChannelBuffer dst, int length) { throw new UnreplayableOperationException(); } public void readBytes(ChannelBuffer dst) { throw new UnreplayableOperationException(); } public ChannelBuffer readBytes(ChannelBufferIndexFinder endIndexFinder) { int endIndex = buffer.indexOf(buffer.readerIndex(), buffer.writerIndex(), endIndexFinder); if (endIndex < 0) { throw REPLAY; } return buffer.readBytes(endIndex - buffer.readerIndex()); } public int readBytes(GatheringByteChannel out, int length) throws IOException { throw new UnreplayableOperationException(); } public ChannelBuffer readBytes(int length) { checkReadableBytes(length); return buffer.readBytes(length); } public ChannelBuffer readSlice( ChannelBufferIndexFinder endIndexFinder) { int endIndex = buffer.indexOf(buffer.readerIndex(), buffer.writerIndex(), endIndexFinder); if (endIndex < 0) { throw REPLAY; } return buffer.readSlice(endIndex - buffer.readerIndex()); } public ChannelBuffer readSlice(int length) { checkReadableBytes(length); return buffer.readSlice(length); } public void readBytes(OutputStream out, int length) throws IOException { throw new UnreplayableOperationException(); } public int readerIndex() { return buffer.readerIndex(); } public void readerIndex(int readerIndex) { buffer.readerIndex(readerIndex); } public int readInt() { checkReadableBytes(4); return buffer.readInt(); } public long readUnsignedInt() { checkReadableBytes(4); return buffer.readUnsignedInt(); } public long readLong() { checkReadableBytes(8); return buffer.readLong(); } public int readMedium() { checkReadableBytes(3); return buffer.readMedium(); } public int readUnsignedMedium() { checkReadableBytes(3); return buffer.readUnsignedMedium(); } public short readShort() { checkReadableBytes(2); return buffer.readShort(); } public int readUnsignedShort() { checkReadableBytes(2); return buffer.readUnsignedShort(); } public void resetReaderIndex() { buffer.resetReaderIndex(); } public void resetWriterIndex() { throw new UnreplayableOperationException(); } public void setByte(int index, byte value) { throw new UnreplayableOperationException(); } public void setBytes(int index, byte[] src, int srcIndex, int length) { throw new UnreplayableOperationException(); } public void setBytes(int index, byte[] src) { throw new UnreplayableOperationException(); } public void setBytes(int index, ByteBuffer src) { throw new UnreplayableOperationException(); } public void setBytes(int index, ChannelBuffer src, int srcIndex, int length) { throw new UnreplayableOperationException(); } public void setBytes(int index, ChannelBuffer src, int length) { throw new UnreplayableOperationException(); } public void setBytes(int index, ChannelBuffer src) { throw new UnreplayableOperationException(); } public int setBytes(int index, InputStream in, int length) throws IOException { throw new UnreplayableOperationException(); } public void setZero(int index, int length) { throw new UnreplayableOperationException(); } public int setBytes(int index, ScatteringByteChannel in, int length) throws IOException { throw new UnreplayableOperationException(); } public void setIndex(int readerIndex, int writerIndex) { throw new UnreplayableOperationException(); } public void setInt(int index, int value) { throw new UnreplayableOperationException(); } public void setLong(int index, long value) { throw new UnreplayableOperationException(); } public void setMedium(int index, int value) { throw new UnreplayableOperationException(); } public void setShort(int index, short value) { throw new UnreplayableOperationException(); } public int skipBytes(ChannelBufferIndexFinder firstIndexFinder) { int oldReaderIndex = buffer.readerIndex(); int newReaderIndex = buffer.indexOf(oldReaderIndex, buffer.writerIndex(), firstIndexFinder); if (newReaderIndex < 0) { throw REPLAY; } buffer.readerIndex(newReaderIndex); return newReaderIndex - oldReaderIndex; } public void skipBytes(int length) { checkReadableBytes(length); buffer.skipBytes(length); } public ChannelBuffer slice() { throw new UnreplayableOperationException(); } public ChannelBuffer slice(int index, int length) { checkIndex(index, length); return buffer.slice(index, length); } public ByteBuffer toByteBuffer() { throw new UnreplayableOperationException(); } public ByteBuffer toByteBuffer(int index, int length) { return buffer.toByteBuffer(index, length); } public ByteBuffer[] toByteBuffers() { throw new UnreplayableOperationException(); } public ByteBuffer[] toByteBuffers(int index, int length) { checkIndex(index, length); return buffer.toByteBuffers(index, length); } public String toString(int index, int length, String charsetName) { checkIndex(index, length); return buffer.toString(index, length, charsetName); } public String toString( int index, int length, String charsetName, ChannelBufferIndexFinder terminatorFinder) { checkIndex(index, length); return buffer.toString(index, length, charsetName, terminatorFinder); } public String toString(String charsetName) { throw new UnreplayableOperationException(); } public String toString( String charsetName, ChannelBufferIndexFinder terminatorFinder) { throw new UnreplayableOperationException(); } @Override public String toString() { return getClass().getSimpleName() + '(' + "ridx=" + readerIndex() + ", " + "widx=" + writerIndex() + ')'; } public boolean writable() { return false; } public int writableBytes() { return 0; } public void writeByte(byte value) { throw new UnreplayableOperationException(); } public void writeBytes(byte[] src, int srcIndex, int length) { throw new UnreplayableOperationException(); } public void writeBytes(byte[] src) { throw new UnreplayableOperationException(); } public void writeBytes(ByteBuffer src) { throw new UnreplayableOperationException(); } public void writeBytes(ChannelBuffer src, int srcIndex, int length) { throw new UnreplayableOperationException(); } public void writeBytes(ChannelBuffer src, int length) { throw new UnreplayableOperationException(); } public void writeBytes(ChannelBuffer src) { throw new UnreplayableOperationException(); } public int writeBytes(InputStream in, int length) throws IOException { throw new UnreplayableOperationException(); } public int writeBytes(ScatteringByteChannel in, int length) throws IOException { throw new UnreplayableOperationException(); } public void writeInt(int value) { throw new UnreplayableOperationException(); } public void writeLong(long value) { throw new UnreplayableOperationException(); } public void writeMedium(int value) { throw new UnreplayableOperationException(); } public void writeZero(int length) { throw new UnreplayableOperationException(); } public int writerIndex() { return buffer.writerIndex(); } public void writerIndex(int writerIndex) { throw new UnreplayableOperationException(); } public void writeShort(short value) { throw new UnreplayableOperationException(); } private void checkIndex(int index) { if (index > buffer.writerIndex()) { throw REPLAY; } } private void checkIndex(int index, int length) { if (index + length > buffer.writerIndex()) { throw REPLAY; } } private void checkReadableBytes(int readableBytes) { if (buffer.readableBytes() < readableBytes) { throw REPLAY; } } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/replay/VoidEnum.java0000644000175000017500000000273011066406360031154 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.replay; /** * A placeholder {@link Enum} which could be specified as a type parameter of * {@link ReplayingDecoder} when a user wants to manage the decoder state or * there's no state to manage. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 303 $, $Date: 2008-09-24 02:48:32 -0700 (Wed, 24 Sep 2008) $ * */ public enum VoidEnum { // No state is defined. } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/base64/0000755000175000017500000000000011316313150026341 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/base64/Base64Encoder.java0000644000175000017500000000572411126301010031527 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.base64; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * Encodes a {@link ChannelBuffer} into a Base64-encoded {@link ChannelBuffer}. * A typical setup for TCP/IP would be: *
 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
 * pipeline.addLast("base64Decoder", new {@link Base64Decoder}());
 *
 * // Encoder
 * pipeline.addLast("base64Encoder", new {@link Base64Encoder}());
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 620 $, $Date: 2008-12-29 18:06:00 -0800 (Mon, 29 Dec 2008) $ */ public class Base64Encoder extends OneToOneEncoder { private final boolean breakLines; private final Base64Dialect dialect; public Base64Encoder() { this(true); } public Base64Encoder(boolean breakLines) { this(breakLines, Base64Dialect.STANDARD); } public Base64Encoder(boolean breakLines, Base64Dialect dialect) { if (dialect == null) { throw new NullPointerException("dialect"); } this.breakLines = breakLines; this.dialect = dialect; } @Override protected Object encode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof ChannelBuffer)) { return msg; } ChannelBuffer src = (ChannelBuffer) msg; return Base64.encode( src, src.readerIndex(), src.readableBytes(), breakLines, dialect); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/base64/Base64Dialect.java0000644000175000017500000002741511126133556031540 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Robert Harder and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.handler.codec.base64; /** * Enumeration of supported Base64 dialects. *

* The internal lookup tables in this class has been derived from * Robert Harder's Public Domain Base64 Encoder/Decoder. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Robert Harder (rob@iharder.net) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 619 $, $Date: 2008-12-29 03:41:34 -0800 (Mon, 29 Dec 2008) $ */ public enum Base64Dialect { /** * Standard Base64 encoding as described in the Section 3 of * RFC3548. */ STANDARD(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '+', (byte) '/' }, new byte[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 62, // Plus sign at decimal 43 -9, -9, -9, // Decimal 44 - 46 63, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, -9, -9, // Decimal 91 - 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, // Decimal 123 - 126 /* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }, true), /** * Base64-like encoding that is URL-safe as described in the Section 4 of * RFC3548. It is * important to note that data encoded this way is not officially * valid Base64, or at the very least should not be called Base64 without * also specifying that is was encoded using the URL-safe dialect. */ URL_SAFE(new byte[] { (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) '-', (byte) '_' }, new byte[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 62, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, // Letters 'A' through 'N' 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, // Letters 'O' through 'Z' -9, -9, -9, -9, // Decimal 91 - 94 63, // Underscore at decimal 95 -9, // Decimal 96 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, // Letters 'a' through 'm' 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, // Letters 'n' through 'z' -9, -9, -9, -9, // Decimal 123 - 126 /*-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }, false), /** * Special "ordered" dialect of Base64 described in * RFC1940. */ ORDERED(new byte[] { (byte) '-', (byte) '0', (byte) '1', (byte) '2', (byte) '3', (byte) '4', (byte) '5', (byte) '6', (byte) '7', (byte) '8', (byte) '9', (byte) 'A', (byte) 'B', (byte) 'C', (byte) 'D', (byte) 'E', (byte) 'F', (byte) 'G', (byte) 'H', (byte) 'I', (byte) 'J', (byte) 'K', (byte) 'L', (byte) 'M', (byte) 'N', (byte) 'O', (byte) 'P', (byte) 'Q', (byte) 'R', (byte) 'S', (byte) 'T', (byte) 'U', (byte) 'V', (byte) 'W', (byte) 'X', (byte) 'Y', (byte) 'Z', (byte) '_', (byte) 'a', (byte) 'b', (byte) 'c', (byte) 'd', (byte) 'e', (byte) 'f', (byte) 'g', (byte) 'h', (byte) 'i', (byte) 'j', (byte) 'k', (byte) 'l', (byte) 'm', (byte) 'n', (byte) 'o', (byte) 'p', (byte) 'q', (byte) 'r', (byte) 's', (byte) 't', (byte) 'u', (byte) 'v', (byte) 'w', (byte) 'x', (byte) 'y', (byte) 'z' }, new byte[] { -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 0 - 8 -5, -5, // Whitespace: Tab and Linefeed -9, -9, // Decimal 11 - 12 -5, // Whitespace: Carriage Return -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 14 - 26 -9, -9, -9, -9, -9, // Decimal 27 - 31 -5, // Whitespace: Space -9, -9, -9, -9, -9, -9, -9, -9, -9, -9, // Decimal 33 - 42 -9, // Plus sign at decimal 43 -9, // Decimal 44 0, // Minus sign at decimal 45 -9, // Decimal 46 -9, // Slash at decimal 47 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, // Numbers zero through nine -9, -9, -9, // Decimal 58 - 60 -1, // Equals sign at decimal 61 -9, -9, -9, // Decimal 62 - 64 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, // Letters 'A' through 'M' 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, // Letters 'N' through 'Z' -9, -9, -9, -9, // Decimal 91 - 94 37, // Underscore at decimal 95 -9, // Decimal 96 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, // Letters 'a' through 'm' 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, // Letters 'n' through 'z' -9, -9, -9, -9, // Decimal 123 - 126 /* -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243 -9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */ }, true); final byte[] alphabet; final byte[] decodabet; final boolean breakLinesByDefault; private Base64Dialect(byte[] alphabet, byte[] decodabet, boolean breakLinesByDefault) { this.alphabet = alphabet; this.decodabet = decodabet; this.breakLinesByDefault = breakLinesByDefault; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/base64/Base64.java0000644000175000017500000003512611153452262030246 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /* * Written by Robert Harder and released to the public domain, as explained at * http://creativecommons.org/licenses/publicdomain */ package org.jboss.netty.handler.codec.base64; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBufferFactory; import org.jboss.netty.buffer.HeapChannelBufferFactory; /** * Utility class for {@link ChannelBuffer} that encodes and decodes to and from * Base64 notation. *

* The encoding and decoding algorithm in this class has been derived from * Robert Harder's Public Domain Base64 Encoder/Decoder. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Robert Harder (rob@iharder.net) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 966 $, $Date: 2009-03-04 02:15:14 -0800 (Wed, 04 Mar 2009) $ */ public class Base64 { /** Maximum line length (76) of Base64 output. */ private static final int MAX_LINE_LENGTH = 76; /** The equals sign (=) as a byte. */ private static final byte EQUALS_SIGN = (byte) '='; /** The new line character (\n) as a byte. */ private static final byte NEW_LINE = (byte) '\n'; private static final byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding private static final byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding private static final byte[] alphabet(Base64Dialect dialect) { if (dialect == null) { throw new NullPointerException("dialect"); } return dialect.alphabet; } private static final byte[] decodabet(Base64Dialect dialect) { if (dialect == null) { throw new NullPointerException("dialect"); } return dialect.decodabet; } private static final boolean breakLines(Base64Dialect dialect) { if (dialect == null) { throw new NullPointerException("dialect"); } return dialect.breakLinesByDefault; } public static ChannelBuffer encode(ChannelBuffer src) { return encode(src, Base64Dialect.STANDARD); } public static ChannelBuffer encode(ChannelBuffer src, Base64Dialect dialect) { return encode(src, breakLines(dialect), dialect); } public static ChannelBuffer encode( ChannelBuffer src, ChannelBufferFactory bufferFactory) { return encode(src, Base64Dialect.STANDARD, bufferFactory); } public static ChannelBuffer encode( ChannelBuffer src, Base64Dialect dialect, ChannelBufferFactory bufferFactory) { return encode(src, breakLines(dialect), dialect, bufferFactory); } public static ChannelBuffer encode(ChannelBuffer src, boolean breakLines) { return encode(src, breakLines, Base64Dialect.STANDARD); } public static ChannelBuffer encode( ChannelBuffer src, boolean breakLines, Base64Dialect dialect) { return encode(src, breakLines, dialect, HeapChannelBufferFactory.getInstance()); } public static ChannelBuffer encode( ChannelBuffer src, boolean breakLines, ChannelBufferFactory bufferFactory) { return encode(src, breakLines, Base64Dialect.STANDARD, bufferFactory); } public static ChannelBuffer encode( ChannelBuffer src, boolean breakLines, Base64Dialect dialect, ChannelBufferFactory bufferFactory) { if (src == null) { throw new NullPointerException("src"); } ChannelBuffer dest = encode( src, src.readerIndex(), src.readableBytes(), breakLines, dialect, bufferFactory); src.readerIndex(src.writerIndex()); return dest; } public static ChannelBuffer encode(ChannelBuffer src, int off, int len) { return encode(src, off, len, Base64Dialect.STANDARD); } public static ChannelBuffer encode(ChannelBuffer src, int off, int len, Base64Dialect dialect) { return encode(src, off, len, breakLines(dialect), dialect); } public static ChannelBuffer encode(ChannelBuffer src, int off, int len, ChannelBufferFactory bufferFactory) { return encode(src, off, len, Base64Dialect.STANDARD, bufferFactory); } public static ChannelBuffer encode(ChannelBuffer src, int off, int len, Base64Dialect dialect, ChannelBufferFactory bufferFactory) { return encode(src, off, len, breakLines(dialect), dialect, bufferFactory); } public static ChannelBuffer encode( ChannelBuffer src, int off, int len, boolean breakLines) { return encode(src, off, len, breakLines, Base64Dialect.STANDARD); } public static ChannelBuffer encode( ChannelBuffer src, int off, int len, boolean breakLines, Base64Dialect dialect) { return encode(src, off, len, breakLines, dialect, HeapChannelBufferFactory.getInstance()); } public static ChannelBuffer encode( ChannelBuffer src, int off, int len, boolean breakLines, ChannelBufferFactory bufferFactory) { return encode(src, off, len, breakLines, Base64Dialect.STANDARD, bufferFactory); } public static ChannelBuffer encode( ChannelBuffer src, int off, int len, boolean breakLines, Base64Dialect dialect, ChannelBufferFactory bufferFactory) { if (src == null) { throw new NullPointerException("src"); } if (dialect == null) { throw new NullPointerException("dialect"); } if (bufferFactory == null) { throw new NullPointerException("bufferFactory"); } int len43 = len * 4 / 3; ChannelBuffer dest = bufferFactory.getBuffer( len43 + (len % 3 > 0? 4 : 0) + // Account for padding (breakLines? len43 / MAX_LINE_LENGTH : 0)); // New lines int d = 0; int e = 0; int len2 = len - 2; int lineLength = 0; for (; d < len2; d += 3, e += 4) { encode3to4(src, d + off, 3, dest, e, dialect); lineLength += 4; if (breakLines && lineLength == MAX_LINE_LENGTH) { dest.setByte(e + 4, NEW_LINE); e ++; lineLength = 0; } // end if: end of line } // end for: each piece of array if (d < len) { encode3to4(src, d + off, len - d, dest, e, dialect); e += 4; } // end if: some padding needed return dest.slice(0, e); } private static void encode3to4( ChannelBuffer src, int srcOffset, int numSigBytes, ChannelBuffer dest, int destOffset, Base64Dialect dialect) { byte[] ALPHABET = alphabet(dialect); // 1 2 3 // 01234567890123456789012345678901 Bit position // --------000000001111111122222222 Array position from threeBytes // --------| || || || | Six bit groups to index ALPHABET // >>18 >>12 >> 6 >> 0 Right shift necessary // 0x3f 0x3f 0x3f Additional AND // Create buffer with zero-padding if there are only one or two // significant bytes passed in the array. // We have to shift left 24 in order to flush out the 1's that appear // when Java treats a value as negative that is cast from a byte to an int. int inBuff = (numSigBytes > 0? src.getByte(srcOffset ) << 24 >>> 8 : 0) | (numSigBytes > 1? src.getByte(srcOffset + 1) << 24 >>> 16 : 0) | (numSigBytes > 2? src.getByte(srcOffset + 2) << 24 >>> 24 : 0); switch (numSigBytes) { case 3: dest.setByte(destOffset , ALPHABET[inBuff >>> 18 ]); dest.setByte(destOffset + 1, ALPHABET[inBuff >>> 12 & 0x3f]); dest.setByte(destOffset + 2, ALPHABET[inBuff >>> 6 & 0x3f]); dest.setByte(destOffset + 3, ALPHABET[inBuff & 0x3f]); break; case 2: dest.setByte(destOffset , ALPHABET[inBuff >>> 18 ]); dest.setByte(destOffset + 1, ALPHABET[inBuff >>> 12 & 0x3f]); dest.setByte(destOffset + 2, ALPHABET[inBuff >>> 6 & 0x3f]); dest.setByte(destOffset + 3, EQUALS_SIGN); break; case 1: dest.setByte(destOffset , ALPHABET[inBuff >>> 18 ]); dest.setByte(destOffset + 1, ALPHABET[inBuff >>> 12 & 0x3f]); dest.setByte(destOffset + 2, EQUALS_SIGN); dest.setByte(destOffset + 3, EQUALS_SIGN); break; } } public static ChannelBuffer decode(ChannelBuffer src) { return decode(src, Base64Dialect.STANDARD); } public static ChannelBuffer decode(ChannelBuffer src, Base64Dialect dialect) { return decode(src, dialect, HeapChannelBufferFactory.getInstance()); } public static ChannelBuffer decode(ChannelBuffer src, ChannelBufferFactory bufferFactory) { return decode(src, Base64Dialect.STANDARD, bufferFactory); } public static ChannelBuffer decode(ChannelBuffer src, Base64Dialect dialect, ChannelBufferFactory bufferFactory) { if (src == null) { throw new NullPointerException("src"); } ChannelBuffer dest = decode(src, src.readerIndex(), src.readableBytes(), dialect, bufferFactory); src.readerIndex(src.writerIndex()); return dest; } public static ChannelBuffer decode( ChannelBuffer src, int off, int len) { return decode(src, off, len, Base64Dialect.STANDARD); } public static ChannelBuffer decode( ChannelBuffer src, int off, int len, Base64Dialect dialect) { return decode(src, off, len, dialect, HeapChannelBufferFactory.getInstance()); } public static ChannelBuffer decode( ChannelBuffer src, int off, int len, ChannelBufferFactory bufferFactory) { return decode(src, off, len, Base64Dialect.STANDARD, bufferFactory); } public static ChannelBuffer decode( ChannelBuffer src, int off, int len, Base64Dialect dialect, ChannelBufferFactory bufferFactory) { if (src == null) { throw new NullPointerException("src"); } if (dialect == null) { throw new NullPointerException("dialect"); } if (bufferFactory == null) { throw new NullPointerException("bufferFactory"); } byte[] DECODABET = decodabet(dialect); int len34 = len * 3 / 4; ChannelBuffer dest = bufferFactory.getBuffer(len34); // Upper limit on size of output int outBuffPosn = 0; byte[] b4 = new byte[4]; int b4Posn = 0; int i = 0; byte sbiCrop = 0; byte sbiDecode = 0; for (i = off; i < off + len; i ++) { sbiCrop = (byte) (src.getByte(i) & 0x7f); // Only the low seven bits sbiDecode = DECODABET[sbiCrop]; if (sbiDecode >= WHITE_SPACE_ENC) { // White space, Equals sign or better if (sbiDecode >= EQUALS_SIGN_ENC) { b4[b4Posn ++] = sbiCrop; if (b4Posn > 3) { outBuffPosn += decode4to3( b4, 0, dest, outBuffPosn, dialect); b4Posn = 0; // If that was the equals sign, break out of 'for' loop if (sbiCrop == EQUALS_SIGN) { break; } } // end if: quartet built } // end if: equals sign or better } // end if: white space, equals sign or better else { throw new IllegalArgumentException( "bad Base64 input character at " + i + ": " + src.getUnsignedByte(i) + " (decimal)"); } } return dest.slice(0, outBuffPosn); } private static int decode4to3( byte[] src, int srcOffset, ChannelBuffer dest, int destOffset, Base64Dialect dialect) { byte[] DECODABET = decodabet(dialect); // Example: Dk== if (src[srcOffset + 2] == EQUALS_SIGN) { int outBuff = (DECODABET[src[srcOffset ]] & 0xFF) << 18 | (DECODABET[src[srcOffset + 1]] & 0xFF) << 12; dest.setByte(destOffset, (byte) (outBuff >>> 16)); return 1; } // Example: DkL= else if (src[srcOffset + 3] == EQUALS_SIGN) { int outBuff = (DECODABET[src[srcOffset ]] & 0xFF) << 18 | (DECODABET[src[srcOffset + 1]] & 0xFF) << 12 | (DECODABET[src[srcOffset + 2]] & 0xFF) << 6; dest.setByte(destOffset , (byte) (outBuff >>> 16)); dest.setByte(destOffset + 1, (byte) (outBuff >>> 8)); return 2; } // Example: DkLE else { int outBuff; try { outBuff = (DECODABET[src[srcOffset ]] & 0xFF) << 18 | (DECODABET[src[srcOffset + 1]] & 0xFF) << 12 | (DECODABET[src[srcOffset + 2]] & 0xFF) << 6 | DECODABET[src[srcOffset + 3]] & 0xFF; } catch (IndexOutOfBoundsException e) { throw new IllegalArgumentException("not encoded in Base64"); } dest.setByte(destOffset , (byte) (outBuff >> 16)); dest.setByte(destOffset + 1, (byte) (outBuff >> 8)); dest.setByte(destOffset + 2, (byte) outBuff); return 3; } } private Base64() { // Unused } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/base64/package-info.java0000644000175000017500000000246611122137536031547 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Encoder and decoder which transform a * Base64-encoded * {@link java.lang.String} or {@link org.jboss.netty.buffer.ChannelBuffer} * into a decoded {@link org.jboss.netty.buffer.ChannelBuffer} and vice versa. */ package org.jboss.netty.handler.codec.base64;libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/handler/codec/base64/Base64Decoder.java0000644000175000017500000000646511144744707031550 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.handler.codec.base64; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.frame.FrameDecoder; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; /** * Decodes a Base64-encoded {@link ChannelBuffer} or US-ASCII {@link String} * into a {@link ChannelBuffer}. Please note that this decoder must be used * with a proper {@link FrameDecoder} such as {@link DelimiterBasedFrameDecoder} * if you are using a stream-based transport such as TCP/IP. A typical decoder * setup for TCP/IP would be: *

 * {@link ChannelPipeline} pipeline = ...;
 *
 * // Decoders
 * pipeline.addLast("frameDecoder", new {@link DelimiterBasedFrameDecoder}(80, {@link Delimiters#nulDelimiter()}));
 * pipeline.addLast("base64Decoder", new {@link Base64Decoder}());
 *
 * // Encoder
 * pipeline.addLast("base64Encoder", new {@link Base64Encoder}());
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 855 $, $Date: 2009-02-11 23:03:35 -0800 (Wed, 11 Feb 2009) $ */ @ChannelPipelineCoverage("all") public class Base64Decoder extends OneToOneDecoder { private final Base64Dialect dialect; public Base64Decoder() { this(Base64Dialect.STANDARD); } public Base64Decoder(Base64Dialect dialect) { if (dialect == null) { throw new NullPointerException("dialect"); } this.dialect = dialect; } @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (msg instanceof String) { msg = ChannelBuffers.wrappedBuffer( ((String) msg).getBytes("ASCII")); } else if (!(msg instanceof ChannelBuffer)) { return msg; } ChannelBuffer src = (ChannelBuffer) msg; return Base64.decode( src, src.readerIndex(), src.readableBytes(), dialect); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/0000755000175000017500000000000011316313127024551 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/spring/0000755000175000017500000000000011316313126026052 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/spring/package-info.java0000644000175000017500000000222011216403720031234 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Spring framework integration. * * @apiviz.exclude */ package org.jboss.netty.container.spring; ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/spring/NettyResourceFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/spring/NettyResourceFactory.jav0000644000175000017500000000505711216402444032727 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.spring; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.logging.CommonsLoggerFactory; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.util.internal.ExecutorUtil; import org.jboss.netty.util.internal.UnterminatableExecutor; import org.springframework.beans.factory.DisposableBean; import org.springframework.beans.factory.InitializingBean; /** * A factory bean that provides the common resources required by * {@link ChannelFactory} implementations. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1424 $, $Date: 2009-06-18 02:13:08 -0700 (Thu, 18 Jun 2009) $ */ public class NettyResourceFactory implements InitializingBean, DisposableBean { private Executor executor; private Executor unterminatableExecutor; public synchronized void afterPropertiesSet() { if (executor != null) { return; } executor = Executors.newCachedThreadPool(); unterminatableExecutor = new UnterminatableExecutor(executor); InternalLoggerFactory.setDefaultFactory(new CommonsLoggerFactory()); } public synchronized void destroy() { if (executor != null) { ExecutorUtil.terminate(executor); } executor = null; unterminatableExecutor = null; } public synchronized Executor getChannelFactoryExecutor() { return unterminatableExecutor; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/0000755000175000017500000000000011316313127025645 5ustar deckerdecker././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/NioServerSocketChannelFactoryProvider.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/NioServerSocketChannelFac0000644000175000017500000000401211216402210032544 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import com.google.inject.Inject; import com.google.inject.Provider; /** * A {@link Provider} that creates a new {@link NioServerSocketChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1423 $, $Date: 2009-06-18 02:10:32 -0700 (Thu, 18 Jun 2009) $ */ public class NioServerSocketChannelFactoryProvider extends AbstractChannelFactoryProvider { /** * Creates a new provider with the {@code executor} injected via the * {@link ChannelFactoryResource} annotation. */ @Inject public NioServerSocketChannelFactoryProvider( @ChannelFactoryResource Executor executor) { super(executor); } public NioServerSocketChannelFactory get() { return new NioServerSocketChannelFactory(executor, executor); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/ChannelFactoryResource.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/ChannelFactoryResource.ja0000644000175000017500000000351411216402065032573 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.lang.annotation.Documented; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; import org.jboss.netty.channel.ChannelFactory; import com.google.inject.BindingAnnotation; /** * A parameter or a field annotated with this annotation will be injected with * the resource required to run a {@link ChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1422 $, $Date: 2009-06-18 02:09:09 -0700 (Thu, 18 Jun 2009) $ */ @Retention(RetentionPolicy.RUNTIME) @Target({ElementType.FIELD, ElementType.PARAMETER}) @BindingAnnotation @Documented public @interface ChannelFactoryResource { // No value required } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/OioServerSocketChannelFactoryProvider.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/OioServerSocketChannelFac0000644000175000017500000000401211216402210032545 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; import com.google.inject.Inject; import com.google.inject.Provider; /** * A {@link Provider} that creates a new {@link OioServerSocketChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1423 $, $Date: 2009-06-18 02:10:32 -0700 (Thu, 18 Jun 2009) $ */ public class OioServerSocketChannelFactoryProvider extends AbstractChannelFactoryProvider { /** * Creates a new provider with the {@code executor} injected via the * {@link ChannelFactoryResource} annotation. */ @Inject public OioServerSocketChannelFactoryProvider( @ChannelFactoryResource Executor executor) { super(executor); } public OioServerSocketChannelFactory get() { return new OioServerSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/NettyModule.java0000644000175000017500000001221411216402065030760 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory; import org.jboss.netty.channel.local.LocalClientChannelFactory; import org.jboss.netty.channel.local.LocalServerChannelFactory; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.ServerSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; import org.jboss.netty.util.internal.ExecutorUtil; import org.jboss.netty.util.internal.UnterminatableExecutor; import com.google.inject.AbstractModule; import com.google.inject.Module; import com.google.inject.Scopes; /** * A Guice {@link Module} that defines the bindings for all known * {@link ChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1422 $, $Date: 2009-06-18 02:09:09 -0700 (Thu, 18 Jun 2009) $ */ public class NettyModule extends AbstractModule { private final ExecutorService executor = Executors.newCachedThreadPool(); /** * Releases all resources created by this module. */ public void destroy() { ExecutorUtil.terminate(executor); } @Override protected void configure() { if (executor.isShutdown()) { throw new IllegalStateException( "Executor has been shut down already."); } Executor executor = new UnterminatableExecutor(this.executor); bind(Executor.class). annotatedWith(ChannelFactoryResource.class). toInstance(executor); bind(ClientSocketChannelFactory.class). toProvider(NioClientSocketChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(ServerSocketChannelFactory.class). toProvider(NioServerSocketChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(DatagramChannelFactory.class). toProvider(OioDatagramChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(NioClientSocketChannelFactory.class). toProvider(NioClientSocketChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(NioServerSocketChannelFactory.class). toProvider(NioServerSocketChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(NioDatagramChannelFactory.class). toProvider(NioDatagramChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(OioClientSocketChannelFactory.class). toProvider(OioClientSocketChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(OioServerSocketChannelFactory.class). toProvider(OioServerSocketChannelFactoryProvider.class). in(Scopes.SINGLETON); bind(OioDatagramChannelFactory.class). toProvider(OioDatagramChannelFactoryProvider.class). in(Scopes.SINGLETON); // Local transports bind(LocalClientChannelFactory.class). to(DefaultLocalClientChannelFactory.class). in(Scopes.SINGLETON); bind(LocalServerChannelFactory.class). to(DefaultLocalServerChannelFactory.class). in(Scopes.SINGLETON); bind(DefaultLocalClientChannelFactory.class). to(DefaultLocalClientChannelFactory.class). in(Scopes.SINGLETON); bind(DefaultLocalServerChannelFactory.class). to(DefaultLocalServerChannelFactory.class). in(Scopes.SINGLETON); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/NioClientSocketChannelFactoryProvider.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/NioClientSocketChannelFac0000644000175000017500000000401211216402210032514 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import com.google.inject.Inject; import com.google.inject.Provider; /** * A {@link Provider} that creates a new {@link NioClientSocketChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1423 $, $Date: 2009-06-18 02:10:32 -0700 (Thu, 18 Jun 2009) $ */ public class NioClientSocketChannelFactoryProvider extends AbstractChannelFactoryProvider { /** * Creates a new provider with the {@code executor} injected via the * {@link ChannelFactoryResource} annotation. */ @Inject public NioClientSocketChannelFactoryProvider( @ChannelFactoryResource Executor executor) { super(executor); } public NioClientSocketChannelFactory get() { return new NioClientSocketChannelFactory(executor, executor); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/package-info.java0000644000175000017500000000222211216403720031030 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * Google Guice integration. * * @apiviz.exclude */ package org.jboss.netty.container.guice; ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/OioDatagramChannelFactoryProvider.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/OioDatagramChannelFactory0000644000175000017500000000374411216402210032577 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import com.google.inject.Inject; import com.google.inject.Provider; /** * A {@link Provider} that creates a new {@link OioDatagramChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1423 $, $Date: 2009-06-18 02:10:32 -0700 (Thu, 18 Jun 2009) $ */ public class OioDatagramChannelFactoryProvider extends AbstractChannelFactoryProvider { /** * Creates a new provider with the {@code executor} injected via the * {@link ChannelFactoryResource} annotation. */ @Inject public OioDatagramChannelFactoryProvider( @ChannelFactoryResource Executor executor) { super(executor); } public OioDatagramChannelFactory get() { return new OioDatagramChannelFactory(executor); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/OioClientSocketChannelFactoryProvider.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/OioClientSocketChannelFac0000644000175000017500000000400011216402210032512 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import com.google.inject.Inject; import com.google.inject.Provider; /** * A {@link Provider} that creates a new {@link OioClientSocketChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1423 $, $Date: 2009-06-18 02:10:32 -0700 (Thu, 18 Jun 2009) $ */ public class OioClientSocketChannelFactoryProvider extends AbstractChannelFactoryProvider { /** * Creates a new provider with the {@code executor} injected via the * {@link ChannelFactoryResource} annotation. */ @Inject public OioClientSocketChannelFactoryProvider( @ChannelFactoryResource Executor executor) { super(executor); } public OioClientSocketChannelFactory get() { return new OioClientSocketChannelFactory(executor); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/AbstractChannelFactoryProvider.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/AbstractChannelFactoryPro0000644000175000017500000000340511216402065032636 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import org.jboss.netty.channel.ChannelFactory; import com.google.inject.Provider; /** * A skeletal {@link Provider} implementation for a {@link ChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1422 $, $Date: 2009-06-18 02:09:09 -0700 (Thu, 18 Jun 2009) $ */ public abstract class AbstractChannelFactoryProvider implements Provider { protected final Executor executor; protected AbstractChannelFactoryProvider(Executor executor) { if (executor == null) { throw new NullPointerException("executor"); } this.executor = executor; } } ././@LongLink0000000000000000000000000000016200000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/NioDatagramChannelFactoryProvider.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/guice/NioDatagramChannelFactory0000644000175000017500000000374411216402210032576 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.guice; import java.util.concurrent.Executor; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import com.google.inject.Inject; import com.google.inject.Provider; /** * A {@link Provider} that creates a new {@link NioDatagramChannelFactory}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1423 $, $Date: 2009-06-18 02:10:32 -0700 (Thu, 18 Jun 2009) $ */ public class NioDatagramChannelFactoryProvider extends AbstractChannelFactoryProvider { /** * Creates a new provider with the {@code executor} injected via the * {@link ChannelFactoryResource} annotation. */ @Inject public NioDatagramChannelFactoryProvider( @ChannelFactoryResource Executor executor) { super(executor); } public NioDatagramChannelFactory get() { return new NioDatagramChannelFactory(executor); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/microcontainer/0000755000175000017500000000000011316313127027565 5ustar deckerdecker././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/microcontainer/package-info.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/microcontainer/package-info.jav0000644000175000017500000000223211216403720032610 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * JBoss Microcontainer integration. * * @apiviz.exclude */ package org.jboss.netty.container.microcontainer; ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/microcontainer/NettyResourceFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/microcontainer/NettyResourceFac0000644000175000017500000000472411216402444032744 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.microcontainer; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.logging.JBossLoggerFactory; import org.jboss.netty.util.internal.ExecutorUtil; import org.jboss.netty.util.internal.UnterminatableExecutor; /** * A factory bean that provides the common resources required by * {@link ChannelFactory} implementations. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1424 $, $Date: 2009-06-18 02:13:08 -0700 (Thu, 18 Jun 2009) $ */ public class NettyResourceFactory { private Executor executor; private Executor unterminatableExecutor; public synchronized void create() { if (executor != null) { return; } executor = Executors.newCachedThreadPool(); unterminatableExecutor = new UnterminatableExecutor(executor); } public void start() { InternalLoggerFactory.setDefaultFactory(new JBossLoggerFactory()); } public synchronized void stop() { if (executor != null) { ExecutorUtil.terminate(executor); } } public synchronized void destroy() { executor = null; unterminatableExecutor = null; } public synchronized Executor getChannelFactoryExecutor() { return unterminatableExecutor; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/osgi/0000755000175000017500000000000011316313126025511 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/osgi/NettyBundleActivator.java0000644000175000017500000001271011216402444032470 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.container.osgi; import java.util.ArrayList; import java.util.List; import java.util.Properties; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory; import org.jboss.netty.channel.local.LocalClientChannelFactory; import org.jboss.netty.channel.local.LocalServerChannelFactory; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.ServerSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioDatagramChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import org.jboss.netty.channel.socket.oio.OioServerSocketChannelFactory; import org.jboss.netty.logging.InternalLoggerFactory; import org.jboss.netty.logging.OsgiLoggerFactory; import org.jboss.netty.util.internal.ExecutorUtil; import org.osgi.framework.BundleActivator; import org.osgi.framework.BundleContext; import org.osgi.framework.ServiceRegistration; /** * An OSGi {@link BundleActivator} that configures logging and registered * all {@link ChannelFactory} implementations as OSGi services. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1424 $, $Date: 2009-06-18 02:13:08 -0700 (Thu, 18 Jun 2009) $ */ public class NettyBundleActivator implements BundleActivator { private final List registrations = new ArrayList(); private Executor executor; private OsgiLoggerFactory loggerFactory; public void start(BundleContext ctx) throws Exception { // Switch the internal logger to the OSGi LogService. loggerFactory = new OsgiLoggerFactory(ctx); InternalLoggerFactory.setDefaultFactory(loggerFactory); // Prepare the resources required for creating ChannelFactories. Executor executor = this.executor = Executors.newCachedThreadPool(); // The default transport is NIO. register(ctx, new NioClientSocketChannelFactory(executor, executor), ClientSocketChannelFactory.class); register(ctx, new NioServerSocketChannelFactory(executor, executor), ServerSocketChannelFactory.class); // ... except for the datagram transport. register(ctx, new OioDatagramChannelFactory(executor), DatagramChannelFactory.class); // Local transports register(ctx, new DefaultLocalClientChannelFactory(), LocalClientChannelFactory.class); register(ctx, new DefaultLocalServerChannelFactory(), LocalServerChannelFactory.class); // Miscellaneous transports register(ctx, new OioClientSocketChannelFactory(executor)); register(ctx, new OioServerSocketChannelFactory(executor, executor)); register(ctx, new NioDatagramChannelFactory(executor)); } public void stop(BundleContext ctx) throws Exception { unregisterAll(); if (executor != null) { ExecutorUtil.terminate(executor); executor = null; } if (loggerFactory != null) { InternalLoggerFactory.setDefaultFactory(loggerFactory.getFallback()); loggerFactory.destroy(); loggerFactory = null; } } private void register(BundleContext ctx, ChannelFactory factory, Class... factoryTypes) { Properties props = new Properties(); props.setProperty("category", "netty"); registrations.add(ctx.registerService(factory.getClass().getName(), factory, props)); for (Class t: factoryTypes) { registrations.add(ctx.registerService(t.getName(), factory, props)); } } private void unregisterAll() { List registrationsCopy = new ArrayList(registrations); registrations.clear(); for (ServiceRegistration r: registrationsCopy) { r.unregister(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/container/osgi/package-info.java0000644000175000017500000000220111216403720030672 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ /** * OSGi framework integration. * * @apiviz.exclude */ package org.jboss.netty.container.osgi; libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/0000755000175000017500000000000011316313144024221 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/0000755000175000017500000000000011316313142026163 5ustar deckerdecker././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialClientPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialClientPipeline0000644000175000017500000000407111050275327032650 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; /** * Creates a newly configured {@link ChannelPipeline} for a client-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class FactorialClientPipelineFactory implements ChannelPipelineFactory { private final int count; public FactorialClientPipelineFactory(int count) { this.count = count; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); // Add the number codec first, pipeline.addLast("decoder", new BigIntegerDecoder()); pipeline.addLast("encoder", new NumberEncoder()); // and then business logic. pipeline.addLast("handler", new FactorialClientHandler(count)); return pipeline; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialServerPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialServerPipeline0000644000175000017500000000405711050275327032704 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; /** * Creates a newly configured {@link ChannelPipeline} for a server-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ * */ public class FactorialServerPipelineFactory implements ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); // Add the number codec first, pipeline.addLast("decoder", new BigIntegerDecoder()); pipeline.addLast("encoder", new NumberEncoder()); // and then business logic. // Please note we create a handler for every new channel // because it has stateful properties. pipeline.addLast("handler", new FactorialServerHandler()); return pipeline; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialClient.java0000644000175000017500000000661511113751575032114 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; /** * Sends a sequence of integers to a {@link FactorialServer} to calculate * the factorial of the specified integer. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 536 $, $Date: 2008-11-28 03:18:21 -0800 (Fri, 28 Nov 2008) $ */ public class FactorialClient { public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length != 3) { System.err.println( "Usage: " + FactorialClient.class.getSimpleName() + " "); return; } // Parse options. String host = args[0]; int port = Integer.parseInt(args[1]); int count = Integer.parseInt(args[2]); if (count <= 0) { throw new IllegalArgumentException("count must be a positive integer."); } // Set up. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); bootstrap.setPipelineFactory(new FactorialClientPipelineFactory(count)); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); // Make a new connection. ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection is made successfully. Channel channel = connectFuture.awaitUninterruptibly().getChannel(); // Get the handler instance to retrieve the answer. FactorialClientHandler handler = (FactorialClientHandler) channel.getPipeline().getLast(); // Print out the answer. System.out.format( "Factorial of %,d is: %,d", count, handler.getFactorial()); // Shut down all thread pools to exit. factory.releaseExternalResources(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/BigIntegerDecoder.java0000644000175000017500000000471411050275327032350 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import java.math.BigInteger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.handler.codec.frame.FrameDecoder; /** * Decodes the binary representation of a {@link BigInteger} with 32-bit * integer length prefix into a Java {@link BigInteger} instance. For example, * { 0, 0, 0, 1, 42 } will be decoded into new BigInteger("42"). * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class BigIntegerDecoder extends FrameDecoder { @Override protected Object decode( ChannelHandlerContext ctx, Channel channel, ChannelBuffer buffer) throws Exception { // Wait until the length prefix is available. if (buffer.readableBytes() < 4) { return null; } int dataLength = buffer.getInt(buffer.readerIndex()); // Wait until the whole data is available. if (buffer.readableBytes() < dataLength + 4) { return null; } // Skip the length field because we know it already. buffer.skipBytes(4); // Convert the received data into a new BigInteger. byte[] decoded = new byte[dataLength]; buffer.readBytes(decoded); return new BigInteger(decoded); } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialProtocolException.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialProtocolExcept0000644000175000017500000000341311050275327032715 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; /** * Thrown when there was a protocol violation during communication. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class FactorialProtocolException extends Exception { private static final long serialVersionUID = -7045872169845421748L; public FactorialProtocolException() { super(); } public FactorialProtocolException(String message, Throwable cause) { super(message, cause); } public FactorialProtocolException(String message) { super(message); } public FactorialProtocolException(Throwable cause) { super(cause); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialClientHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialClientHandler.0000644000175000017500000001132111172030314032520 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import java.math.BigInteger; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handler for a client-side channel. Please note that this handler's * {@link ChannelPipelineCoverage} annotation value is "one". It means * this handler maintains some stateful information which is specific to * a certain channel. Therefore, an instance of this handler can * cover only one ChannelPipeline and Channel pair. You have to create * a new handler instance whenever you create a new channel and insert * this handler to avoid a race condition. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("one") // <-- HERE public class FactorialClientHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( FactorialClientHandler.class.getName()); // Stateful properties private int i = 1; private int receivedMessages = 0; private final int count; final BlockingQueue answer = new LinkedBlockingQueue(); public FactorialClientHandler(int count) { this.count = count; } public BigInteger getFactorial() { for (;;) { try { return answer.take(); } catch (InterruptedException e) { // Ignore. } } } @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { sendNumbers(e); } @Override public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) { sendNumbers(e); } @Override public void messageReceived( ChannelHandlerContext ctx, final MessageEvent e) { receivedMessages ++; if (receivedMessages == count) { // Offer the answer after closing the connection. e.getChannel().close().addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) { boolean offered = answer.offer((BigInteger) e.getMessage()); assert offered; } }); } } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } private void sendNumbers(ChannelStateEvent e) { Channel channel = e.getChannel(); while (channel.isWritable()) { if (i <= count) { channel.write(Integer.valueOf(i)); i ++; } else { break; } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialServer.java0000644000175000017500000000440111050275327032127 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * Receives a sequence of integers from a {@link FactorialClient} to calculate * the factorial of the specified integer. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class FactorialServer { public static void main(String[] args) throws Exception { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); bootstrap.setPipelineFactory(new FactorialServerPipelineFactory()); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/NumberEncoder.java0000644000175000017500000000521611172030314031557 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import java.math.BigInteger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.handler.codec.oneone.OneToOneEncoder; /** * Encodes a {@link Number} into the binary representation with a 32-bit length * prefix. For example, 42 will be encoded to { 0, 0, 0, 1, 42 }. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ * */ @ChannelPipelineCoverage("all") public class NumberEncoder extends OneToOneEncoder { @Override protected Object encode( ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { if (!(msg instanceof Number)) { // Ignore what this encoder can't encode. return msg; } // Convert to a BigInteger first for easier implementation. BigInteger v; if (msg instanceof BigInteger) { v = (BigInteger) msg; } else { v = new BigInteger(String.valueOf(msg)); } // Convert the number into a byte array. byte[] data = v.toByteArray(); int dataLength = data.length; // Construct a message with a length header. ChannelBuffer buf = ChannelBuffers.dynamicBuffer(); buf.writeInt(dataLength); buf.writeBytes(data); // Return the constructed message. return buf; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialServerHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/factorial/FactorialServerHandler.0000644000175000017500000000751511172030314032562 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.factorial; import java.math.BigInteger; import java.util.Formatter; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handler for a server-side channel. Please note that this handler's * {@link ChannelPipelineCoverage} annotation value is "one". It means * this handler maintains some stateful information which is specific to * a certain channel. Therefore, an instance of this handler can * cover only one ChannelPipeline and Channel pair. You have to create * a new handler instance whenever you create a new channel and insert * this handler to avoid a race condition. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("one") // <-- HERE public class FactorialServerHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( FactorialServerHandler.class.getName()); // Stateful properties. private int lastMultiplier = 1; private BigInteger factorial = new BigInteger(new byte[] { 1 }); @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { // Calculate the cumulative factorial and send it to the client. BigInteger number; if (e.getMessage() instanceof BigInteger) { number = (BigInteger) e.getMessage(); } else { number = new BigInteger(e.getMessage().toString()); } lastMultiplier = number.intValue(); factorial = factorial.multiply(number); e.getChannel().write(factorial); } @Override public void channelDisconnected(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { logger.info(new Formatter().format( "Factorial of %,d is: %,d", lastMultiplier, factorial).toString()); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/0000755000175000017500000000000011316313143026346 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatClient.java0000644000175000017500000001035211211705313032375 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.example.telnet.TelnetClient; /** * Simple SSL chat client modified from {@link TelnetClient}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1327 $, $Date: 2009-06-04 01:50:19 -0700 (Thu, 04 Jun 2009) $ * */ public class SecureChatClient { public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length != 2) { System.err.println( "Usage: " + SecureChatClient.class.getSimpleName() + " "); return; } // Parse options. String host = args[0]; int port = Integer.parseInt(args[1]); // Configure the client. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); SecureChatClientHandler handler = new SecureChatClientHandler(); bootstrap.setPipelineFactory(new SecureChatPipelineFactory(handler)); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.awaitUninterruptibly().getChannel(); if (!future.isSuccess()) { future.getCause().printStackTrace(); factory.releaseExternalResources(); return; } // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = channel.write(line + '\n'); // If user typed the 'bye' command, wait until the server closes // the connection. if (line.toLowerCase().equals("bye")) { channel.getCloseFuture().awaitUninterruptibly(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.awaitUninterruptibly(); } // Close the connection. Make sure the close operation ends because // all I/O operations are asynchronous in Netty. channel.close().awaitUninterruptibly(); // Shut down all thread pools to exit. factory.releaseExternalResources(); } } ././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatSslContextFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatSslContextFa0000644000175000017500000000704111107226261032621 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import java.security.KeyStore; import java.security.Security; import javax.net.ssl.KeyManagerFactory; import javax.net.ssl.SSLContext; /** * Creates a bogus {@link SSLContext}. A client-side context created by this * factory accepts any certificate even if it is invalid. A server-side context * created by this factory sends a bogus certificate defined in {@link SecureChatKeyStore}. * * You will have to create your context differently in a real world application. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 472 $, $Date: 2008-11-13 23:45:53 -0800 (Thu, 13 Nov 2008) $ */ public class SecureChatSslContextFactory { private static final String PROTOCOL = "TLS"; private static final SSLContext SERVER_CONTEXT; private static final SSLContext CLIENT_CONTEXT; static { String algorithm = Security.getProperty("ssl.KeyManagerFactory.algorithm"); if (algorithm == null) { algorithm = "SunX509"; } SSLContext serverContext = null; SSLContext clientContext = null; try { KeyStore ks = KeyStore.getInstance("JKS"); ks.load(SecureChatKeyStore.asInputStream(), SecureChatKeyStore.getKeyStorePassword()); // Set up key manager factory to use our key store KeyManagerFactory kmf = KeyManagerFactory.getInstance(algorithm); kmf.init(ks, SecureChatKeyStore.getCertificatePassword()); // Initialize the SSLContext to work with our key managers. serverContext = SSLContext.getInstance(PROTOCOL); serverContext.init( kmf.getKeyManagers(), SecureChatTrustManagerFactory.getTrustManagers(), null); } catch (Exception e) { throw new Error( "Failed to initialize the server-side SSLContext", e); } try { clientContext = SSLContext.getInstance(PROTOCOL); clientContext.init( null, SecureChatTrustManagerFactory.getTrustManagers(), null); } catch (Exception e) { throw new Error( "Failed to initialize the client-side SSLContext", e); } SERVER_CONTEXT = serverContext; CLIENT_CONTEXT = clientContext; } public static SSLContext getServerContext() { return SERVER_CONTEXT; } public static SSLContext getClientContext() { return CLIENT_CONTEXT; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatPipelineFact0000644000175000017500000000643411050275327032620 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import static org.jboss.netty.channel.Channels.*; import javax.net.ssl.SSLEngine; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; import org.jboss.netty.handler.ssl.SslHandler; /** * Creates a newly configured {@link ChannelPipeline} for a new channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ * */ public class SecureChatPipelineFactory implements ChannelPipelineFactory { private final ChannelHandler handler; public SecureChatPipelineFactory(ChannelHandler handler) { this.handler = handler; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline pipeline = pipeline(); // Add SSL handler first to encrypt and decrypt everything. // In this example, we use a bogus certificate in the server side // and accept any invalid certificates in the client side. // You will need something more complicated to identify both // and server in the real world. SSLEngine engine; if (handler instanceof SecureChatClientHandler) { engine = SecureChatSslContextFactory.getClientContext().createSSLEngine(); engine.setUseClientMode(true); } else { engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); engine.setUseClientMode(false); } pipeline.addLast("ssl", new SslHandler(engine)); // On top of the SSL handler, add the text line codec. pipeline.addLast("framer", new DelimiterBasedFrameDecoder( 8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); // and then business logic. pipeline.addLast("handler", handler); return pipeline; } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatTrustManagerFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatTrustManager0000644000175000017500000000571211107226261032663 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import java.security.InvalidAlgorithmParameterException; import java.security.KeyStore; import java.security.KeyStoreException; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import javax.net.ssl.ManagerFactoryParameters; import javax.net.ssl.TrustManager; import javax.net.ssl.TrustManagerFactorySpi; import javax.net.ssl.X509TrustManager; /** * Bogus {@link TrustManagerFactorySpi} which accepts any certificate * even if it is invalid. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 472 $, $Date: 2008-11-13 23:45:53 -0800 (Thu, 13 Nov 2008) $ */ public class SecureChatTrustManagerFactory extends TrustManagerFactorySpi { private static final TrustManager DUMMY_TRUST_MANAGER = new X509TrustManager() { public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } public void checkClientTrusted( X509Certificate[] arg0, String arg1) throws CertificateException { // Always trust - it is an example. // You should do something in the real world. } public void checkServerTrusted( X509Certificate[] arg0, String arg1) throws CertificateException { // Always trust - it is an example. // You should do something in the real world. } }; public static TrustManager[] getTrustManagers() { return new TrustManager[] { DUMMY_TRUST_MANAGER }; } @Override protected TrustManager[] engineGetTrustManagers() { return getTrustManagers(); } @Override protected void engineInit(KeyStore keystore) throws KeyStoreException { // Unused } @Override protected void engineInit(ManagerFactoryParameters managerFactoryParameters) throws InvalidAlgorithmParameterException { // Unused } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatKeyStore.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatKeyStore.jav0000644000175000017500000004010511050275327032572 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import java.io.ByteArrayInputStream; import java.io.InputStream; /** * A bogus key store which provides all the required information to * create an example SSL connection. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class SecureChatKeyStore { private static final short[] DATA = new short[] { 0xfe, 0xed, 0xfe, 0xed, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x02, 0x00, 0x00, 0x00, 0x01, 0x00, 0x07, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x00, 0x00, 0x01, 0x1a, 0x9f, 0x57, 0xa5, 0x27, 0x00, 0x00, 0x01, 0x9a, 0x30, 0x82, 0x01, 0x96, 0x30, 0x0e, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x2a, 0x02, 0x11, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x01, 0x82, 0x48, 0x6d, 0xcf, 0x16, 0xb5, 0x50, 0x95, 0x36, 0xbf, 0x47, 0x27, 0x50, 0x58, 0x0d, 0xa2, 0x52, 0x7e, 0x25, 0xab, 0x14, 0x1a, 0x26, 0x5e, 0x2d, 0x8a, 0x23, 0x90, 0x60, 0x7f, 0x12, 0x20, 0x56, 0xd1, 0x43, 0xa2, 0x6b, 0x47, 0x5d, 0xed, 0x9d, 0xd4, 0xe5, 0x83, 0x28, 0x89, 0xc2, 0x16, 0x4c, 0x76, 0x06, 0xad, 0x8e, 0x8c, 0x29, 0x1a, 0x9b, 0x0f, 0xdd, 0x60, 0x4b, 0xb4, 0x62, 0x82, 0x9e, 0x4a, 0x63, 0x83, 0x2e, 0xd2, 0x43, 0x78, 0xc2, 0x32, 0x1f, 0x60, 0xa9, 0x8a, 0x7f, 0x0f, 0x7c, 0xa6, 0x1d, 0xe6, 0x92, 0x9e, 0x52, 0xc7, 0x7d, 0xbb, 0x35, 0x3b, 0xaa, 0x89, 0x73, 0x4c, 0xfb, 0x99, 0x54, 0x97, 0x99, 0x28, 0x6e, 0x66, 0x5b, 0xf7, 0x9b, 0x7e, 0x6d, 0x8a, 0x2f, 0xfa, 0xc3, 0x1e, 0x71, 0xb9, 0xbd, 0x8f, 0xc5, 0x63, 0x25, 0x31, 0x20, 0x02, 0xff, 0x02, 0xf0, 0xc9, 0x2c, 0xdd, 0x3a, 0x10, 0x30, 0xab, 0xe5, 0xad, 0x3d, 0x1a, 0x82, 0x77, 0x46, 0xed, 0x03, 0x38, 0xa4, 0x73, 0x6d, 0x36, 0x36, 0x33, 0x70, 0xb2, 0x63, 0x20, 0xca, 0x03, 0xbf, 0x5a, 0xf4, 0x7c, 0x35, 0xf0, 0x63, 0x1a, 0x12, 0x33, 0x12, 0x58, 0xd9, 0xa2, 0x63, 0x6b, 0x63, 0x82, 0x41, 0x65, 0x70, 0x37, 0x4b, 0x99, 0x04, 0x9f, 0xdd, 0x5e, 0x07, 0x01, 0x95, 0x9f, 0x36, 0xe8, 0xc3, 0x66, 0x2a, 0x21, 0x69, 0x68, 0x40, 0xe6, 0xbc, 0xbb, 0x85, 0x81, 0x21, 0x13, 0xe6, 0xa4, 0xcf, 0xd3, 0x67, 0xe3, 0xfd, 0x75, 0xf0, 0xdf, 0x83, 0xe0, 0xc5, 0x36, 0x09, 0xac, 0x1b, 0xd4, 0xf7, 0x2a, 0x23, 0x57, 0x1c, 0x5c, 0x0f, 0xf4, 0xcf, 0xa2, 0xcf, 0xf5, 0xbd, 0x9c, 0x69, 0x98, 0x78, 0x3a, 0x25, 0xe4, 0xfd, 0x85, 0x11, 0xcc, 0x7d, 0xef, 0xeb, 0x74, 0x60, 0xb1, 0xb7, 0xfb, 0x1f, 0x0e, 0x62, 0xff, 0xfe, 0x09, 0x0a, 0xc3, 0x80, 0x2f, 0x10, 0x49, 0x89, 0x78, 0xd2, 0x08, 0xfa, 0x89, 0x22, 0x45, 0x91, 0x21, 0xbc, 0x90, 0x3e, 0xad, 0xb3, 0x0a, 0xb4, 0x0e, 0x1c, 0xa1, 0x93, 0x92, 0xd8, 0x72, 0x07, 0x54, 0x60, 0xe7, 0x91, 0xfc, 0xd9, 0x3c, 0xe1, 0x6f, 0x08, 0xe4, 0x56, 0xf6, 0x0b, 0xb0, 0x3c, 0x39, 0x8a, 0x2d, 0x48, 0x44, 0x28, 0x13, 0xca, 0xe9, 0xf7, 0xa3, 0xb6, 0x8a, 0x5f, 0x31, 0xa9, 0x72, 0xf2, 0xde, 0x96, 0xf2, 0xb1, 0x53, 0xb1, 0x3e, 0x24, 0x57, 0xfd, 0x18, 0x45, 0x1f, 0xc5, 0x33, 0x1b, 0xa4, 0xe8, 0x21, 0xfa, 0x0e, 0xb2, 0xb9, 0xcb, 0xc7, 0x07, 0x41, 0xdd, 0x2f, 0xb6, 0x6a, 0x23, 0x18, 0xed, 0xc1, 0xef, 0xe2, 0x4b, 0xec, 0xc9, 0xba, 0xfb, 0x46, 0x43, 0x90, 0xd7, 0xb5, 0x68, 0x28, 0x31, 0x2b, 0x8d, 0xa8, 0x51, 0x63, 0xf7, 0x53, 0x99, 0x19, 0x68, 0x85, 0x66, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x58, 0x2e, 0x35, 0x30, 0x39, 0x00, 0x00, 0x02, 0x3a, 0x30, 0x82, 0x02, 0x36, 0x30, 0x82, 0x01, 0xe0, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x04, 0x48, 0x59, 0xf1, 0x92, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x81, 0xa0, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4b, 0x52, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x4b, 0x79, 0x75, 0x6e, 0x67, 0x67, 0x69, 0x2d, 0x64, 0x6f, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0b, 0x53, 0x65, 0x6f, 0x6e, 0x67, 0x6e, 0x61, 0x6d, 0x2d, 0x73, 0x69, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x11, 0x54, 0x68, 0x65, 0x20, 0x4e, 0x65, 0x74, 0x74, 0x79, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x0f, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x73, 0x31, 0x30, 0x30, 0x2e, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x27, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x63, 0x68, 0x61, 0x74, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x74, 0x79, 0x2e, 0x67, 0x6c, 0x65, 0x61, 0x6d, 0x79, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x30, 0x20, 0x17, 0x0d, 0x30, 0x38, 0x30, 0x36, 0x31, 0x39, 0x30, 0x35, 0x34, 0x31, 0x33, 0x38, 0x5a, 0x18, 0x0f, 0x32, 0x31, 0x38, 0x37, 0x31, 0x31, 0x32, 0x34, 0x30, 0x35, 0x34, 0x31, 0x33, 0x38, 0x5a, 0x30, 0x81, 0xa0, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4b, 0x52, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x4b, 0x79, 0x75, 0x6e, 0x67, 0x67, 0x69, 0x2d, 0x64, 0x6f, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0b, 0x53, 0x65, 0x6f, 0x6e, 0x67, 0x6e, 0x61, 0x6d, 0x2d, 0x73, 0x69, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x11, 0x54, 0x68, 0x65, 0x20, 0x4e, 0x65, 0x74, 0x74, 0x79, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x31, 0x18, 0x30, 0x16, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x0f, 0x45, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x20, 0x41, 0x75, 0x74, 0x68, 0x6f, 0x72, 0x73, 0x31, 0x30, 0x30, 0x2e, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x27, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x63, 0x68, 0x61, 0x74, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x74, 0x79, 0x2e, 0x67, 0x6c, 0x65, 0x61, 0x6d, 0x79, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x30, 0x5c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x4b, 0x00, 0x30, 0x48, 0x02, 0x41, 0x00, 0xc3, 0xe3, 0x5e, 0x41, 0xa7, 0x87, 0x11, 0x00, 0x42, 0x2a, 0xb0, 0x4b, 0xed, 0xb2, 0xe0, 0x23, 0xdb, 0xb1, 0x3d, 0x58, 0x97, 0x35, 0x60, 0x0b, 0x82, 0x59, 0xd3, 0x00, 0xea, 0xd4, 0x61, 0xb8, 0x79, 0x3f, 0xb6, 0x3c, 0x12, 0x05, 0x93, 0x2e, 0x9a, 0x59, 0x68, 0x14, 0x77, 0x3a, 0xc8, 0x50, 0x25, 0x57, 0xa4, 0x49, 0x18, 0x63, 0x41, 0xf0, 0x2d, 0x28, 0xec, 0x06, 0xfb, 0xb4, 0x9f, 0xbf, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x41, 0x00, 0x65, 0x6c, 0x30, 0x01, 0xc2, 0x8e, 0x3e, 0xcb, 0xb3, 0x77, 0x48, 0xe9, 0x66, 0x61, 0x9a, 0x40, 0x86, 0xaf, 0xf6, 0x03, 0xeb, 0xba, 0x6a, 0xf2, 0xfd, 0xe2, 0xaf, 0x36, 0x5e, 0x7b, 0xaa, 0x22, 0x04, 0xdd, 0x2c, 0x20, 0xc4, 0xfc, 0xdd, 0xd0, 0x82, 0x20, 0x1c, 0x3d, 0xd7, 0x9e, 0x5e, 0x5c, 0x92, 0x5a, 0x76, 0x71, 0x28, 0xf5, 0x07, 0x7d, 0xa2, 0x81, 0xba, 0x77, 0x9f, 0x2a, 0xd9, 0x44, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x6d, 0x79, 0x6b, 0x65, 0x79, 0x00, 0x00, 0x01, 0x1a, 0x9f, 0x5b, 0x56, 0xa0, 0x00, 0x00, 0x01, 0x99, 0x30, 0x82, 0x01, 0x95, 0x30, 0x0e, 0x06, 0x0a, 0x2b, 0x06, 0x01, 0x04, 0x01, 0x2a, 0x02, 0x11, 0x01, 0x01, 0x05, 0x00, 0x04, 0x82, 0x01, 0x81, 0x29, 0xa8, 0xb6, 0x08, 0x0c, 0x85, 0x75, 0x3e, 0xdd, 0xb5, 0xe5, 0x1a, 0x87, 0x68, 0xd1, 0x90, 0x4b, 0x29, 0x31, 0xee, 0x90, 0xbc, 0x9d, 0x73, 0xa0, 0x3f, 0xe9, 0x0b, 0xa4, 0xef, 0x30, 0x9b, 0x36, 0x9a, 0xb2, 0x54, 0x77, 0x81, 0x07, 0x4b, 0xaa, 0xa5, 0x77, 0x98, 0xe1, 0xeb, 0xb5, 0x7c, 0x4e, 0x48, 0xd5, 0x08, 0xfc, 0x2c, 0x36, 0xe2, 0x65, 0x03, 0xac, 0xe5, 0xf3, 0x96, 0xb7, 0xd0, 0xb5, 0x3b, 0x92, 0xe4, 0x14, 0x05, 0x7a, 0x6a, 0x92, 0x56, 0xfe, 0x4e, 0xab, 0xd3, 0x0e, 0x32, 0x04, 0x22, 0x22, 0x74, 0x47, 0x7d, 0xec, 0x21, 0x99, 0x30, 0x31, 0x64, 0x46, 0x64, 0x9b, 0xc7, 0x13, 0xbf, 0xbe, 0xd0, 0x31, 0x49, 0xe7, 0x3c, 0xbf, 0xba, 0xb1, 0x20, 0xf9, 0x42, 0xf4, 0xa9, 0xa9, 0xe5, 0x13, 0x65, 0x32, 0xbf, 0x7c, 0xcc, 0x91, 0xd3, 0xfd, 0x24, 0x47, 0x0b, 0xe5, 0x53, 0xad, 0x50, 0x30, 0x56, 0xd1, 0xfa, 0x9c, 0x37, 0xa8, 0xc1, 0xce, 0xf6, 0x0b, 0x18, 0xaa, 0x7c, 0xab, 0xbd, 0x1f, 0xdf, 0xe4, 0x80, 0xb8, 0xa7, 0xe0, 0xad, 0x7d, 0x50, 0x74, 0xf1, 0x98, 0x78, 0xbc, 0x58, 0xb9, 0xc2, 0x52, 0xbe, 0xd2, 0x5b, 0x81, 0x94, 0x83, 0x8f, 0xb9, 0x4c, 0xee, 0x01, 0x2b, 0x5e, 0xc9, 0x6e, 0x9b, 0xf5, 0x63, 0x69, 0xe4, 0xd8, 0x0b, 0x47, 0xd8, 0xfd, 0xd8, 0xe0, 0xed, 0xa8, 0x27, 0x03, 0x74, 0x1e, 0x5d, 0x32, 0xe6, 0x5c, 0x63, 0xc2, 0xfb, 0x3f, 0xee, 0xb4, 0x13, 0xc6, 0x0e, 0x6e, 0x74, 0xe0, 0x22, 0xac, 0xce, 0x79, 0xf9, 0x43, 0x68, 0xc1, 0x03, 0x74, 0x2b, 0xe1, 0x18, 0xf8, 0x7f, 0x76, 0x9a, 0xea, 0x82, 0x3f, 0xc2, 0xa6, 0xa7, 0x4c, 0xfe, 0xae, 0x29, 0x3b, 0xc1, 0x10, 0x7c, 0xd5, 0x77, 0x17, 0x79, 0x5f, 0xcb, 0xad, 0x1f, 0xd8, 0xa1, 0xfd, 0x90, 0xe1, 0x6b, 0xb2, 0xef, 0xb9, 0x41, 0x26, 0xa4, 0x0b, 0x4f, 0xc6, 0x83, 0x05, 0x6f, 0xf0, 0x64, 0x40, 0xe1, 0x44, 0xc4, 0xf9, 0x40, 0x2b, 0x3b, 0x40, 0xdb, 0xaf, 0x35, 0xa4, 0x9b, 0x9f, 0xc4, 0x74, 0x07, 0xe5, 0x18, 0x60, 0xc5, 0xfe, 0x15, 0x0e, 0x3a, 0x25, 0x2a, 0x11, 0xee, 0x78, 0x2f, 0xb8, 0xd1, 0x6e, 0x4e, 0x3c, 0x0a, 0xb5, 0xb9, 0x40, 0x86, 0x27, 0x6d, 0x8f, 0x53, 0xb7, 0x77, 0x36, 0xec, 0x5d, 0xed, 0x32, 0x40, 0x43, 0x82, 0xc3, 0x52, 0x58, 0xc4, 0x26, 0x39, 0xf3, 0xb3, 0xad, 0x58, 0xab, 0xb7, 0xf7, 0x8e, 0x0e, 0xba, 0x8e, 0x78, 0x9d, 0xbf, 0x58, 0x34, 0xbd, 0x77, 0x73, 0xa6, 0x50, 0x55, 0x00, 0x60, 0x26, 0xbf, 0x6d, 0xb4, 0x98, 0x8a, 0x18, 0x83, 0x89, 0xf8, 0xcd, 0x0d, 0x49, 0x06, 0xae, 0x51, 0x6e, 0xaf, 0xbd, 0xe2, 0x07, 0x13, 0xd8, 0x64, 0xcc, 0xbf, 0x00, 0x00, 0x00, 0x01, 0x00, 0x05, 0x58, 0x2e, 0x35, 0x30, 0x39, 0x00, 0x00, 0x02, 0x34, 0x30, 0x82, 0x02, 0x30, 0x30, 0x82, 0x01, 0xda, 0xa0, 0x03, 0x02, 0x01, 0x02, 0x02, 0x04, 0x48, 0x59, 0xf2, 0x84, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x30, 0x81, 0x9d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4b, 0x52, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x4b, 0x79, 0x75, 0x6e, 0x67, 0x67, 0x69, 0x2d, 0x64, 0x6f, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0b, 0x53, 0x65, 0x6f, 0x6e, 0x67, 0x6e, 0x61, 0x6d, 0x2d, 0x73, 0x69, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x11, 0x54, 0x68, 0x65, 0x20, 0x4e, 0x65, 0x74, 0x74, 0x79, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x0c, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x73, 0x31, 0x30, 0x30, 0x2e, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x27, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x63, 0x68, 0x61, 0x74, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x74, 0x79, 0x2e, 0x67, 0x6c, 0x65, 0x61, 0x6d, 0x79, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x30, 0x20, 0x17, 0x0d, 0x30, 0x38, 0x30, 0x36, 0x31, 0x39, 0x30, 0x35, 0x34, 0x35, 0x34, 0x30, 0x5a, 0x18, 0x0f, 0x32, 0x31, 0x38, 0x37, 0x31, 0x31, 0x32, 0x33, 0x30, 0x35, 0x34, 0x35, 0x34, 0x30, 0x5a, 0x30, 0x81, 0x9d, 0x31, 0x0b, 0x30, 0x09, 0x06, 0x03, 0x55, 0x04, 0x06, 0x13, 0x02, 0x4b, 0x52, 0x31, 0x13, 0x30, 0x11, 0x06, 0x03, 0x55, 0x04, 0x08, 0x13, 0x0a, 0x4b, 0x79, 0x75, 0x6e, 0x67, 0x67, 0x69, 0x2d, 0x64, 0x6f, 0x31, 0x14, 0x30, 0x12, 0x06, 0x03, 0x55, 0x04, 0x07, 0x13, 0x0b, 0x53, 0x65, 0x6f, 0x6e, 0x67, 0x6e, 0x61, 0x6d, 0x2d, 0x73, 0x69, 0x31, 0x1a, 0x30, 0x18, 0x06, 0x03, 0x55, 0x04, 0x0a, 0x13, 0x11, 0x54, 0x68, 0x65, 0x20, 0x4e, 0x65, 0x74, 0x74, 0x79, 0x20, 0x50, 0x72, 0x6f, 0x6a, 0x65, 0x63, 0x74, 0x31, 0x15, 0x30, 0x13, 0x06, 0x03, 0x55, 0x04, 0x0b, 0x13, 0x0c, 0x43, 0x6f, 0x6e, 0x74, 0x72, 0x69, 0x62, 0x75, 0x74, 0x6f, 0x72, 0x73, 0x31, 0x30, 0x30, 0x2e, 0x06, 0x03, 0x55, 0x04, 0x03, 0x13, 0x27, 0x73, 0x65, 0x63, 0x75, 0x72, 0x65, 0x63, 0x68, 0x61, 0x74, 0x2e, 0x65, 0x78, 0x61, 0x6d, 0x70, 0x6c, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x74, 0x79, 0x2e, 0x67, 0x6c, 0x65, 0x61, 0x6d, 0x79, 0x6e, 0x6f, 0x64, 0x65, 0x2e, 0x6e, 0x65, 0x74, 0x30, 0x5c, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x01, 0x05, 0x00, 0x03, 0x4b, 0x00, 0x30, 0x48, 0x02, 0x41, 0x00, 0x95, 0xb3, 0x47, 0x17, 0x95, 0x0f, 0x57, 0xcf, 0x66, 0x72, 0x0a, 0x7e, 0x5b, 0x54, 0xea, 0x8c, 0x6f, 0x79, 0xde, 0x94, 0xac, 0x0b, 0x5a, 0xd4, 0xd6, 0x1b, 0x58, 0x12, 0x1a, 0x16, 0x3d, 0xfe, 0xdf, 0xa5, 0x2b, 0x86, 0xbc, 0x64, 0xd4, 0x80, 0x1e, 0x3f, 0xf9, 0xe2, 0x04, 0x03, 0x79, 0x9b, 0xc1, 0x5c, 0xf0, 0xf1, 0xf3, 0xf1, 0xe3, 0xbf, 0x3f, 0xc0, 0x1f, 0xdd, 0xdb, 0xc0, 0x5b, 0x21, 0x02, 0x03, 0x01, 0x00, 0x01, 0x30, 0x0d, 0x06, 0x09, 0x2a, 0x86, 0x48, 0x86, 0xf7, 0x0d, 0x01, 0x01, 0x05, 0x05, 0x00, 0x03, 0x41, 0x00, 0x02, 0xd7, 0xdd, 0xbd, 0x0c, 0x8e, 0x21, 0x20, 0xef, 0x9e, 0x4f, 0x1f, 0xf5, 0x49, 0xf1, 0xae, 0x58, 0x9b, 0x94, 0x3a, 0x1f, 0x70, 0x33, 0xf0, 0x9b, 0xbb, 0xe9, 0xc0, 0xf3, 0x72, 0xcb, 0xde, 0xb6, 0x56, 0x72, 0xcc, 0x1c, 0xf0, 0xd6, 0x5a, 0x2a, 0xbc, 0xa1, 0x7e, 0x23, 0x83, 0xe9, 0xe7, 0xcf, 0x9e, 0xa5, 0xf9, 0xcc, 0xc2, 0x61, 0xf4, 0xdb, 0x40, 0x93, 0x1d, 0x63, 0x8a, 0x50, 0x4c, 0x11, 0x39, 0xb1, 0x91, 0xc1, 0xe6, 0x9d, 0xd9, 0x1a, 0x62, 0x1b, 0xb8, 0xd3, 0xd6, 0x9a, 0x6d, 0xb9, 0x8e, 0x15, 0x51 }; public static InputStream asInputStream() { byte[] data = new byte[DATA.length]; for (int i = 0; i < data.length; i ++) { data[i] = (byte) DATA[i]; } return new ByteArrayInputStream(data); } public static char[] getCertificatePassword() { return "secret".toCharArray(); } public static char[] getKeyStorePassword() { return "secret".toCharArray(); } private SecureChatKeyStore() { // Unused } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatClientHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatClientHandle0000644000175000017500000000577611172030314032605 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.ssl.SslHandler; /** * Handles a client-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class SecureChatClientHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( SecureChatClientHandler.class.getName()); @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Get the SslHandler from the pipeline // which were added in SecureChatPipelineFactory. SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class); // Begin handshake. sslHandler.handshake(e.getChannel()); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { System.err.println(e.getMessage()); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatServerHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatServerHandle0000644000175000017500000001307011172030314032617 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import java.net.InetAddress; import java.util.Set; import java.util.concurrent.ConcurrentHashMap; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.ssl.SslHandler; import org.jboss.netty.util.internal.MapBackedSet; /** * Handles a server-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class SecureChatServerHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( SecureChatServerHandler.class.getName()); static final Set channels = new MapBackedSet(new ConcurrentHashMap()); @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Get the SslHandler in the current pipeline. // We added it in SecureChatPipelineFactory. final SslHandler sslHandler = ctx.getPipeline().get(SslHandler.class); // Get notified when SSL handshake is done. ChannelFuture handshakeFuture = sslHandler.handshake(e.getChannel()); handshakeFuture.addListener(new Greeter(sslHandler)); } @Override public void channelDisconnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Unregister the channel from the global channel list // so the channel does not receive messages anymore. channels.remove(e.getChannel()); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { // Convert to a String first. String request = (String) e.getMessage(); // Send the received message to all channels but the current one. for (Channel c: channels) { if (c != e.getChannel()) { c.write("[" + e.getChannel().getRemoteAddress() + "] " + request + '\n'); } } // Close the connection if the client has sent 'bye'. if (request.toLowerCase().equals("bye")) { e.getChannel().close(); } } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ private static final class Greeter implements ChannelFutureListener { private final SslHandler sslHandler; Greeter(SslHandler sslHandler) { this.sslHandler = sslHandler; } public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Once session is secured, send a greeting. future.getChannel().write( "Welcome to " + InetAddress.getLocalHost().getHostName() + " secure chat service!\n"); future.getChannel().write( "Your session is protected by " + sslHandler.getEngine().getSession().getCipherSuite() + " cipher suite.\n"); // Register the channel to the global channel list // so the channel received the messages from others. channels.add(future.getChannel()); } else { future.getChannel().close(); } } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/securechat/SecureChatServer.java0000644000175000017500000000450611050275327032441 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.securechat; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.example.telnet.TelnetServer; /** * Simple SSL chat server modified from {@link TelnetServer}. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class SecureChatServer { public static void main(String[] args) throws Exception { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); SecureChatServerHandler handler = new SecureChatServerHandler(); bootstrap.setPipelineFactory(new SecureChatPipelineFactory(handler)); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/qotm/0000755000175000017500000000000011316313141025176 5ustar deckerdecker././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServerHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServerHandle0000644000175000017500000000540711156220320032633 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.qotm; import java.util.Random; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1029 $, $Date: 2009-03-12 07:48:48 -0700 (Thu, 12 Mar 2009) $ */ @ChannelPipelineCoverage("all") public class QuoteOfTheMomentServerHandler extends SimpleChannelUpstreamHandler { private static final Random random = new Random(); // Quotes from Mohandas K. Gandhi: private static final String[] quotes = new String[] { "Where there is love there is life.", "First they ignore you, then they laugh at you, then they fight you, then you win.", "Be the change you want to see in the world.", "The weak can never forgive. Forgiveness is the attribute of the strong.", }; private static String nextQuote() { int quoteId; synchronized (random) { quoteId = random.nextInt(quotes.length); } return quotes[quoteId]; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String msg = (String) e.getMessage(); if (msg.equals("QOTM?")) { e.getChannel().write("QOTM: " + nextQuote(), e.getRemoteAddress()); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { e.getCause().printStackTrace(); // We don't close the channel because we can keep serving requests. } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentServer.java0000644000175000017500000000474411175512004032446 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.qotm; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * A UDP server that responds to the QOTM (quote of the moment) request to a * {@link QuoteOfTheMomentClient}. * * Inspired by the official Java tutorial. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1251 $, $Date: 2009-04-27 22:28:36 -0700 (Mon, 27 Apr 2009) $ */ public class QuoteOfTheMomentServer { public static void main(String[] args) throws Exception { DatagramChannelFactory f = new OioDatagramChannelFactory(Executors.newCachedThreadPool()); ConnectionlessBootstrap b = new ConnectionlessBootstrap(f); ChannelPipeline p = b.getPipeline(); p.addLast("encoder", new StringEncoder("UTF-8")); p.addLast("decoder", new StringDecoder("UTF-8")); p.addLast("handler", new QuoteOfTheMomentServerHandler()); b.setOption("broadcast", "false"); b.bind(new InetSocketAddress(8080)); } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClientHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClientHandle0000644000175000017500000000415511156220320032602 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.qotm; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1029 $, $Date: 2009-03-12 07:48:48 -0700 (Thu, 12 Mar 2009) $ */ @ChannelPipelineCoverage("all") public class QuoteOfTheMomentClientHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { String msg = (String) e.getMessage(); if (msg.startsWith("QOTM: ")) { System.out.println("Quote of the Moment: " + msg.substring(6)); e.getChannel().close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { e.getCause().printStackTrace(); e.getChannel().close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/qotm/QuoteOfTheMomentClient.java0000644000175000017500000000613411175512004032411 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.qotm; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ConnectionlessBootstrap; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.socket.DatagramChannel; import org.jboss.netty.channel.socket.DatagramChannelFactory; import org.jboss.netty.channel.socket.oio.OioDatagramChannelFactory; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * A UDP broadcast client that asks for a quote of the moment (QOTM) to * {@link QuoteOfTheMomentServer}. * * Inspired by the official Java tutorial. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1251 $, $Date: 2009-04-27 22:28:36 -0700 (Mon, 27 Apr 2009) $ */ public class QuoteOfTheMomentClient { public static void main(String[] args) throws Exception { DatagramChannelFactory f = new OioDatagramChannelFactory(Executors.newCachedThreadPool()); ConnectionlessBootstrap b = new ConnectionlessBootstrap(f); ChannelPipeline p = b.getPipeline(); p.addLast("encoder", new StringEncoder("UTF-8")); p.addLast("decoder", new StringDecoder("UTF-8")); p.addLast("handler", new QuoteOfTheMomentClientHandler()); b.setOption("broadcast", "true"); DatagramChannel c = (DatagramChannel) b.bind(new InetSocketAddress(0)); // Broadcast the QOTM request to port 8080. c.write("QOTM?", new InetSocketAddress("255.255.255.255", 8080)); // QuoteOfTheMomentClientHandler will close the DatagramChannel when a // response is received. If the channel is not closed within 5 seconds, // print an error message and quit. if (!c.getCloseFuture().awaitUninterruptibly(5000)) { System.err.println("QOTM request timed out."); c.close().awaitUninterruptibly(); } f.releaseExternalResources(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/servlet/0000755000175000017500000000000011316313142025703 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/0000755000175000017500000000000011316313141025175 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/0000755000175000017500000000000011316313141026333 5ustar deckerdecker././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpClientPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpClientPipelineFact0000644000175000017500000000422011216747541032634 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.snoop; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpRequestEncoder; import org.jboss.netty.handler.codec.http.HttpResponseDecoder; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpClientPipelineFactory implements ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); pipeline.addLast("decoder", new HttpResponseDecoder()); // Uncomment the following line if you don't want to handle HttpChunks. //pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); pipeline.addLast("encoder", new HttpRequestEncoder()); pipeline.addLast("handler", new HttpResponseHandler()); return pipeline; } } ././@LongLink0000000000000000000000000000015500000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpServerPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpServerPipelineFact0000644000175000017500000000461711216747541032676 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.snoop; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpServerPipelineFactory implements ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); // Uncomment the following line if you want HTTPS //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); //engine.setUseClientMode(false); //pipeline.addLast("ssl", new SslHandler(engine)); pipeline.addLast("decoder", new HttpRequestDecoder()); // Uncomment the following line if you don't want to handle HttpChunks. //pipeline.addLast("aggregator", new HttpChunkAggregator(1048576)); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("handler", new HttpRequestHandler()); return pipeline; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpServer.java0000644000175000017500000000423311216747541031324 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.snoop; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpServer { public static void main(String[] args) { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); bootstrap.setPipelineFactory(new HttpServerPipelineFactory()); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } ././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpResponseHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpResponseHandler.ja0000644000175000017500000000657111216747541032632 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.snoop; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpResponse; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ @ChannelPipelineCoverage("one") public class HttpResponseHandler extends SimpleChannelUpstreamHandler { private volatile boolean readingChunks; @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (!readingChunks) { HttpResponse response = (HttpResponse) e.getMessage(); System.out.println("STATUS: " + response.getStatus()); System.out.println("VERSION: " + response.getProtocolVersion()); System.out.println(); if (!response.getHeaderNames().isEmpty()) { for (String name: response.getHeaderNames()) { for (String value: response.getHeaders(name)) { System.out.println("HEADER: " + name + " = " + value); } } System.out.println(); } if (response.getStatus().getCode() == 200 && response.isChunked()) { readingChunks = true; System.out.println("CHUNKED CONTENT {"); } else { ChannelBuffer content = response.getContent(); if (content.readable()) { System.out.println("CONTENT {"); System.out.println(content.toString("UTF-8")); System.out.println("} END OF CONTENT"); } } } else { HttpChunk chunk = (HttpChunk) e.getMessage(); if (chunk.isLast()) { readingChunks = false; System.out.println("} END OF CHUNKED CONTENT"); } else { System.out.print(chunk.getContent().toString("UTF-8")); System.out.flush(); } } } } ././@LongLink0000000000000000000000000000014600000000000011566 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpRequestHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpRequestHandler.jav0000644000175000017500000001646611216747541032656 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.snoop; import java.util.List; import java.util.Map; import java.util.Set; import java.util.Map.Entry; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.http.Cookie; import org.jboss.netty.handler.codec.http.CookieDecoder; import org.jboss.netty.handler.codec.http.CookieEncoder; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpChunk; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpVersion; import org.jboss.netty.handler.codec.http.QueryStringDecoder; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ @ChannelPipelineCoverage("one") public class HttpRequestHandler extends SimpleChannelUpstreamHandler { private volatile HttpRequest request; private volatile boolean readingChunks; private final StringBuilder responseContent = new StringBuilder(); @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { if (!readingChunks) { HttpRequest request = this.request = (HttpRequest) e.getMessage(); responseContent.append("WELCOME TO THE WILD WILD WEB SERVER\r\n"); responseContent.append("===================================\r\n"); responseContent.append("VERSION: " + request.getProtocolVersion().getText() + "\r\n"); if (request.containsHeader(HttpHeaders.Names.HOST)) { responseContent.append("HOSTNAME: " + request.getHeader(HttpHeaders.Names.HOST) + "\r\n"); } responseContent.append("REQUEST_URI: " + request.getUri() + "\r\n\r\n"); if (!request.getHeaderNames().isEmpty()) { for (String name: request.getHeaderNames()) { for (String value: request.getHeaders(name)) { responseContent.append("HEADER: " + name + " = " + value + "\r\n"); } } responseContent.append("\r\n"); } QueryStringDecoder queryStringDecoder = new QueryStringDecoder(request.getUri()); Map> params = queryStringDecoder.getParameters(); if (!params.isEmpty()) { for (Entry> p: params.entrySet()) { String key = p.getKey(); List vals = p.getValue(); for (String val : vals) { responseContent.append("PARAM: " + key + " = " + val + "\r\n"); } } responseContent.append("\r\n"); } if (request.isChunked()) { readingChunks = true; } else { ChannelBuffer content = request.getContent(); if (content.readable()) { responseContent.append("CONTENT: " + content.toString("UTF-8") + "\r\n"); } writeResponse(e); } } else { HttpChunk chunk = (HttpChunk) e.getMessage(); if (chunk.isLast()) { readingChunks = false; responseContent.append("END OF CONTENT\r\n"); writeResponse(e); } else { responseContent.append("CHUNK: " + chunk.getContent().toString("UTF-8") + "\r\n"); } } } private void writeResponse(MessageEvent e) { // Convert the response content to a ChannelBuffer. ChannelBuffer buf = ChannelBuffers.copiedBuffer(responseContent.toString(), "UTF-8"); responseContent.setLength(0); // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION)); // Build the response object. HttpResponse response = new DefaultHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setContent(buf); response.setHeader(HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); if (!close) { // There's no need to add 'Content-Length' header // if this is the last response. response.setHeader(HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(buf.readableBytes())); } String cookieString = request.getHeader(HttpHeaders.Names.COOKIE); if (cookieString != null) { CookieDecoder cookieDecoder = new CookieDecoder(); Set cookies = cookieDecoder.decode(cookieString); if(!cookies.isEmpty()) { // Reset the cookies if necessary. CookieEncoder cookieEncoder = new CookieEncoder(true); for (Cookie cookie : cookies) { cookieEncoder.addCookie(cookie); } response.addHeader(HttpHeaders.Names.SET_COOKIE, cookieEncoder.encode()); } } // Write the response. ChannelFuture future = e.getChannel().write(response); // Close the connection after the write operation is done if necessary. if (close) { future.addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { e.getCause().printStackTrace(); e.getChannel().close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/snoop/HttpClient.java0000644000175000017500000001044011216747541031271 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.snoop; import java.net.InetSocketAddress; import java.net.URI; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.handler.codec.http.CookieEncoder; import org.jboss.netty.handler.codec.http.DefaultHttpRequest; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpVersion; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpClient { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println( "Usage: " + HttpClient.class.getSimpleName() + " "); return; } URI uri = new URI(args[0]); String scheme = uri.getScheme() == null? "http" : uri.getScheme(); String host = uri.getHost() == null? "localhost" : uri.getHost(); int port = uri.getPort() == -1? 80 : uri.getPort(); if (!scheme.equals("http")) { // We can actually support HTTPS fairly easily by inserting // an SslHandler to the pipeline - left as an exercise. System.err.println("Only HTTP is supported."); return; } // Configure the client. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); bootstrap.setPipelineFactory(new HttpClientPipelineFactory()); // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.awaitUninterruptibly().getChannel(); if (!future.isSuccess()) { future.getCause().printStackTrace(); factory.releaseExternalResources(); return; } // Send the HTTP request. HttpRequest request = new DefaultHttpRequest( HttpVersion.HTTP_1_1, HttpMethod.GET, uri.toASCIIString()); request.addHeader(HttpHeaders.Names.HOST, host); request.addHeader(HttpHeaders.Names.CONNECTION, HttpHeaders.Values.CLOSE); CookieEncoder httpCookieEncoder = new CookieEncoder(false); httpCookieEncoder.addCookie("my-cookie", "foo"); httpCookieEncoder.addCookie("another-cookie", "bar"); request.addHeader(HttpHeaders.Names.COOKIE, httpCookieEncoder.encode()); channel.write(request); // Wait for the server to close the connection. channel.getCloseFuture().awaitUninterruptibly(); // Shut down executor threads to exit. factory.releaseExternalResources(); } }libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/file/0000755000175000017500000000000011316313141026114 5ustar deckerdecker././@LongLink0000000000000000000000000000014700000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServer.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServer.ja0000644000175000017500000000356111216747541032531 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.file; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) */ public class HttpStaticFileServer { public static void main(String[] args) { // Configure the server. ServerBootstrap bootstrap = new ServerBootstrap( new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool())); bootstrap.setPipelineFactory(new HttpStaticFileServerPipelineFactory()); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } ././@LongLink0000000000000000000000000000015600000000000011567 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerHan0000644000175000017500000001466711216747541032600 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.file; import java.io.File; import java.io.FileNotFoundException; import java.io.RandomAccessFile; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.frame.TooLongFrameException; import org.jboss.netty.handler.codec.http.DefaultHttpResponse; import org.jboss.netty.handler.codec.http.HttpHeaders; import org.jboss.netty.handler.codec.http.HttpMethod; import org.jboss.netty.handler.codec.http.HttpRequest; import org.jboss.netty.handler.codec.http.HttpResponse; import org.jboss.netty.handler.codec.http.HttpResponseStatus; import org.jboss.netty.handler.codec.http.HttpVersion; import org.jboss.netty.handler.stream.ChunkedFile; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) */ @ChannelPipelineCoverage("one") public class HttpStaticFileServerHandler extends SimpleChannelUpstreamHandler { @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { HttpRequest request = (HttpRequest) e.getMessage(); if (request.getMethod() != HttpMethod.GET) { sendError(ctx, HttpResponseStatus.METHOD_NOT_ALLOWED); return; } if (request.isChunked()) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } String path = sanitizeUri(request.getUri()); if (path == null) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } File file = new File(path); if (file.isHidden() || !file.exists()) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } if (!file.isFile()) { sendError(ctx, HttpResponseStatus.FORBIDDEN); return; } RandomAccessFile raf; try { raf = new RandomAccessFile(file, "r"); } catch (FileNotFoundException fnfe) { sendError(ctx, HttpResponseStatus.NOT_FOUND); return; } long fileLength = raf.length(); HttpResponse response = new DefaultHttpResponse( HttpVersion.HTTP_1_1, HttpResponseStatus.OK); response.setHeader( HttpHeaders.Names.CONTENT_LENGTH, String.valueOf(fileLength)); Channel ch = e.getChannel(); // Write the initial line and the header. ch.write(response); // Write the content. ChannelFuture writeFuture = ch.write(new ChunkedFile(raf, 0, fileLength, 8192)); // Decide whether to close the connection or not. boolean close = HttpHeaders.Values.CLOSE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION)) || request.getProtocolVersion().equals(HttpVersion.HTTP_1_0) && !HttpHeaders.Values.KEEP_ALIVE.equalsIgnoreCase(request.getHeader(HttpHeaders.Names.CONNECTION)); if (close) { // Close the connection when the whole content is written out. writeFuture.addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { Channel ch = e.getChannel(); Throwable cause = e.getCause(); if (cause instanceof TooLongFrameException) { sendError(ctx, HttpResponseStatus.BAD_REQUEST); return; } cause.printStackTrace(); if (ch.isConnected()) { sendError(ctx, HttpResponseStatus.INTERNAL_SERVER_ERROR); } } private String sanitizeUri(String uri) { // Decode the path. try { uri = URLDecoder.decode(uri, "UTF-8"); } catch (UnsupportedEncodingException e) { try { uri = URLDecoder.decode(uri, "ISO-8859-1"); } catch (UnsupportedEncodingException e1) { throw new Error(); } } // Convert file separators. uri = uri.replace('/', File.separatorChar); // Simplistic dumb security check. // You will have to do something serious in the production environment. if (uri.contains(File.separator + ".") || uri.contains("." + File.separator) || uri.startsWith(".") || uri.endsWith(".")) { return null; } // Convert to absolute path. return System.getProperty("user.dir") + File.separator + uri; } private void sendError(ChannelHandlerContext ctx, HttpResponseStatus status) { HttpResponse response = new DefaultHttpResponse( HttpVersion.HTTP_1_1, status); response.setHeader( HttpHeaders.Names.CONTENT_TYPE, "text/plain; charset=UTF-8"); response.setContent(ChannelBuffers.copiedBuffer( "Failure: " + status.toString() + "\r\n", "UTF-8")); // Close the connection as soon as the error message is sent. ctx.getChannel().write(response).addListener(ChannelFutureListener.CLOSE); } } ././@LongLink0000000000000000000000000000016600000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/file/HttpStaticFileServerPip0000644000175000017500000000440511216747541032607 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.file; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.http.HttpRequestDecoder; import org.jboss.netty.handler.codec.http.HttpResponseEncoder; import org.jboss.netty.handler.stream.ChunkedWriteHandler; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) */ public class HttpStaticFileServerPipelineFactory implements ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); // Uncomment the following line if you want HTTPS //SSLEngine engine = SecureChatSslContextFactory.getServerContext().createSSLEngine(); //engine.setUseClientMode(false); //pipeline.addLast("ssl", new SslHandler(engine)); pipeline.addLast("decoder", new HttpRequestDecoder()); pipeline.addLast("encoder", new HttpResponseEncoder()); pipeline.addLast("chunkedWriter", new ChunkedWriteHandler()); pipeline.addLast("handler", new HttpStaticFileServerHandler()); return pipeline; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/tunnel/0000755000175000017500000000000011316313141026502 5ustar deckerdecker././@LongLink0000000000000000000000000000015700000000000011570 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/tunnel/HttpTunnelingClientExample.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/tunnel/HttpTunnelingClientEx0000644000175000017500000001554311216747541032712 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.tunnel; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.URI; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.socket.http.HttpTunnelAddress; import org.jboss.netty.channel.socket.http.HttpTunnelingClientSocketChannelFactory; import org.jboss.netty.channel.socket.http.HttpTunnelingServlet; import org.jboss.netty.channel.socket.oio.OioClientSocketChannelFactory; import org.jboss.netty.handler.codec.oneone.OneToOneDecoder; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * Make sure that the {@link LocalTransportRegister} bean is deployed along * with the {@link HttpTunnelingServlet} with the following web.xml. * *
 * <?xml version="1.0" encoding="UTF-8"?>
 * <web-app xmlns="http://java.sun.com/xml/ns/j2ee"
 *             xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 *             xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
 *             version="2.4">
 *    <!--the name of the channel, this should be a registered local channel. see LocalTransportRegister-->
 *    <context-param>
 *       <param-name>serverChannelName</param-name>
 *       <param-value>myLocalServer</param-value>
 *    </context-param>
 *
 *     <!--Whether or not we are streaming or just polling using normal HTTP requests-->
 *     <context-param>
 *       <param-name>streaming</param-name>
 *       <param-value>true</param-value>
 *    </context-param>
 *
 *     <!--How long to wait for a client reconnecting in milliseconds-->
 *    <context-param>
 *       <param-name>reconnectTimeout</param-name>
 *       <param-value>3000</param-value>
 *    </context-param>
 *
 *    <listener>
 *       <listener-class>org.jboss.netty.channel.socket.http.HttpTunnelingSessionListener</listener-class>
 *    </listener>
 *
 *    <listener>
 *       <listener-class>org.jboss.netty.channel.socket.http.HttpTunnelingContextListener</listener-class>
 *    </listener>
 *
 *    <servlet>
 *       <servlet-name>NettyTunnelingServlet</servlet-name>
 *       <servlet-class>org.jboss.netty.channel.socket.http.HttpTunnelingServlet</servlet-class>
 *    </servlet>
 *
 *    <servlet-mapping>
 *       <servlet-name>NettyTunnelingServlet</servlet-name>
 *       <url-pattern>/netty-tunnel</url-pattern>
 *    </servlet-mapping>
 * </web-app>
 * 
* @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class HttpTunnelingClientExample { public static void main(String[] args) throws Exception { if (args.length != 1) { System.err.println( "Usage: " + HttpTunnelingClientExample.class.getSimpleName() + " "); System.err.println( "Example: " + HttpTunnelingClientExample.class.getSimpleName() + " http://localhost:8080/netty-tunnel"); return; } URI uri = new URI(args[0]); String scheme = uri.getScheme() == null? "http" : uri.getScheme(); if (!scheme.equals("http")) { // We can actually support HTTPS fairly easily by inserting // an SslHandler to the pipeline - left as an exercise. System.err.println("Only HTTP is supported."); return; } HttpTunnelingClientSocketChannelFactory factory = new HttpTunnelingClientSocketChannelFactory(new OioClientSocketChannelFactory(Executors.newCachedThreadPool()), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); bootstrap.getPipeline().addLast("decoder", new StringDecoder()); bootstrap.getPipeline().addLast("encoder", new StringEncoder()); bootstrap.getPipeline().addLast("handler", new PrintHandler()); ChannelFuture channelFuture = bootstrap.connect(new HttpTunnelAddress(uri)); channelFuture.awaitUninterruptibly(); System.out.println("Enter text (quit to end)"); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (; ;) { String line = in.readLine(); if (line == null || "quit".equalsIgnoreCase(line)) { break; } // Sends the received line to the server. lastWriteFuture = channelFuture.getChannel().write(line); } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.awaitUninterruptibly(); } channelFuture.getChannel().close(); // Wait until the connection is closed or the connection attempt fails. channelFuture.getChannel().getCloseFuture().awaitUninterruptibly(); factory.releaseExternalResources(); } @ChannelPipelineCoverage("all") static class PrintHandler extends OneToOneDecoder { @Override protected Object decode(ChannelHandlerContext ctx, Channel channel, Object msg) throws Exception { String message = (String) msg; System.out.println("received message back '" + message + "'"); return message; } } } ././@LongLink0000000000000000000000000000015300000000000011564 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/tunnel/LocalTransportRegister.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/http/tunnel/LocalTransportRegiste0000644000175000017500000000444311216747541032742 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.http.tunnel; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory; import org.jboss.netty.channel.local.LocalAddress; import org.jboss.netty.example.echo.EchoHandler; /** * Deploy this in JBossAS 5 by adding the following bean. * *
 * <bean name="org.jboss.netty.example.http.tunnel.LocalTransportRegister"
 *       class="org.jboss.netty.example.http.tunnel.LocalTransportRegister" />
 * 
* * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class LocalTransportRegister { private final ChannelFactory factory = new DefaultLocalServerChannelFactory(); private volatile Channel serverChannel; public void start() { ServerBootstrap serverBootstrap = new ServerBootstrap(factory); EchoHandler handler = new EchoHandler(); serverBootstrap.getPipeline().addLast("handler", handler); serverChannel = serverBootstrap.bind(new LocalAddress("myLocalServer")); } public void stop() { serverChannel.close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/proxy/0000755000175000017500000000000011316313142025400 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/proxy/HexDumpProxy.java0000644000175000017500000000542011214412050030653 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.proxy; import java.net.InetSocketAddress; import java.util.concurrent.Executor; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1358 $, $Date: 2009-06-12 01:39:04 -0700 (Fri, 12 Jun 2009) $ */ public class HexDumpProxy { public static void main(String[] args) throws Exception { // Validate command line options. if (args.length != 3) { System.err.println( "Usage: " + HexDumpProxy.class.getSimpleName() + " "); return; } // Parse command line options. int localPort = Integer.parseInt(args[0]); String remoteHost = args[1]; int remotePort = Integer.parseInt(args[2]); System.err.println( "Proxying *:" + localPort + " to " + remoteHost + ':' + remotePort + " ..."); // Configure the bootstrap. Executor executor = Executors.newCachedThreadPool(); ServerBootstrap sb = new ServerBootstrap( new NioServerSocketChannelFactory(executor, executor)); ClientSocketChannelFactory cf = new NioClientSocketChannelFactory(executor, executor); sb.setPipelineFactory( new HexDumpProxyPipelineFactory(cf, remoteHost, remotePort)); // Start up the server. sb.bind(new InetSocketAddress(localPort)); } } ././@LongLink0000000000000000000000000000015200000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyPipelineFactory0000644000175000017500000000412211214412050032747 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.proxy; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1358 $, $Date: 2009-06-12 01:39:04 -0700 (Fri, 12 Jun 2009) $ */ public class HexDumpProxyPipelineFactory implements ChannelPipelineFactory { private final ClientSocketChannelFactory cf; private final String remoteHost; private final int remotePort; public HexDumpProxyPipelineFactory( ClientSocketChannelFactory cf, String remoteHost, int remotePort) { this.cf = cf; this.remoteHost = remoteHost; this.remotePort = remotePort; } public ChannelPipeline getPipeline() throws Exception { ChannelPipeline p = pipeline(); // Note the static import. p.addLast("handler", new HexDumpProxyInboundHandler(cf, remoteHost, remotePort)); return p; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyInboundHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/proxy/HexDumpProxyInboundHandler.0000644000175000017500000001224711214412404032636 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.proxy; import java.net.InetSocketAddress; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.channel.socket.ClientSocketChannelFactory; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 1360 $, $Date: 2009-06-12 01:42:44 -0700 (Fri, 12 Jun 2009) $ */ @ChannelPipelineCoverage("one") public class HexDumpProxyInboundHandler extends SimpleChannelUpstreamHandler { private final ClientSocketChannelFactory cf; private final String remoteHost; private final int remotePort; private volatile Channel outboundChannel; public HexDumpProxyInboundHandler( ClientSocketChannelFactory cf, String remoteHost, int remotePort) { this.cf = cf; this.remoteHost = remoteHost; this.remotePort = remotePort; } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Suspend incoming traffic until connected to the remote host. final Channel inboundChannel = e.getChannel(); inboundChannel.setReadable(false); // Start the connection attempt. ClientBootstrap cb = new ClientBootstrap(cf); cb.getPipeline().addLast("handler", new OutboundHandler(e.getChannel())); ChannelFuture f = cb.connect(new InetSocketAddress(remoteHost, remotePort)); outboundChannel = f.getChannel(); f.addListener(new ChannelFutureListener() { public void operationComplete(ChannelFuture future) throws Exception { if (future.isSuccess()) { // Connection attempt succeeded: // Begin to accept incoming traffic. inboundChannel.setReadable(true); } else { // Close the connection if the connection attempt has failed. inboundChannel.close(); } } }); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer msg = (ChannelBuffer) e.getMessage(); System.out.println(">>> " + ChannelBuffers.hexDump(msg)); outboundChannel.write(msg); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { if (outboundChannel != null) { outboundChannel.close(); } } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { e.getCause().printStackTrace(); e.getChannel().close(); } @ChannelPipelineCoverage("one") private class OutboundHandler extends SimpleChannelUpstreamHandler { private final Channel inboundChannel; OutboundHandler(Channel inboundChannel) { this.inboundChannel = inboundChannel; } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) throws Exception { ChannelBuffer msg = (ChannelBuffer) e.getMessage(); System.out.println("<<< " + ChannelBuffers.hexDump(msg)); inboundChannel.write(msg); } @Override public void channelClosed(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { inboundChannel.close(); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) throws Exception { e.getCause().printStackTrace(); e.getChannel().close(); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/telnet/0000755000175000017500000000000011316313144025514 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/telnet/TelnetServer.java0000644000175000017500000000433511050275327031013 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.telnet; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * Simplistic telnet server. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class TelnetServer { public static void main(String[] args) throws Exception { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); TelnetServerHandler handler = new TelnetServerHandler(); bootstrap.setPipelineFactory(new TelnetPipelineFactory(handler)); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/telnet/TelnetClient.java0000644000175000017500000001017211211705313030747 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.telnet; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; /** * Simplistic telnet client. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1327 $, $Date: 2009-06-04 01:50:19 -0700 (Thu, 04 Jun 2009) $ */ public class TelnetClient { public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length != 2) { System.err.println( "Usage: " + TelnetClient.class.getSimpleName() + " "); return; } // Parse options. String host = args[0]; int port = Integer.parseInt(args[1]); // Configure the client. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); TelnetClientHandler handler = new TelnetClientHandler(); bootstrap.setPipelineFactory(new TelnetPipelineFactory(handler)); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection attempt succeeds or fails. Channel channel = future.awaitUninterruptibly().getChannel(); if (!future.isSuccess()) { future.getCause().printStackTrace(); factory.releaseExternalResources(); return; } // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (;;) { String line = in.readLine(); if (line == null) { break; } // Sends the received line to the server. lastWriteFuture = channel.write(line + '\n'); // If user typed the 'bye' command, wait until the server closes // the connection. if (line.toLowerCase().equals("bye")) { channel.getCloseFuture().awaitUninterruptibly(); break; } } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.awaitUninterruptibly(); } // Close the connection. Make sure the close operation ends because // all I/O operations are asynchronous in Netty. channel.close().awaitUninterruptibly(); // Shut down all thread pools to exit. factory.releaseExternalResources(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/telnet/TelnetServerHandler.java0000644000175000017500000000776311172030314032307 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.telnet; import java.net.InetAddress; import java.util.Date; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelFutureListener; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handles a server-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class TelnetServerHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( TelnetServerHandler.class.getName()); @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Send greeting for a new connection. e.getChannel().write( "Welcome to " + InetAddress.getLocalHost().getHostName() + "!\r\n"); e.getChannel().write("It is " + new Date() + " now.\r\n"); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { // Cast to a String first. // We know it is a String because we put some codec in TelnetPipelineFactory. String request = (String) e.getMessage(); // Generate and write a response. String response; boolean close = false; if (request.length() == 0) { response = "Please type something.\r\n"; } else if (request.toLowerCase().equals("bye")) { response = "Have a good day!\r\n"; close = true; } else { response = "Did you say '" + request + "'?\r\n"; } // We do not need to write a ChannelBuffer here. // We know the encoder inserted at TelnetPipelineFactory will do the conversion. ChannelFuture future = e.getChannel().write(response); // Close the connection after sending 'Have a good day!' // if the client has sent 'bye'. if (close) { future.addListener(ChannelFutureListener.CLOSE); } } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/telnet/TelnetPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/telnet/TelnetPipelineFactory.java0000644000175000017500000000477511050275327032652 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.telnet; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelHandler; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.frame.DelimiterBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.Delimiters; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * Creates a newly configured {@link ChannelPipeline} for a new channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ * */ public class TelnetPipelineFactory implements ChannelPipelineFactory { private final ChannelHandler handler; public TelnetPipelineFactory(ChannelHandler handler) { this.handler = handler; } public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); // Add the text line codec combination first, pipeline.addLast("framer", new DelimiterBasedFrameDecoder( 8192, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); // and then business logic. pipeline.addLast("handler", handler); return pipeline; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/telnet/TelnetClientHandler.java0000644000175000017500000000516711172030314032253 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.telnet; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handles a client-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class TelnetClientHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( TelnetClientHandler.class.getName()); @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { // Print out the line received from the server. System.err.println(e.getMessage()); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/0000755000175000017500000000000011316313143026171 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeServer.java0000644000175000017500000000440511131030655032076 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.localtime; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * Receives a list of continent/city pairs from a {@link LocalTimeClient} to * get the local times of the specified cities. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 643 $, $Date: 2009-01-06 20:38:05 -0800 (Tue, 06 Jan 2009) $ */ public class LocalTimeServer { public static void main(String[] args) throws Exception { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); bootstrap.setPipelineFactory(new LocalTimeServerPipelineFactory()); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientHandler.0000644000175000017500000001143111172030314032474 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.localtime; import java.util.ArrayList; import java.util.Collection; import java.util.Formatter; import java.util.List; import java.util.concurrent.BlockingQueue; import java.util.concurrent.LinkedBlockingQueue; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.example.localtime.LocalTimeProtocol.Continent; import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime; import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes; import org.jboss.netty.example.localtime.LocalTimeProtocol.Location; import org.jboss.netty.example.localtime.LocalTimeProtocol.Locations; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("one") public class LocalTimeClientHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( LocalTimeClientHandler.class.getName()); // Stateful properties private volatile Channel channel; private final BlockingQueue answer = new LinkedBlockingQueue(); public List getLocalTimes(Collection cities) { Locations.Builder builder = Locations.newBuilder(); for (String c: cities) { String[] components = c.split("/"); builder.addLocation(Location.newBuilder(). setContinent(Continent.valueOf(components[0].toUpperCase())). setCity(components[1]).build()); } channel.write(builder.build()); LocalTimes localTimes; for (;;) { try { localTimes = answer.take(); break; } catch (InterruptedException e) { // Ignore. } } List result = new ArrayList(); for (LocalTime lt: localTimes.getLocalTimeList()) { result.add( new Formatter().format( "%4d-%02d-%02d %02d:%02d:%02d %s", lt.getYear(), lt.getMonth(), lt.getDayOfMonth(), lt.getHour(), lt.getMinute(), lt.getSecond(), lt.getDayOfWeek().name()).toString()); } return result; } @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { channel = e.getChannel(); super.channelOpen(ctx, e); } @Override public void messageReceived( ChannelHandlerContext ctx, final MessageEvent e) { boolean offered = answer.offer((LocalTimes) e.getMessage()); assert offered; } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.java0000644000175000017500000017222511131244325032440 0ustar deckerdecker// Generated by the protocol buffer compiler. DO NOT EDIT! package org.jboss.netty.example.localtime; @SuppressWarnings("all") public final class LocalTimeProtocol { private LocalTimeProtocol() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public static enum Continent { AFRICA(0, 0), AMERICA(1, 1), ANTARCTICA(2, 2), ARCTIC(3, 3), ASIA(4, 4), ATLANTIC(5, 5), AUSTRALIA(6, 6), EUROPE(7, 7), INDIAN(8, 8), MIDEAST(9, 9), PACIFIC(10, 10), ; public final int getNumber() { return value; } public static Continent valueOf(int value) { switch (value) { case 0: return AFRICA; case 1: return AMERICA; case 2: return ANTARCTICA; case 3: return ARCTIC; case 4: return ASIA; case 5: return ATLANTIC; case 6: return AUSTRALIA; case 7: return EUROPE; case 8: return INDIAN; case 9: return MIDEAST; case 10: return PACIFIC; default: return null; } } public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor().getEnumTypes().get(0); } private static final Continent[] VALUES = { AFRICA, AMERICA, ANTARCTICA, ARCTIC, ASIA, ATLANTIC, AUSTRALIA, EUROPE, INDIAN, MIDEAST, PACIFIC, }; public static Continent valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private Continent(int index, int value) { this.index = index; this.value = value; } static { org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor(); } } public static enum DayOfWeek { SUNDAY(0, 1), MONDAY(1, 2), TUESDAY(2, 3), WEDNESDAY(3, 4), THURSDAY(4, 5), FRIDAY(5, 6), SATURDAY(6, 7), ; public final int getNumber() { return value; } public static DayOfWeek valueOf(int value) { switch (value) { case 1: return SUNDAY; case 2: return MONDAY; case 3: return TUESDAY; case 4: return WEDNESDAY; case 5: return THURSDAY; case 6: return FRIDAY; case 7: return SATURDAY; default: return null; } } public final com.google.protobuf.Descriptors.EnumValueDescriptor getValueDescriptor() { return getDescriptor().getValues().get(index); } public final com.google.protobuf.Descriptors.EnumDescriptor getDescriptorForType() { return getDescriptor(); } public static final com.google.protobuf.Descriptors.EnumDescriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor().getEnumTypes().get(1); } private static final DayOfWeek[] VALUES = { SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, }; public static DayOfWeek valueOf( com.google.protobuf.Descriptors.EnumValueDescriptor desc) { if (desc.getType() != getDescriptor()) { throw new java.lang.IllegalArgumentException( "EnumValueDescriptor is not for this type."); } return VALUES[desc.getIndex()]; } private final int index; private final int value; private DayOfWeek(int index, int value) { this.index = index; this.value = value; } static { org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor(); } } public static final class Location extends com.google.protobuf.GeneratedMessage { // Use Location.newBuilder() to construct. private Location() {} private static final Location defaultInstance = new Location(); public static Location getDefaultInstance() { return defaultInstance; } public Location getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_descriptor; } @Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable; } // required .org.jboss.netty.example.localtime.Continent continent = 1; private boolean hasContinent; private org.jboss.netty.example.localtime.LocalTimeProtocol.Continent continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; public boolean hasContinent() { return hasContinent; } public org.jboss.netty.example.localtime.LocalTimeProtocol.Continent getContinent() { return continent_; } // required string city = 2; private boolean hasCity; private java.lang.String city_ = ""; public boolean hasCity() { return hasCity; } public java.lang.String getCity() { return city_; } @Override public final boolean isInitialized() { if (!hasContinent) { return false; } if (!hasCity) { return false; } return true; } @Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (hasContinent()) { output.writeEnum(1, getContinent().getNumber()); } if (hasCity()) { output.writeString(2, getCity()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; @Override public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; if (hasContinent()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(1, getContinent().getNumber()); } if (hasCity()) { size += com.google.protobuf.CodedOutputStream .computeStringSize(2, getCity()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( byte[] data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Location parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return new Builder(); } public Builder newBuilderForType() { return new Builder(); } public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.Location prototype) { return new Builder().mergeFrom(prototype); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder { // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.Location.newBuilder() private Builder() {} org.jboss.netty.example.localtime.LocalTimeProtocol.Location result = new org.jboss.netty.example.localtime.LocalTimeProtocol.Location(); @Override protected org.jboss.netty.example.localtime.LocalTimeProtocol.Location internalGetResult() { return result; } @Override public Builder clear() { result = new org.jboss.netty.example.localtime.LocalTimeProtocol.Location(); return this; } @Override public Builder clone() { return new Builder().mergeFrom(result); } @Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDescriptor(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Location getDefaultInstanceForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Location build() { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result); } return buildPartial(); } private org.jboss.netty.example.localtime.LocalTimeProtocol.Location buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Location buildPartial() { org.jboss.netty.example.localtime.LocalTimeProtocol.Location returnMe = result; result = null; return returnMe; } @Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.Location) { return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.Location)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.Location other) { if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.Location.getDefaultInstance()) { return this; } if (other.hasContinent()) { setContinent(other.getContinent()); } if (other.hasCity()) { setCity(other.getCity()); } mergeUnknownFields(other.getUnknownFields()); return this; } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return mergeFrom(input, com.google.protobuf.ExtensionRegistry.getEmptyRegistry()); } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { setUnknownFields(unknownFields.build()); return this; } break; } case 8: { int rawValue = input.readEnum(); org.jboss.netty.example.localtime.LocalTimeProtocol.Continent value = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(1, rawValue); } else { setContinent(value); } break; } case 18: { setCity(input.readString()); break; } } } } // required .org.jboss.netty.example.localtime.Continent continent = 1; public boolean hasContinent() { return result.hasContinent(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Continent getContinent() { return result.getContinent(); } public Builder setContinent(org.jboss.netty.example.localtime.LocalTimeProtocol.Continent value) { result.hasContinent = true; result.continent_ = value; return this; } public Builder clearContinent() { result.hasContinent = false; result.continent_ = org.jboss.netty.example.localtime.LocalTimeProtocol.Continent.AFRICA; return this; } // required string city = 2; public boolean hasCity() { return result.hasCity(); } public java.lang.String getCity() { return result.getCity(); } public Builder setCity(java.lang.String value) { result.hasCity = true; result.city_ = value; return this; } public Builder clearCity() { result.hasCity = false; result.city_ = ""; return this; } } static { org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor(); } } public static final class Locations extends com.google.protobuf.GeneratedMessage { // Use Locations.newBuilder() to construct. private Locations() {} private static final Locations defaultInstance = new Locations(); public static Locations getDefaultInstance() { return defaultInstance; } public Locations getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_descriptor; } @Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable; } // repeated .org.jboss.netty.example.localtime.Location location = 1; private java.util.List location_ = java.util.Collections.emptyList(); public java.util.List getLocationList() { return location_; } public int getLocationCount() { return location_.size(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Location getLocation(int index) { return location_.get(index); } @Override public final boolean isInitialized() { for (org.jboss.netty.example.localtime.LocalTimeProtocol.Location element : getLocationList()) { if (!element.isInitialized()) { return false; } } return true; } @Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (org.jboss.netty.example.localtime.LocalTimeProtocol.Location element : getLocationList()) { output.writeMessage(1, element); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; @Override public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; for (org.jboss.netty.example.localtime.LocalTimeProtocol.Location element : getLocationList()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, element); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( byte[] data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.Locations parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return new Builder(); } public Builder newBuilderForType() { return new Builder(); } public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.Locations prototype) { return new Builder().mergeFrom(prototype); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder { // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.newBuilder() private Builder() {} org.jboss.netty.example.localtime.LocalTimeProtocol.Locations result = new org.jboss.netty.example.localtime.LocalTimeProtocol.Locations(); @Override protected org.jboss.netty.example.localtime.LocalTimeProtocol.Locations internalGetResult() { return result; } @Override public Builder clear() { result = new org.jboss.netty.example.localtime.LocalTimeProtocol.Locations(); return this; } @Override public Builder clone() { return new Builder().mergeFrom(result); } @Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.getDescriptor(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Locations getDefaultInstanceForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.getDefaultInstance(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Locations build() { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result); } return buildPartial(); } private org.jboss.netty.example.localtime.LocalTimeProtocol.Locations buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Locations buildPartial() { if (result.location_ != java.util.Collections.EMPTY_LIST) { result.location_ = java.util.Collections.unmodifiableList(result.location_); } org.jboss.netty.example.localtime.LocalTimeProtocol.Locations returnMe = result; result = null; return returnMe; } @Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.Locations) { return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.Locations)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.Locations other) { if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.getDefaultInstance()) { return this; } if (!other.location_.isEmpty()) { if (result.location_.isEmpty()) { result.location_ = new java.util.ArrayList(); } result.location_.addAll(other.location_); } mergeUnknownFields(other.getUnknownFields()); return this; } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return mergeFrom(input, com.google.protobuf.ExtensionRegistry.getEmptyRegistry()); } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { setUnknownFields(unknownFields.build()); return this; } break; } case 10: { org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder subBuilder = org.jboss.netty.example.localtime.LocalTimeProtocol.Location.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addLocation(subBuilder.buildPartial()); break; } } } } // repeated .org.jboss.netty.example.localtime.Location location = 1; public java.util.List getLocationList() { return java.util.Collections.unmodifiableList(result.location_); } public int getLocationCount() { return result.getLocationCount(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.Location getLocation(int index) { return result.getLocation(index); } public Builder setLocation(int index, org.jboss.netty.example.localtime.LocalTimeProtocol.Location value) { result.location_.set(index, value); return this; } public Builder setLocation(int index, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder builderForValue) { result.location_.set(index, builderForValue.build()); return this; } public Builder addLocation(org.jboss.netty.example.localtime.LocalTimeProtocol.Location value) { if (result.location_.isEmpty()) { result.location_ = new java.util.ArrayList(); } result.location_.add(value); return this; } public Builder addLocation(org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder builderForValue) { if (result.location_.isEmpty()) { result.location_ = new java.util.ArrayList(); } result.location_.add(builderForValue.build()); return this; } public Builder addAllLocation( java.lang.Iterable values) { if (result.location_.isEmpty()) { result.location_ = new java.util.ArrayList(); } super.addAll(values, result.location_); return this; } public Builder clearLocation() { result.location_ = java.util.Collections.emptyList(); return this; } } static { org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor(); } } public static final class LocalTime extends com.google.protobuf.GeneratedMessage { // Use LocalTime.newBuilder() to construct. private LocalTime() {} private static final LocalTime defaultInstance = new LocalTime(); public static LocalTime getDefaultInstance() { return defaultInstance; } public LocalTime getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor; } @Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable; } // required uint32 year = 1; private boolean hasYear; private int year_ = 0; public boolean hasYear() { return hasYear; } public int getYear() { return year_; } // required uint32 month = 2; private boolean hasMonth; private int month_ = 0; public boolean hasMonth() { return hasMonth; } public int getMonth() { return month_; } // required uint32 dayOfMonth = 4; private boolean hasDayOfMonth; private int dayOfMonth_ = 0; public boolean hasDayOfMonth() { return hasDayOfMonth; } public int getDayOfMonth() { return dayOfMonth_; } // required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; private boolean hasDayOfWeek; private org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; public boolean hasDayOfWeek() { return hasDayOfWeek; } public org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek getDayOfWeek() { return dayOfWeek_; } // required uint32 hour = 6; private boolean hasHour; private int hour_ = 0; public boolean hasHour() { return hasHour; } public int getHour() { return hour_; } // required uint32 minute = 7; private boolean hasMinute; private int minute_ = 0; public boolean hasMinute() { return hasMinute; } public int getMinute() { return minute_; } // required uint32 second = 8; private boolean hasSecond; private int second_ = 0; public boolean hasSecond() { return hasSecond; } public int getSecond() { return second_; } @Override public final boolean isInitialized() { if (!hasYear) { return false; } if (!hasMonth) { return false; } if (!hasDayOfMonth) { return false; } if (!hasDayOfWeek) { return false; } if (!hasHour) { return false; } if (!hasMinute) { return false; } if (!hasSecond) { return false; } return true; } @Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { if (hasYear()) { output.writeUInt32(1, getYear()); } if (hasMonth()) { output.writeUInt32(2, getMonth()); } if (hasDayOfMonth()) { output.writeUInt32(4, getDayOfMonth()); } if (hasDayOfWeek()) { output.writeEnum(5, getDayOfWeek().getNumber()); } if (hasHour()) { output.writeUInt32(6, getHour()); } if (hasMinute()) { output.writeUInt32(7, getMinute()); } if (hasSecond()) { output.writeUInt32(8, getSecond()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; @Override public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; if (hasYear()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(1, getYear()); } if (hasMonth()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(2, getMonth()); } if (hasDayOfMonth()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(4, getDayOfMonth()); } if (hasDayOfWeek()) { size += com.google.protobuf.CodedOutputStream .computeEnumSize(5, getDayOfWeek().getNumber()); } if (hasHour()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(6, getHour()); } if (hasMinute()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(7, getMinute()); } if (hasSecond()) { size += com.google.protobuf.CodedOutputStream .computeUInt32Size(8, getSecond()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( byte[] data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return new Builder(); } public Builder newBuilderForType() { return new Builder(); } public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime prototype) { return new Builder().mergeFrom(prototype); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder { // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.newBuilder() private Builder() {} org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime result = new org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime(); @Override protected org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime internalGetResult() { return result; } @Override public Builder clear() { result = new org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime(); return this; } @Override public Builder clone() { return new Builder().mergeFrom(result); } @Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDescriptor(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getDefaultInstanceForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime build() { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result); } return buildPartial(); } private org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime buildPartial() { org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime returnMe = result; result = null; return returnMe; } @Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime) { return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime other) { if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.getDefaultInstance()) { return this; } if (other.hasYear()) { setYear(other.getYear()); } if (other.hasMonth()) { setMonth(other.getMonth()); } if (other.hasDayOfMonth()) { setDayOfMonth(other.getDayOfMonth()); } if (other.hasDayOfWeek()) { setDayOfWeek(other.getDayOfWeek()); } if (other.hasHour()) { setHour(other.getHour()); } if (other.hasMinute()) { setMinute(other.getMinute()); } if (other.hasSecond()) { setSecond(other.getSecond()); } mergeUnknownFields(other.getUnknownFields()); return this; } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return mergeFrom(input, com.google.protobuf.ExtensionRegistry.getEmptyRegistry()); } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { setUnknownFields(unknownFields.build()); return this; } break; } case 8: { setYear(input.readUInt32()); break; } case 16: { setMonth(input.readUInt32()); break; } case 32: { setDayOfMonth(input.readUInt32()); break; } case 40: { int rawValue = input.readEnum(); org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek value = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.valueOf(rawValue); if (value == null) { unknownFields.mergeVarintField(5, rawValue); } else { setDayOfWeek(value); } break; } case 48: { setHour(input.readUInt32()); break; } case 56: { setMinute(input.readUInt32()); break; } case 64: { setSecond(input.readUInt32()); break; } } } } // required uint32 year = 1; public boolean hasYear() { return result.hasYear(); } public int getYear() { return result.getYear(); } public Builder setYear(int value) { result.hasYear = true; result.year_ = value; return this; } public Builder clearYear() { result.hasYear = false; result.year_ = 0; return this; } // required uint32 month = 2; public boolean hasMonth() { return result.hasMonth(); } public int getMonth() { return result.getMonth(); } public Builder setMonth(int value) { result.hasMonth = true; result.month_ = value; return this; } public Builder clearMonth() { result.hasMonth = false; result.month_ = 0; return this; } // required uint32 dayOfMonth = 4; public boolean hasDayOfMonth() { return result.hasDayOfMonth(); } public int getDayOfMonth() { return result.getDayOfMonth(); } public Builder setDayOfMonth(int value) { result.hasDayOfMonth = true; result.dayOfMonth_ = value; return this; } public Builder clearDayOfMonth() { result.hasDayOfMonth = false; result.dayOfMonth_ = 0; return this; } // required .org.jboss.netty.example.localtime.DayOfWeek dayOfWeek = 5; public boolean hasDayOfWeek() { return result.hasDayOfWeek(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek getDayOfWeek() { return result.getDayOfWeek(); } public Builder setDayOfWeek(org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek value) { result.hasDayOfWeek = true; result.dayOfWeek_ = value; return this; } public Builder clearDayOfWeek() { result.hasDayOfWeek = false; result.dayOfWeek_ = org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek.SUNDAY; return this; } // required uint32 hour = 6; public boolean hasHour() { return result.hasHour(); } public int getHour() { return result.getHour(); } public Builder setHour(int value) { result.hasHour = true; result.hour_ = value; return this; } public Builder clearHour() { result.hasHour = false; result.hour_ = 0; return this; } // required uint32 minute = 7; public boolean hasMinute() { return result.hasMinute(); } public int getMinute() { return result.getMinute(); } public Builder setMinute(int value) { result.hasMinute = true; result.minute_ = value; return this; } public Builder clearMinute() { result.hasMinute = false; result.minute_ = 0; return this; } // required uint32 second = 8; public boolean hasSecond() { return result.hasSecond(); } public int getSecond() { return result.getSecond(); } public Builder setSecond(int value) { result.hasSecond = true; result.second_ = value; return this; } public Builder clearSecond() { result.hasSecond = false; result.second_ = 0; return this; } } static { org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor(); } } public static final class LocalTimes extends com.google.protobuf.GeneratedMessage { // Use LocalTimes.newBuilder() to construct. private LocalTimes() {} private static final LocalTimes defaultInstance = new LocalTimes(); public static LocalTimes getDefaultInstance() { return defaultInstance; } public LocalTimes getDefaultInstanceForType() { return defaultInstance; } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor; } @Override protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.jboss.netty.example.localtime.LocalTimeProtocol.internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable; } // repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; private java.util.List localTime_ = java.util.Collections.emptyList(); public java.util.List getLocalTimeList() { return localTime_; } public int getLocalTimeCount() { return localTime_.size(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getLocalTime(int index) { return localTime_.get(index); } @Override public final boolean isInitialized() { for (org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime element : getLocalTimeList()) { if (!element.isInitialized()) { return false; } } return true; } @Override public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { for (org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime element : getLocalTimeList()) { output.writeMessage(1, element); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; @Override public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) { return size; } size = 0; for (org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime element : getLocalTimeList()) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, element); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( byte[] data, com.google.protobuf.ExtensionRegistry extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return newBuilder().mergeFrom(data, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom(java.io.InputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return newBuilder().mergeFrom(input).buildParsed(); } public static org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { return newBuilder().mergeFrom(input, extensionRegistry) .buildParsed(); } public static Builder newBuilder() { return new Builder(); } public Builder newBuilderForType() { return new Builder(); } public static Builder newBuilder(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes prototype) { return new Builder().mergeFrom(prototype); } public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder { // Construct using org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.newBuilder() private Builder() {} org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes result = new org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes(); @Override protected org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes internalGetResult() { return result; } @Override public Builder clear() { result = new org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes(); return this; } @Override public Builder clone() { return new Builder().mergeFrom(result); } @Override public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.getDescriptor(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes getDefaultInstanceForType() { return org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.getDefaultInstance(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes build() { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result); } return buildPartial(); } private org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes buildParsed() throws com.google.protobuf.InvalidProtocolBufferException { if (!isInitialized()) { throw new com.google.protobuf.UninitializedMessageException( result).asInvalidProtocolBufferException(); } return buildPartial(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes buildPartial() { if (result.localTime_ != java.util.Collections.EMPTY_LIST) { result.localTime_ = java.util.Collections.unmodifiableList(result.localTime_); } org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes returnMe = result; result = null; return returnMe; } @Override public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes) { return mergeFrom((org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes other) { if (other == org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.getDefaultInstance()) { return this; } if (!other.localTime_.isEmpty()) { if (result.localTime_.isEmpty()) { result.localTime_ = new java.util.ArrayList(); } result.localTime_.addAll(other.localTime_); } mergeUnknownFields(other.getUnknownFields()); return this; } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return mergeFrom(input, com.google.protobuf.ExtensionRegistry.getEmptyRegistry()); } @Override public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistry extensionRegistry) throws java.io.IOException { com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder( getUnknownFields()); while (true) { int tag = input.readTag(); switch (tag) { case 0: setUnknownFields(unknownFields.build()); return this; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { setUnknownFields(unknownFields.build()); return this; } break; } case 10: { org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder subBuilder = org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.newBuilder(); input.readMessage(subBuilder, extensionRegistry); addLocalTime(subBuilder.buildPartial()); break; } } } } // repeated .org.jboss.netty.example.localtime.LocalTime localTime = 1; public java.util.List getLocalTimeList() { return java.util.Collections.unmodifiableList(result.localTime_); } public int getLocalTimeCount() { return result.getLocalTimeCount(); } public org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime getLocalTime(int index) { return result.getLocalTime(index); } public Builder setLocalTime(int index, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime value) { result.localTime_.set(index, value); return this; } public Builder setLocalTime(int index, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder builderForValue) { result.localTime_.set(index, builderForValue.build()); return this; } public Builder addLocalTime(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime value) { if (result.localTime_.isEmpty()) { result.localTime_ = new java.util.ArrayList(); } result.localTime_.add(value); return this; } public Builder addLocalTime(org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder builderForValue) { if (result.localTime_.isEmpty()) { result.localTime_ = new java.util.ArrayList(); } result.localTime_.add(builderForValue.build()); return this; } public Builder addAllLocalTime( java.lang.Iterable values) { if (result.localTime_.isEmpty()) { result.localTime_ = new java.util.ArrayList(); } super.addAll(values, result.localTime_); return this; } public Builder clearLocalTime() { result.localTime_ = java.util.Collections.emptyList(); return this; } } static { org.jboss.netty.example.localtime.LocalTimeProtocol.getDescriptor(); } } private static com.google.protobuf.Descriptors.Descriptor internal_static_org_jboss_netty_example_localtime_Location_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_org_jboss_netty_example_localtime_Locations_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable; private static com.google.protobuf.Descriptors.Descriptor internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String descriptorData = "\n\027LocalTimeProtocol.proto\022!org.jboss.net" + "ty.example.localtime\"Y\n\010Location\022?\n\tcont" + "inent\030\001 \002(\0162,.org.jboss.netty.example.lo" + "caltime.Continent\022\014\n\004city\030\002 \002(\t\"J\n\tLocat" + "ions\022=\n\010location\030\001 \003(\0132+.org.jboss.netty" + ".example.localtime.Location\"\253\001\n\tLocalTim" + "e\022\014\n\004year\030\001 \002(\r\022\r\n\005month\030\002 \002(\r\022\022\n\ndayOfM" + "onth\030\004 \002(\r\022?\n\tdayOfWeek\030\005 \002(\0162,.org.jbos" + "s.netty.example.localtime.DayOfWeek\022\014\n\004h" + "our\030\006 \002(\r\022\016\n\006minute\030\007 \002(\r\022\016\n\006second\030\010 \002(" + "\r\"M\n\nLocalTimes\022?\n\tlocalTime\030\001 \003(\0132,.org" + ".jboss.netty.example.localtime.LocalTime" + "*\231\001\n\tContinent\022\n\n\006AFRICA\020\000\022\013\n\007AMERICA\020\001\022" + "\016\n\nANTARCTICA\020\002\022\n\n\006ARCTIC\020\003\022\010\n\004ASIA\020\004\022\014\n" + "\010ATLANTIC\020\005\022\r\n\tAUSTRALIA\020\006\022\n\n\006EUROPE\020\007\022\n" + "\n\006INDIAN\020\010\022\013\n\007MIDEAST\020\t\022\013\n\007PACIFIC\020\n*g\n\t" + "DayOfWeek\022\n\n\006SUNDAY\020\001\022\n\n\006MONDAY\020\002\022\013\n\007TUE" + "SDAY\020\003\022\r\n\tWEDNESDAY\020\004\022\014\n\010THURSDAY\020\005\022\n\n\006F" + "RIDAY\020\006\022\014\n\010SATURDAY\020\007B\002H\001"; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; internal_static_org_jboss_netty_example_localtime_Location_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_org_jboss_netty_example_localtime_Location_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_Location_descriptor, new java.lang.String[] { "Continent", "City", }, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.class, org.jboss.netty.example.localtime.LocalTimeProtocol.Location.Builder.class); internal_static_org_jboss_netty_example_localtime_Locations_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_org_jboss_netty_example_localtime_Locations_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_Locations_descriptor, new java.lang.String[] { "Location", }, org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.class, org.jboss.netty.example.localtime.LocalTimeProtocol.Locations.Builder.class); internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_org_jboss_netty_example_localtime_LocalTime_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_LocalTime_descriptor, new java.lang.String[] { "Year", "Month", "DayOfMonth", "DayOfWeek", "Hour", "Minute", "Second", }, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.class, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime.Builder.class); internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor = getDescriptor().getMessageTypes().get(3); internal_static_org_jboss_netty_example_localtime_LocalTimes_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_org_jboss_netty_example_localtime_LocalTimes_descriptor, new java.lang.String[] { "LocalTime", }, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.class, org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes.Builder.class); return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { }, assigner); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeClient.java0000644000175000017500000001066011131030655032046 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.localtime; import java.net.InetSocketAddress; import java.util.ArrayList; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; /** * Sends a list of continent/city pairs to a {@link LocalTimeServer} to * get the local times of the specified cities. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 643 $, $Date: 2009-01-06 20:38:05 -0800 (Tue, 06 Jan 2009) $ */ public class LocalTimeClient { public static void main(String[] args) throws Exception { // Print usage if necessary. if (args.length < 3) { printUsage(); return; } // Parse options. String host = args[0]; int port = Integer.parseInt(args[1]); Collection cities = parseCities(args, 2); if (cities == null) { return; } // Set up. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); bootstrap.setPipelineFactory(new LocalTimeClientPipelineFactory()); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); // Make a new connection. ChannelFuture connectFuture = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection is made successfully. Channel channel = connectFuture.awaitUninterruptibly().getChannel(); // Get the handler instance to initiate the request. LocalTimeClientHandler handler = channel.getPipeline().get(LocalTimeClientHandler.class); // Request and get the response. List response = handler.getLocalTimes(cities); // Close the connection. channel.close().awaitUninterruptibly(); // Shut down all thread pools to exit. factory.releaseExternalResources(); // Print the response at last but not least. Iterator i1 = cities.iterator(); Iterator i2 = response.iterator(); while (i1.hasNext()) { System.out.format("%28s: %s%n", i1.next(), i2.next()); } } private static void printUsage() { System.err.println( "Usage: " + LocalTimeClient.class.getSimpleName() + " ..."); System.err.println( "Example: " + LocalTimeClient.class.getSimpleName() + " localhost 8080 America/New_York Asia/Seoul"); } private static List parseCities(String[] args, int offset) { List cities = new ArrayList(); for (int i = offset; i < args.length; i ++) { if (!args[i].matches("^[_A-Za-z]+/[_A-Za-z]+$")) { System.err.println("Syntax error: '" + args[i] + "'"); printUsage(); return null; } cities.add(args[i].trim()); } return cities; } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.protolibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeProtocol.proto0000644000175000017500000000346111131030655032654 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.localtime; option optimize_for = SPEED; enum Continent { AFRICA = 0; AMERICA = 1; ANTARCTICA = 2; ARCTIC = 3; ASIA = 4; ATLANTIC = 5; AUSTRALIA = 6; EUROPE = 7; INDIAN = 8; MIDEAST = 9; PACIFIC = 10; } message Location { required Continent continent = 1; required string city = 2; } message Locations { repeated Location location = 1; } enum DayOfWeek { SUNDAY = 1; MONDAY = 2; TUESDAY = 3; WEDNESDAY = 4; THURSDAY = 5; FRIDAY = 6; SATURDAY = 7; } message LocalTime { required uint32 year = 1; required uint32 month = 2; required uint32 dayOfMonth = 4; required DayOfWeek dayOfWeek = 5; required uint32 hour = 6; required uint32 minute = 7; required uint32 second = 8; } message LocalTimes { repeated LocalTime localTime = 1; } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerPipeline0000644000175000017500000000432111131030655032641 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.localtime; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 643 $, $Date: 2009-01-06 20:38:05 -0800 (Tue, 06 Jan 2009) $ */ public class LocalTimeServerPipelineFactory implements ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline p = pipeline(); p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); p.addLast("protobufDecoder", new ProtobufDecoder(LocalTimeProtocol.Locations.getDefaultInstance())); p.addLast("frameEncoder", new LengthFieldPrepender(4)); p.addLast("protobufEncoder", new ProtobufEncoder()); p.addLast("handler", new LocalTimeServerHandler()); return p; } } ././@LongLink0000000000000000000000000000015100000000000011562 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeServerHandler.0000644000175000017500000001013611172030314032525 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.localtime; import static java.util.Calendar.*; import java.util.Calendar; import java.util.TimeZone; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.example.localtime.LocalTimeProtocol.Continent; import org.jboss.netty.example.localtime.LocalTimeProtocol.DayOfWeek; import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTime; import org.jboss.netty.example.localtime.LocalTimeProtocol.LocalTimes; import org.jboss.netty.example.localtime.LocalTimeProtocol.Location; import org.jboss.netty.example.localtime.LocalTimeProtocol.Locations; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class LocalTimeServerHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( LocalTimeServerHandler.class.getName()); @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { Locations locations = (Locations) e.getMessage(); long currentTime = System.currentTimeMillis(); LocalTimes.Builder builder = LocalTimes.newBuilder(); for (Location l: locations.getLocationList()) { TimeZone tz = TimeZone.getTimeZone( toString(l.getContinent()) + '/' + l.getCity()); Calendar calendar = Calendar.getInstance(tz); calendar.setTimeInMillis(currentTime); builder.addLocalTime(LocalTime.newBuilder(). setYear(calendar.get(YEAR)). setMonth(calendar.get(MONTH) + 1). setDayOfMonth(calendar.get(DAY_OF_MONTH)). setDayOfWeek(DayOfWeek.valueOf(calendar.get(DAY_OF_WEEK))). setHour(calendar.get(HOUR_OF_DAY)). setMinute(calendar.get(MINUTE)). setSecond(calendar.get(SECOND)).build()); } e.getChannel().write(builder.build()); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } private static String toString(Continent c) { return "" + c.name().charAt(0) + c.name().toLowerCase().substring(1); } } ././@LongLink0000000000000000000000000000016100000000000011563 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientPipelineFactory.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/localtime/LocalTimeClientPipeline0000644000175000017500000000432211131030655032612 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.localtime; import static org.jboss.netty.channel.Channels.*; import org.jboss.netty.channel.ChannelPipeline; import org.jboss.netty.channel.ChannelPipelineFactory; import org.jboss.netty.handler.codec.frame.LengthFieldBasedFrameDecoder; import org.jboss.netty.handler.codec.frame.LengthFieldPrepender; import org.jboss.netty.handler.codec.protobuf.ProtobufDecoder; import org.jboss.netty.handler.codec.protobuf.ProtobufEncoder; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * @version $Rev: 643 $, $Date: 2009-01-06 20:38:05 -0800 (Tue, 06 Jan 2009) $ */ public class LocalTimeClientPipelineFactory implements ChannelPipelineFactory { public ChannelPipeline getPipeline() throws Exception { ChannelPipeline p = pipeline(); p.addLast("frameDecoder", new LengthFieldBasedFrameDecoder(1048576, 0, 4, 0, 4)); p.addLast("protobufDecoder", new ProtobufDecoder(LocalTimeProtocol.LocalTimes.getDefaultInstance())); p.addLast("frameEncoder", new LengthFieldPrepender(4)); p.addLast("protobufEncoder", new ProtobufEncoder()); p.addLast("handler", new LocalTimeClientHandler()); return p; } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/echo/0000755000175000017500000000000011316313144025137 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/echo/EchoClient.java0000644000175000017500000000617311113752132030025 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.echo; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; /** * Sends one message when a connection is open and echoes back any received * data to the server. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 537 $, $Date: 2008-11-28 03:22:02 -0800 (Fri, 28 Nov 2008) $ * */ public class EchoClient { public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length < 2 || args.length > 3) { System.err.println( "Usage: " + EchoClient.class.getSimpleName() + " []"); return; } // Parse options. String host = args[0]; int port = Integer.parseInt(args[1]); int firstMessageSize; if (args.length == 3) { firstMessageSize = Integer.parseInt(args[2]); } else { firstMessageSize = 256; } // Configure the client. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); EchoHandler handler = new EchoHandler(firstMessageSize); bootstrap.getPipeline().addLast("handler", handler); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection is closed or the connection attempt fails. future.getChannel().getCloseFuture().awaitUninterruptibly(); // Shut down thread pools to exit. factory.releaseExternalResources(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/echo/EchoServer.java0000644000175000017500000000445111050275327030060 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.echo; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * Echoes back any received data from a client. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ * */ public class EchoServer { public static void main(String[] args) throws Exception { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); EchoHandler handler = new EchoHandler(); bootstrap.getPipeline().addLast("handler", handler); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); // Start performance monitor. new ThroughputMonitor(handler).start(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/echo/ThroughputMonitor.java0000644000175000017500000000422211104723515031525 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.echo; /** * Measures and prints the current throughput every 3 seconds. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 442 $, $Date: 2008-11-06 18:26:21 -0800 (Thu, 06 Nov 2008) $ */ public class ThroughputMonitor extends Thread { private final EchoHandler handler; public ThroughputMonitor(EchoHandler handler) { this.handler = handler; } @Override public void run() { long oldCounter = handler.getTransferredBytes(); long startTime = System.currentTimeMillis(); for (;;) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); long newCounter = handler.getTransferredBytes(); System.err.format( "%4.3f MiB/s%n", (newCounter - oldCounter) * 1000.0 / (endTime - startTime) / 1048576.0); oldCounter = newCounter; startTime = endTime; } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/echo/EchoHandler.java0000644000175000017500000001010611172030314030147 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.echo; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handles both client-side and server-side handler depending on which * constructor was called. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class EchoHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( EchoHandler.class.getName()); private final ChannelBuffer firstMessage; private final AtomicLong transferredBytes = new AtomicLong(); /** * Creates a server-side handler. */ public EchoHandler() { firstMessage = ChannelBuffers.EMPTY_BUFFER; } /** * Creates a client-side handler. */ public EchoHandler(int firstMessageSize) { if (firstMessageSize <= 0) { throw new IllegalArgumentException( "firstMessageSize: " + firstMessageSize); } firstMessage = ChannelBuffers.buffer(firstMessageSize); for (int i = 0; i < firstMessage.capacity(); i ++) { firstMessage.writeByte((byte) i); } } public long getTransferredBytes() { return transferredBytes.get(); } @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } // Let SimpleChannelHandler call actual event handler methods below. super.handleUpstream(ctx, e); } @Override public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) { // Send the first message. Server will not send anything here // because the firstMessage's capacity is 0. e.getChannel().write(firstMessage); } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { // Send back the received message to the remote peer. transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes()); e.getChannel().write(e.getMessage()); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/local/0000755000175000017500000000000011316313143025312 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/local/LocalExample.java0000644000175000017500000001065511216747541030546 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2009, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.local; import java.io.BufferedReader; import java.io.InputStreamReader; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelDownstreamHandler; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelUpstreamHandler; import org.jboss.netty.channel.local.DefaultLocalClientChannelFactory; import org.jboss.netty.channel.local.DefaultLocalServerChannelFactory; import org.jboss.netty.channel.local.LocalAddress; import org.jboss.netty.example.echo.EchoHandler; import org.jboss.netty.handler.codec.string.StringDecoder; import org.jboss.netty.handler.codec.string.StringEncoder; /** * @author The Netty Project (netty-dev@lists.jboss.org) * @author Andy Taylor (andy.taylor@jboss.org) * @version $Rev: 1482 $, $Date: 2009-06-19 10:48:17 -0700 (Fri, 19 Jun 2009) $ */ public class LocalExample { public static void main(String[] args) throws Exception { ChannelFactory factory = new DefaultLocalServerChannelFactory(); ServerBootstrap bootstrap = new ServerBootstrap(factory); EchoHandler handler = new EchoHandler(); LocalAddress socketAddress = new LocalAddress("1"); bootstrap.getPipeline().addLast("handler", handler); bootstrap.bind(socketAddress); ChannelFactory channelFactory = new DefaultLocalClientChannelFactory(); ClientBootstrap clientBootstrap = new ClientBootstrap(channelFactory); clientBootstrap.getPipeline().addLast("decoder", new StringDecoder()); clientBootstrap.getPipeline().addLast("encoder", new StringEncoder()); clientBootstrap.getPipeline().addLast("handler", new PrintHandler()); ChannelFuture channelFuture = clientBootstrap.connect(socketAddress); channelFuture.awaitUninterruptibly(); System.out.println("Enter text (quit to end)"); // Read commands from the stdin. ChannelFuture lastWriteFuture = null; BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); for (; ;) { String line = in.readLine(); if (line == null || "quit".equalsIgnoreCase(line)) { break; } // Sends the received line to the server. lastWriteFuture = channelFuture.getChannel().write(line); } // Wait until all messages are flushed before closing the channel. if (lastWriteFuture != null) { lastWriteFuture.awaitUninterruptibly(); } channelFuture.getChannel().close(); // Wait until the connection is closed or the connection attempt fails. channelFuture.getChannel().getCloseFuture().awaitUninterruptibly(); } @ChannelPipelineCoverage("all") static class PrintHandler implements ChannelUpstreamHandler, ChannelDownstreamHandler { public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { System.err.println(e); ctx.sendUpstream(e); } public void handleDownstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { System.err.println(e); ctx.sendDownstream(e); } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/objectecho/0000755000175000017500000000000011316313142026324 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoClient.java0000644000175000017500000000572611050275327032354 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.objectecho; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; import org.jboss.netty.example.echo.EchoClient; /** * Modification of {@link EchoClient} which utilizes Java object serialization. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class ObjectEchoClient { public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length < 2 || args.length > 3) { System.err.println( "Usage: " + ObjectEchoClient.class.getSimpleName() + " []"); return; } // Parse options. String host = args[0]; int port = Integer.parseInt(args[1]); int firstMessageSize; if (args.length == 3) { firstMessageSize = Integer.parseInt(args[2]); } else { firstMessageSize = 256; } // Configure the client. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); ObjectEchoHandler handler = new ObjectEchoHandler(firstMessageSize); bootstrap.getPipeline().addLast("handler", handler); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); // Start the connection attempt. bootstrap.connect(new InetSocketAddress(host, port)); // Start performance monitor. new ThroughputMonitor(handler).start(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoServer.java0000644000175000017500000000461611050275327032401 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.objectecho; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; import org.jboss.netty.example.echo.EchoServer; /** * Modification of {@link EchoServer} which utilizes Java object serialization. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class ObjectEchoServer { public static void main(String[] args) throws Exception { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); ObjectEchoHandler handler = new ObjectEchoHandler(); bootstrap.getPipeline().addLast("handler", handler); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); // Start performance monitor. new ThroughputMonitor(handler).start(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/objectecho/ObjectEchoHandler.java0000644000175000017500000001106311172030314032470 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.objectecho; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; import org.jboss.netty.handler.codec.serialization.ObjectDecoder; import org.jboss.netty.handler.codec.serialization.ObjectEncoder; /** * Handles both client-side and server-side handler depending on which * constructor was called. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class ObjectEchoHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( ObjectEchoHandler.class.getName()); private final List firstMessage; private final AtomicLong transferredMessages = new AtomicLong(); /** * Creates a server-side handler. */ public ObjectEchoHandler() { firstMessage = new ArrayList(); } /** * Creates a client-side handler. */ public ObjectEchoHandler(int firstMessageSize) { if (firstMessageSize <= 0) { throw new IllegalArgumentException( "firstMessageSize: " + firstMessageSize); } firstMessage = new ArrayList(firstMessageSize); for (int i = 0; i < firstMessageSize; i ++) { firstMessage.add(Integer.valueOf(i)); } } public long getTransferredMessages() { return transferredMessages.get(); } @Override public void handleUpstream( ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent && ((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) { logger.info(e.toString()); } super.handleUpstream(ctx, e); } @Override public void channelOpen(ChannelHandlerContext ctx, ChannelStateEvent e) throws Exception { // Add encoder and decoder as soon as a new channel is created so that // a Java object is serialized and deserialized. e.getChannel().getPipeline().addFirst("encoder", new ObjectEncoder()); e.getChannel().getPipeline().addFirst("decoder", new ObjectDecoder()); } @Override public void channelConnected( ChannelHandlerContext ctx, ChannelStateEvent e) { // Send the first message if this handler is a client-side handler. if (!firstMessage.isEmpty()) { e.getChannel().write(firstMessage); } } @Override public void messageReceived( ChannelHandlerContext ctx, MessageEvent e) { // Echo back the received object to the client. transferredMessages.incrementAndGet(); e.getChannel().write(e.getMessage()); } @Override public void exceptionCaught( ChannelHandlerContext ctx, ExceptionEvent e) { logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/objectecho/ThroughputMonitor.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/objectecho/ThroughputMonitor.java0000644000175000017500000000422111050275327032716 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.objectecho; /** * Measures and prints the current throughput every 3 seconds. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 55 $, $Date: 2008-08-12 04:58:15 -0700 (Tue, 12 Aug 2008) $ */ public class ThroughputMonitor extends Thread { private final ObjectEchoHandler handler; public ThroughputMonitor(ObjectEchoHandler handler) { this.handler = handler; } @Override public void run() { long oldCounter = handler.getTransferredMessages(); long startTime = System.currentTimeMillis(); for (;;) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); long newCounter = handler.getTransferredMessages(); System.err.format( "%4.3f msgs/s%n", (newCounter - oldCounter) * 1000 / (double) (endTime - startTime)); oldCounter = newCounter; startTime = endTime; } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/0000755000175000017500000000000011316313143025631 5ustar deckerdecker././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/DiscardServerHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/DiscardServerHandler.java0000644000175000017500000000600111172030314032523 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.discard; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handles a server-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class DiscardServerHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( DiscardServerHandler.class.getName()); private final AtomicLong transferredBytes = new AtomicLong(); public long getTransferredBytes() { return transferredBytes.get(); } @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { logger.info(e.toString()); } // Let SimpleChannelHandler call actual event handler methods below. super.handleUpstream(ctx, e); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Discard received data silently by doing nothing. transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/ThroughputMonitor.java0000644000175000017500000000424711104723515032227 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.discard; /** * Measures and prints the current throughput every 3 seconds. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 442 $, $Date: 2008-11-06 18:26:21 -0800 (Thu, 06 Nov 2008) $ */ public class ThroughputMonitor extends Thread { private final DiscardServerHandler handler; public ThroughputMonitor(DiscardServerHandler handler) { this.handler = handler; } @Override public void run() { long oldCounter = handler.getTransferredBytes(); long startTime = System.currentTimeMillis(); for (;;) { try { Thread.sleep(3000); } catch (InterruptedException e) { e.printStackTrace(); } long endTime = System.currentTimeMillis(); long newCounter = handler.getTransferredBytes(); System.err.format( "%4.3f MiB/s%n", (newCounter - oldCounter) * 1000.0 / (endTime - startTime) / 1048576.0); oldCounter = newCounter; startTime = endTime; } } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/DiscardClient.java0000644000175000017500000000650211131115327031206 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.discard; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ClientBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.ChannelFuture; import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory; /** * Keeps sending random data to the specified address. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 647 $, $Date: 2009-01-07 04:06:47 -0800 (Wed, 07 Jan 2009) $ */ public class DiscardClient { public static void main(String[] args) throws Exception { // Print usage if no argument is specified. if (args.length < 2 || args.length > 3) { System.err.println( "Usage: " + DiscardClient.class.getSimpleName() + " []"); return; } // Parse options. String host = args[0]; int port = Integer.parseInt(args[1]); int firstMessageSize; if (args.length == 3) { firstMessageSize = Integer.parseInt(args[2]); } else { firstMessageSize = 256; } // Configure the client. ChannelFactory factory = new NioClientSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ClientBootstrap bootstrap = new ClientBootstrap(factory); DiscardClientHandler handler = new DiscardClientHandler(firstMessageSize); //bootstrap.getPipeline().addLast("executor", new ExecutionHandler(new OrderedMemoryAwareThreadPoolExecutor(16, 0, 0))); bootstrap.getPipeline().addLast("handler", handler); bootstrap.setOption("tcpNoDelay", true); bootstrap.setOption("keepAlive", true); //bootstrap.setOption("bufferFactory", DirectChannelBufferFactory.getInstance()); // Start the connection attempt. ChannelFuture future = bootstrap.connect(new InetSocketAddress(host, port)); // Wait until the connection is closed or the connection attempt fails. future.getChannel().getCloseFuture().awaitUninterruptibly(); // Shut down thread pools to exit. factory.releaseExternalResources(); } } ././@LongLink0000000000000000000000000000014500000000000011565 Lustar rootrootlibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/DiscardClientHandler.javalibnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/DiscardClientHandler.java0000644000175000017500000001103211172030314032473 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.discard; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import org.jboss.netty.buffer.ChannelBuffer; import org.jboss.netty.buffer.ChannelBuffers; import org.jboss.netty.channel.Channel; import org.jboss.netty.channel.ChannelEvent; import org.jboss.netty.channel.ChannelHandlerContext; import org.jboss.netty.channel.ChannelPipelineCoverage; import org.jboss.netty.channel.ChannelState; import org.jboss.netty.channel.ChannelStateEvent; import org.jboss.netty.channel.ExceptionEvent; import org.jboss.netty.channel.MessageEvent; import org.jboss.netty.channel.SimpleChannelUpstreamHandler; /** * Handles a client-side channel. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 1211 $, $Date: 2009-04-17 00:33:32 -0700 (Fri, 17 Apr 2009) $ */ @ChannelPipelineCoverage("all") public class DiscardClientHandler extends SimpleChannelUpstreamHandler { private static final Logger logger = Logger.getLogger( DiscardClientHandler.class.getName()); private final AtomicLong transferredBytes = new AtomicLong(); private final byte[] content; public DiscardClientHandler(int messageSize) { if (messageSize <= 0) { throw new IllegalArgumentException( "messageSize: " + messageSize); } content = new byte[messageSize]; } public long getTransferredBytes() { return transferredBytes.get(); } @Override public void handleUpstream(ChannelHandlerContext ctx, ChannelEvent e) throws Exception { if (e instanceof ChannelStateEvent) { if (((ChannelStateEvent) e).getState() != ChannelState.INTEREST_OPS) { logger.info(e.toString()); } } // Let SimpleChannelHandler call actual event handler methods below. super.handleUpstream(ctx, e); } @Override public void channelConnected(ChannelHandlerContext ctx, ChannelStateEvent e) { // Send the initial messages. generateTraffic(e); } @Override public void channelInterestChanged(ChannelHandlerContext ctx, ChannelStateEvent e) { // Keep sending messages whenever the current socket buffer has room. generateTraffic(e); } @Override public void messageReceived(ChannelHandlerContext ctx, MessageEvent e) { // Server is supposed to send nothing. Therefore, do nothing. transferredBytes.addAndGet(((ChannelBuffer) e.getMessage()).readableBytes()); } @Override public void exceptionCaught(ChannelHandlerContext ctx, ExceptionEvent e) { // Close the connection when an exception is raised. logger.log( Level.WARNING, "Unexpected exception from downstream.", e.getCause()); e.getChannel().close(); } private void generateTraffic(ChannelStateEvent e) { // Keep generating traffic until the channel is unwritable. // A channel becomes unwritable when its internal buffer is full. // If you keep writing messages ignoring this property, // you will end up with an OutOfMemoryError. Channel channel = e.getChannel(); while (channel.isWritable()) { ChannelBuffer m = nextMessage(); if (m == null) { break; } channel.write(m); } } private ChannelBuffer nextMessage() { return ChannelBuffers.wrappedBuffer(content); } } libnetty-java-3.1.0.CR1.orig/src/main/java/org/jboss/netty/example/discard/DiscardServer.java0000644000175000017500000000461611131115327031242 0ustar deckerdecker/* * JBoss, Home of Professional Open Source * * Copyright 2008, Red Hat Middleware LLC, and individual contributors * by the @author tags. See the COPYRIGHT.txt in the distribution for a * full listing of individual contributors. * * This 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 software 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 software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.netty.example.discard; import java.net.InetSocketAddress; import java.util.concurrent.Executors; import org.jboss.netty.bootstrap.ServerBootstrap; import org.jboss.netty.channel.ChannelFactory; import org.jboss.netty.channel.socket.nio.NioServerSocketChannelFactory; /** * Discards any incoming data. * * @author The Netty Project (netty-dev@lists.jboss.org) * @author Trustin Lee (tlee@redhat.com) * * @version $Rev: 647 $, $Date: 2009-01-07 04:06:47 -0800 (Wed, 07 Jan 2009) $ */ public class DiscardServer { public static void main(String[] args) throws Exception { // Configure the server. ChannelFactory factory = new NioServerSocketChannelFactory( Executors.newCachedThreadPool(), Executors.newCachedThreadPool()); ServerBootstrap bootstrap = new ServerBootstrap(factory); DiscardServerHandler handler = new DiscardServerHandler(); bootstrap.getPipeline().addLast("handler", handler); bootstrap.setOption("child.tcpNoDelay", true); bootstrap.setOption("child.keepAlive", true); //bootstrap.setOption("child.bufferFactory", DirectChannelBufferFactory.getInstance()); // Bind and start to accept incoming connections. bootstrap.bind(new InetSocketAddress(8080)); // Start performance monitor. new ThroughputMonitor(handler).start(); } } libnetty-java-3.1.0.CR1.orig/src/main/resources/0000755000175000017500000000000011316313154020606 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/resources/org/0000755000175000017500000000000011316313154021375 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/resources/org/jboss/0000755000175000017500000000000011316313154022515 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/resources/org/jboss/netty/0000755000175000017500000000000011316313154023660 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/resources/org/jboss/netty/container/0000755000175000017500000000000011316313154025642 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/resources/org/jboss/netty/container/spring/0000755000175000017500000000000011316313154027144 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/resources/org/jboss/netty/container/spring/beans.xml0000644000175000017500000001131511216400752030757 0ustar deckerdecker libnetty-java-3.1.0.CR1.orig/src/main/resources/META-INF/0000755000175000017500000000000011316313154021746 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/main/resources/META-INF/jboss-beans.xml0000644000175000017500000001273411216400677024713 0ustar deckerdecker org.jboss.netty.internal.ResourceFactory org.jboss.netty.channel.socket.ClientSocketChannelFactory org.jboss.netty.internal.ChannelFactoryExecutor org.jboss.netty.channel.socket.ServerSocketChannelFactory org.jboss.netty.internal.ChannelFactoryExecutor org.jboss.netty.internal.ChannelFactoryExecutor org.jboss.netty.internal.ChannelFactoryExecutor org.jboss.netty.internal.ChannelFactoryExecutor org.jboss.netty.channel.socket.DatagramChannelFactory org.jboss.netty.internal.ChannelFactoryExecutor org.jboss.netty.channel.local.LocalClientChannelFactory org.jboss.netty.channel.local.LocalServerChannelFactory libnetty-java-3.1.0.CR1.orig/src/xref/0000755000175000017500000000000011316313154016614 5ustar deckerdeckerlibnetty-java-3.1.0.CR1.orig/src/xref/stylesheet.css0000644000175000017500000000442611216745563021541 0ustar deckerdecker* { font-family: "Lucida Grande", Geneva, Verdana, "Liberation Sans", Helvetica, Arial, sans-serif; } body { background-color: #FFFFFF; color:#000000; font-size: 10pt; } a:link {color:#0033cc;} a:visited {color:#0044cc;} tt, tt *, pre, pre *, code, code * { font-family: "Liberation Mono", "DejaVu Sans Mono", Consolas, Monaco, "Lucida Console", "Courier New", monospace; } /* Headings */ h1, h2, h3, h4, h5, h6 { color:#4a5d75; line-height:130%; margin-top:0em; font-family:'Lucida Grande', Geneva, Verdana, Arial, sans-serif; background-color:transparent; } h1 { font-size:2em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h2 { font-size:1.6em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h3 { font-size:1.3em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h4 { font-size:1.1em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } h5 { font-size:1em; padding: 0em; margin: 0.8em 0em 0.35em 0em; } ul, li { list-style-type:none; margin:0; padding:0; } table td { padding: 3px; border: 1px solid #000; } table { width:100%; border: 1px solid #000; border-collapse: collapse; } div.overview { background-color:#ddd; padding: 4px 4px 4px 0; } div.overview li, div.framenoframe li { display: inline; } div.framenoframe { text-align: center; font-size: x-small; } div.framenoframe li { margin: 0 3px 0 3px; } div.overview li { margin:3px 3px 0 3px; padding: 4px; } li.selected { background-color:#888; color: #fff; font-weight: bold; } table.summary { margin-bottom: 20px; } table.summary td, table.summary th { font-weight: bold; text-align: left; padding: 3px; } table.summary th { background-color:#CCCCFF; color: #000; } table.summary td { background-color:#fff; border: 1px solid black; } em { color: rgb(63, 63, 191); font-style: normal; } em.comment { color: rgb(63, 127, 95); font-style: normal; } .string { color: rgb(42, 0, 255); } div#footer { text-align:center; } #overview { padding:2px; } hr { height: 1px; color: #000; } .jxr_comment { color: rgb(63, 127, 95); font-style: normal; } .jxr_javadoccomment { color: rgb(63, 63, 191); font-style: normal; } .jxr_string { color: rgb(42, 0, 255); } .jxr_keyword { color: rgb(127, 0, 85); font-weight: bold; } libnetty-java-3.1.0.CR1.orig/.gitignore0000644000175000017500000000006711133755537017070 0ustar deckerdecker # / /.project /.classpath /.settings /target /reports