pax_global_header00006660000000000000000000000064123600160210014501gustar00rootroot0000000000000052 comment=fbc352181e2df76ebaa562f3254efc7766e6ece7 jzmq-3.1.0/000077500000000000000000000000001236001602100124635ustar00rootroot00000000000000jzmq-3.1.0/.gitignore000066400000000000000000000027251236001602100144610ustar00rootroot00000000000000Makefile.in perf/Makefile.in src/Makefile.in Makefile aclocal.m4 autom4te.cache autoscan.log configure config.log config.status configure.scan libtool *.stamp stamp-* *.class .deps .libs *.la *.o *.lo *~ src/main/c++/config.hpp.in src/main/c++/config.hpp src/main/c++/org_zeromq_*.h lib/ target/ .classpath .project .settings/ build-stamp configure-stamp builds/msvc/msvc.ncb builds/msvc/msvc.suo builds/msvc/jzmq/jzmq.vcproj.* builds/msvc/local_lat/local_lat.vcproj.* builds/msvc/local_thr/local_thr.vcproj.* builds/msvc/remote_lat/remote_lat.vcproj.* builds/msvc/remote_thr/remote_thr.vcproj.* builds/msvc/jzmq/Debug/ builds/msvc/local_lat/Debug/ builds/msvc/local_thr/Debug/ builds/msvc/remote_lat/Debug/ builds/msvc/remote_thr/Debug/ builds/msvc/jzmq/Release/ builds/msvc/local_lat/Release/ builds/msvc/local_thr/Release/ builds/msvc/remote_lat/Release/ builds/msvc/remote_thr/Release/ debian/files debian/jzmq.debhelper.log debian/jzmq.postinst.debhelper debian/jzmq.postrm.debhelper debian/jzmq.substvars debian/jzmq/ debian/tmp/ .DS_Store *.iml config/ build/ builds/msvc/Debug/ builds/msvc/Release/ builds/msvc/UpgradeLog.XML builds/msvc/_UpgradeReport_Files/ builds/msvc/jzmq/*.dll builds/msvc/jzmq/jzmq.vcxproj* builds/msvc/msvc.sdf builds/msvc/*.lib builds/msvc/*.dll builds/msvc/local_lat/local_lat.vcxproj* builds/msvc/local_thr/local_thr.vcxproj* builds/msvc/remote_lat/remote_lat.vcxproj* builds/msvc/remote_thr/remote_thr.vcxproj* perf/*.dll \#* .\#* *.jar INSTALL .checkstyle jzmq-3.1.0/.travis.yml000066400000000000000000000010641236001602100145750ustar00rootroot00000000000000before_install: - sudo add-apt-repository ppa:trevorbernard/zeromq -y - sudo apt-get update -y - sudo apt-get install libzmq3-dev libpgm-dev make build-essential pkg-config libtool automake -y - git clone git://github.com/jedisct1/libsodium.git - cd libsodium - git checkout 0.4.5 - ./autogen.sh - ./configure && make check - sudo make install - sudo ldconfig - cd .. - ./autogen.sh - ./configure - make - sudo make install install: mvn install --quiet -DskipTests=true -Dgpg.skip=true language: java script: mvn test jdk: - openjdk6 - openjdk7 jzmq-3.1.0/AUTHORS000066400000000000000000000013621236001602100135350ustar00rootroot00000000000000Contributors ============ Alexej Lotz Asko Kauppi Barak Amar Bernd Prager Chris Wong Conrad D. Steenberg Dhruva Krishnamurthy Dirk O. Kaar Erich Heine Erik Rigtorp Frank Denis George Neill Gonzalo Diethelm Joe Thornber Jon Dyte Kamil Shakirov Martin Hurton Martin Lucina Martin Sustrik Matus Hamorsky McClain Looney Pavel Gushcha Pavol Malosek Steven McCoy Tamara Kustarova Tero Marttila Terry Wilson Trevor Bernard Vitaly Mayatskikh Chris Busbey Credits ======= Aamir Mohammad Aleksey Yeschenko Alexander Majorov Bernd Schumacher Brett Cameron Brian Granger Carsten Dinkelmann David Bahi Dirk Eddelbuettel Evgueny Khartchenko Frank Vanden Berghen John Apps Markus Fischer Matt Muggeridge Paulo Henrique Silva Peter Busser Peter Lemenkov Robert Zhang jzmq-3.1.0/CMakeLists.txt000066400000000000000000000136401236001602100152270ustar00rootroot00000000000000# CMake build script for ØMQ Java bindings on Windows cmake_minimum_required (VERSION 2.8) project (JZMQ) find_package (Java REQUIRED) find_package (JNI REQUIRED) find_program (JNI_JAVAH NAMES javah HINTS ${_JAVA_HINTS} PATHS ${_JAVA_PATHS} ) #----------------------------------------------------------------------------- # force off-tree build if(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) message(FATAL_ERROR "CMake generation is not allowed within the source directory! Remove the CMakeCache.txt file and try again from another folder, e.g.: del CMakeCache.txt mkdir build cd build cmake .. ") endif(${CMAKE_SOURCE_DIR} STREQUAL ${CMAKE_BINARY_DIR}) #----------------------------------------------------------------------------- # default to Release build if(NOT CMAKE_BUILD_TYPE) set(CMAKE_BUILD_TYPE Release CACHE STRING "Choose the type of build, options are: None Debug Release RelWithDebInfo MinSizeRel." FORCE) endif(NOT CMAKE_BUILD_TYPE) set(EXECUTABLE_OUTPUT_PATH ${CMAKE_BINARY_DIR}/bin) set(LIBRARY_OUTPUT_PATH ${CMAKE_BINARY_DIR}/lib) #----------------------------------------------------------------------------- # platform specifics add_definitions( -DWIN32 -DDLL_EXPORT -DFD_SETSIZE=1024 ) #----------------------------------------------------------------------------- # source files set(java-sources org/zeromq/ZMQ.java org/zeromq/ZMQException.java org/zeromq/ZMQForwarder.java org/zeromq/ZMQQueue.java org/zeromq/ZMQStreamer.java org/zeromq/EmbeddedLibraryTools.java org/zeromq/App.java org/zeromq/ZContext.java org/zeromq/ZDispatcher.java org/zeromq/ZFrame.java org/zeromq/ZMsg.java org/zeromq/ZLoop.java org/zeromq/ZThread.java ) set(java-classes org/zeromq/ZMQ.class org/zeromq/ZMQ$$Context.class org/zeromq/ZMQ$$Socket.class org/zeromq/ZMQ$$PollItem.class org/zeromq/ZMQ$$Poller.class org/zeromq/ZMQ$$Error.class org/zeromq/ZMQException.class org/zeromq/ZMQQueue.class org/zeromq/ZMQForwarder.class org/zeromq/ZMQStreamer.class org/zeromq/EmbeddedLibraryTools.class org/zeromq/App.class org/zeromq/ZContext.class org/zeromq/ZDispatcher.class org/zeromq/ZDispatcher$$1.class org/zeromq/ZDispatcher$$SocketDispatcher$$1.class org/zeromq/ZDispatcher$$SocketDispatcher$$2.class org/zeromq/ZDispatcher$$SocketDispatcher$$ZMessageBuffer.class org/zeromq/ZDispatcher$$SocketDispatcher.class org/zeromq/ZDispatcher$$ZMessageHandler.class org/zeromq/ZDispatcher$$ZSender.class org/zeromq/ZFrame.class org/zeromq/ZMsg.class org/zeromq/ZLoop.class org/zeromq/ZLoop$$IZLoopHandler.class org/zeromq/ZLoop$$SPoller.class org/zeromq/ZLoop$$STimer.class org/zeromq/ZThread.class org/zeromq/ZThread$$IAttachedRunnable.class org/zeromq/ZThread$$IDetachedRunnable.class org/zeromq/ZThread$$ShimThread.class ) set(javah-headers org_zeromq_ZMQ.h org_zeromq_ZMQ_Error.h org_zeromq_ZMQ_Context.h org_zeromq_ZMQ_Socket.h org_zeromq_ZMQ_PollItem.h org_zeromq_ZMQ_Poller.h ) set(cxx-sources Context.cpp Poller.cpp Socket.cpp util.cpp ZMQ.cpp ) include_directories( src src/main/java ${CMAKE_CURRENT_BINARY_DIR} ) #----------------------------------------------------------------------------- # optional modules add_definitions( -DZMQ_HAVE_OPENPGM ) include_directories( # /zeromq/zeromq-2.1.10/include # c:/zeromq/zeromq-3.3.0/include c:/zeromq/zeromq-3.2.2/include ${JNI_INCLUDE_DIRS} ) link_directories( # /zeromq/zeromq-2.1.10/build/lib # /zeromq/zeromq-2.1.10/build64/lib # c:/zeromq/zeromq-3.3.0/lib c:/zeromq/zeromq-3.2.2/lib ) #----------------------------------------------------------------------------- # source generators foreach (source ${cxx-sources}) list(APPEND sources ${CMAKE_CURRENT_SOURCE_DIR}/src/main/c++/${source}) endforeach() add_custom_command( OUTPUT ${CMAKE_CURRENT_BINARY_DIR}/config.hpp COMMAND ${CMAKE_COMMAND} ARGS -E copy ${CMAKE_CURRENT_SOURCE_DIR}/builds/msvc/config.hpp ${CMAKE_CURRENT_BINARY_DIR}/config.hpp DEPENDS ${CMAKE_CURRENT_SOURCE_DIR}/builds/msvc/config.hpp ) list(APPEND sources ${CMAKE_CURRENT_BINARY_DIR}/config.hpp) add_custom_command( OUTPUT ${javah-headers} COMMAND ${JNI_JAVAH} ARGS -jni -classpath ${CMAKE_CURRENT_BINARY_DIR} org.zeromq.ZMQ WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${java-classes} ) list(APPEND sources ${javah-headers}) set (source-tmp "") foreach (source ${java-sources}) list (APPEND source-tmp ${CMAKE_CURRENT_SOURCE_DIR}/src/main/java/${source}) endforeach() set (java-sources ${source-tmp}) add_custom_command( OUTPUT ${java-classes} COMMAND ${JAVA_COMPILE} ARGS -classpath ${CMAKE_CURRENT_BINARY_DIR} -sourcepath ${CMAKE_CURRENT_SOURCE_DIR}/src/main/java -d ${CMAKE_CURRENT_BINARY_DIR} ${java-sources} DEPENDS ${java-sources} ) add_custom_command( OUTPUT lib/zmq.jar COMMAND ${JAVA_ARCHIVE} ARGS cf lib/zmq.jar ${java-classes} WORKING_DIRECTORY ${CMAKE_CURRENT_BINARY_DIR} DEPENDS ${java-classes} ) list(APPEND sources lib/zmq.jar) #----------------------------------------------------------------------------- # output add_library(jzmq SHARED ${sources}) target_link_libraries(jzmq libzmq.lib) set(docs AUTHORS COPYING COPYING.LESSER ChangeLog INSTALL NEWS README README-PERF ) install (TARGETS jzmq DESTINATION lib) install (FILES ${CMAKE_CURRENT_BINARY_DIR}/lib/zmq.jar DESTINATION lib) install (FILES ${docs} DESTINATION doc) # By default, do not warn when built on machines using only VS Express: IF(NOT DEFINED CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS) SET(CMAKE_INSTALL_SYSTEM_RUNTIME_LIBS_NO_WARNINGS ON) ENDIF() include (InstallRequiredSystemLibraries) set (CPACK_PACKAGE_VENDOR "Miru Limited") set (CPACK_RESOURCE_FILE_LICENSE "${CMAKE_CURRENT_SOURCE_DIR}/COPYING") #set (CPACK_PACKAGE_VERSION_MAJOR "2") #set (CPACK_PACKAGE_VERSION_MINOR "1") #set (CPACK_PACKAGE_VERSION_PATCH "10") set (CPACK_PACKAGE_VERSION_MAJOR "3") set (CPACK_PACKAGE_VERSION_MINOR "2") set (CPACK_PACKAGE_VERSION_PATCH "2") include (CPack) # end of file jzmq-3.1.0/COPYING000066400000000000000000001045151236001602100135240ustar00rootroot00000000000000 GNU GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. Preamble The GNU General Public License is a free, copyleft license for software and other kinds of works. The licenses for most software and other practical works are designed to take away your freedom to share and change the works. By contrast, the GNU General Public License is intended to guarantee your freedom to share and change all versions of a program--to make sure it remains free software for all its users. We, the Free Software Foundation, use the GNU General Public License for most of our software; it applies also to any other work released this way by its authors. You can apply it to your programs, too. When we speak of free software, we are referring to freedom, 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 them if you wish), that you receive source code or can get it if you want it, that you can change the software or use pieces of it in new free programs, and that you know you can do these things. To protect your rights, we need to prevent others from denying you these rights or asking you to surrender the rights. Therefore, you have certain responsibilities if you distribute copies of the software, or if you modify it: responsibilities to respect the freedom of others. For example, if you distribute copies of such a program, whether gratis or for a fee, you must pass on to the recipients the same freedoms that you received. You must make sure that they, too, receive or can get the source code. And you must show them these terms so they know their rights. Developers that use the GNU GPL protect your rights with two steps: (1) assert copyright on the software, and (2) offer you this License giving you legal permission to copy, distribute and/or modify it. For the developers' and authors' protection, the GPL clearly explains that there is no warranty for this free software. For both users' and authors' sake, the GPL requires that modified versions be marked as changed, so that their problems will not be attributed erroneously to authors of previous versions. Some devices are designed to deny users access to install or run modified versions of the software inside them, although the manufacturer can do so. This is fundamentally incompatible with the aim of protecting users' freedom to change the software. The systematic pattern of such abuse occurs in the area of products for individuals to use, which is precisely where it is most unacceptable. Therefore, we have designed this version of the GPL to prohibit the practice for those products. If such problems arise substantially in other domains, we stand ready to extend this provision to those domains in future versions of the GPL, as needed to protect the freedom of users. Finally, every program is threatened constantly by software patents. States should not allow patents to restrict development and use of software on general-purpose computers, but in those that do, we wish to avoid the special danger that patents applied to a free program could make it effectively proprietary. To prevent this, the GPL assures that patents cannot be used to render the program non-free. The precise terms and conditions for copying, distribution and modification follow. TERMS AND CONDITIONS 0. Definitions. "This License" refers to version 3 of the GNU General Public License. "Copyright" also means copyright-like laws that apply to other kinds of works, such as semiconductor masks. "The Program" refers to any copyrightable work licensed under this License. Each licensee is addressed as "you". "Licensees" and "recipients" may be individuals or organizations. To "modify" a work means to copy from or adapt all or part of the work in a fashion requiring copyright permission, other than the making of an exact copy. The resulting work is called a "modified version" of the earlier work or a work "based on" the earlier work. A "covered work" means either the unmodified Program or a work based on the Program. To "propagate" a work means to do anything with it that, without permission, would make you directly or secondarily liable for infringement under applicable copyright law, except executing it on a computer or modifying a private copy. Propagation includes copying, distribution (with or without modification), making available to the public, and in some countries other activities as well. To "convey" a work means any kind of propagation that enables other parties to make or receive copies. Mere interaction with a user through a computer network, with no transfer of a copy, is not conveying. An interactive user interface displays "Appropriate Legal Notices" to the extent that it includes a convenient and prominently visible feature that (1) displays an appropriate copyright notice, and (2) tells the user that there is no warranty for the work (except to the extent that warranties are provided), that licensees may convey the work under this License, and how to view a copy of this License. If the interface presents a list of user commands or options, such as a menu, a prominent item in the list meets this criterion. 1. Source Code. The "source code" for a work means the preferred form of the work for making modifications to it. "Object code" means any non-source form of a work. A "Standard Interface" means an interface that either is an official standard defined by a recognized standards body, or, in the case of interfaces specified for a particular programming language, one that is widely used among developers working in that language. The "System Libraries" of an executable work include anything, other than the work as a whole, that (a) is included in the normal form of packaging a Major Component, but which is not part of that Major Component, and (b) serves only to enable use of the work with that Major Component, or to implement a Standard Interface for which an implementation is available to the public in source code form. A "Major Component", in this context, means a major essential component (kernel, window system, and so on) of the specific operating system (if any) on which the executable work runs, or a compiler used to produce the work, or an object code interpreter used to run it. The "Corresponding Source" for a work in object code form means all the source code needed to generate, install, and (for an executable work) run the object code and to modify the work, including scripts to control those activities. However, it does not include the work's System Libraries, or general-purpose tools or generally available free programs which are used unmodified in performing those activities but which are not part of the work. For example, Corresponding Source includes interface definition files associated with source files for the work, and the source code for shared libraries and dynamically linked subprograms that the work is specifically designed to require, such as by intimate data communication or control flow between those subprograms and other parts of the work. The Corresponding Source need not include anything that users can regenerate automatically from other parts of the Corresponding Source. The Corresponding Source for a work in source code form is that same work. 2. Basic Permissions. All rights granted under this License are granted for the term of copyright on the Program, and are irrevocable provided the stated conditions are met. This License explicitly affirms your unlimited permission to run the unmodified Program. The output from running a covered work is covered by this License only if the output, given its content, constitutes a covered work. This License acknowledges your rights of fair use or other equivalent, as provided by copyright law. You may make, run and propagate covered works that you do not convey, without conditions so long as your license otherwise remains in force. You may convey covered works to others for the sole purpose of having them make modifications exclusively for you, or provide you with facilities for running those works, provided that you comply with the terms of this License in conveying all material for which you do not control copyright. Those thus making or running the covered works for you must do so exclusively on your behalf, under your direction and control, on terms that prohibit them from making any copies of your copyrighted material outside their relationship with you. Conveying under any other circumstances is permitted solely under the conditions stated below. Sublicensing is not allowed; section 10 makes it unnecessary. 3. Protecting Users' Legal Rights From Anti-Circumvention Law. No covered work shall be deemed part of an effective technological measure under any applicable law fulfilling obligations under article 11 of the WIPO copyright treaty adopted on 20 December 1996, or similar laws prohibiting or restricting circumvention of such measures. When you convey a covered work, you waive any legal power to forbid circumvention of technological measures to the extent such circumvention is effected by exercising rights under this License with respect to the covered work, and you disclaim any intention to limit operation or modification of the work as a means of enforcing, against the work's users, your or third parties' legal rights to forbid circumvention of technological measures. 4. Conveying Verbatim Copies. You may convey verbatim copies of the Program's source code as you receive it, in any medium, provided that you conspicuously and appropriately publish on each copy an appropriate copyright notice; keep intact all notices stating that this License and any non-permissive terms added in accord with section 7 apply to the code; keep intact all notices of the absence of any warranty; and give all recipients a copy of this License along with the Program. You may charge any price or no price for each copy that you convey, and you may offer support or warranty protection for a fee. 5. Conveying Modified Source Versions. You may convey a work based on the Program, or the modifications to produce it from the Program, in the form of source code under the terms of section 4, provided that you also meet all of these conditions: a) The work must carry prominent notices stating that you modified it, and giving a relevant date. b) The work must carry prominent notices stating that it is released under this License and any conditions added under section 7. This requirement modifies the requirement in section 4 to "keep intact all notices". c) You must license the entire work, as a whole, under this License to anyone who comes into possession of a copy. This License will therefore apply, along with any applicable section 7 additional terms, to the whole of the work, and all its parts, regardless of how they are packaged. This License gives no permission to license the work in any other way, but it does not invalidate such permission if you have separately received it. d) If the work has interactive user interfaces, each must display Appropriate Legal Notices; however, if the Program has interactive interfaces that do not display Appropriate Legal Notices, your work need not make them do so. A compilation of a covered work with other separate and independent works, which are not by their nature extensions of the covered work, and which are not combined with it such as to form a larger program, in or on a volume of a storage or distribution medium, is called an "aggregate" if the compilation and its resulting copyright are not used to limit the access or legal rights of the compilation's users beyond what the individual works permit. Inclusion of a covered work in an aggregate does not cause this License to apply to the other parts of the aggregate. 6. Conveying Non-Source Forms. You may convey a covered work in object code form under the terms of sections 4 and 5, provided that you also convey the machine-readable Corresponding Source under the terms of this License, in one of these ways: a) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by the Corresponding Source fixed on a durable physical medium customarily used for software interchange. b) Convey the object code in, or embodied in, a physical product (including a physical distribution medium), accompanied by a written offer, valid for at least three years and valid for as long as you offer spare parts or customer support for that product model, to give anyone who possesses the object code either (1) a copy of the Corresponding Source for all the software in the product that is covered by this License, on a durable physical medium customarily used for software interchange, for a price no more than your reasonable cost of physically performing this conveying of source, or (2) access to copy the Corresponding Source from a network server at no charge. c) Convey individual copies of the object code with a copy of the written offer to provide the Corresponding Source. This alternative is allowed only occasionally and noncommercially, and only if you received the object code with such an offer, in accord with subsection 6b. d) Convey the object code by offering access from a designated place (gratis or for a charge), and offer equivalent access to the Corresponding Source in the same way through the same place at no further charge. You need not require recipients to copy the Corresponding Source along with the object code. If the place to copy the object code is a network server, the Corresponding Source may be on a different server (operated by you or a third party) that supports equivalent copying facilities, provided you maintain clear directions next to the object code saying where to find the Corresponding Source. Regardless of what server hosts the Corresponding Source, you remain obligated to ensure that it is available for as long as needed to satisfy these requirements. e) Convey the object code using peer-to-peer transmission, provided you inform other peers where the object code and Corresponding Source of the work are being offered to the general public at no charge under subsection 6d. A separable portion of the object code, whose source code is excluded from the Corresponding Source as a System Library, need not be included in conveying the object code work. A "User Product" is either (1) a "consumer product", which means any tangible personal property which is normally used for personal, family, or household purposes, or (2) anything designed or sold for incorporation into a dwelling. In determining whether a product is a consumer product, doubtful cases shall be resolved in favor of coverage. For a particular product received by a particular user, "normally used" refers to a typical or common use of that class of product, regardless of the status of the particular user or of the way in which the particular user actually uses, or expects or is expected to use, the product. A product is a consumer product regardless of whether the product has substantial commercial, industrial or non-consumer uses, unless such uses represent the only significant mode of use of the product. "Installation Information" for a User Product means any methods, procedures, authorization keys, or other information required to install and execute modified versions of a covered work in that User Product from a modified version of its Corresponding Source. The information must suffice to ensure that the continued functioning of the modified object code is in no case prevented or interfered with solely because modification has been made. If you convey an object code work under this section in, or with, or specifically for use in, a User Product, and the conveying occurs as part of a transaction in which the right of possession and use of the User Product is transferred to the recipient in perpetuity or for a fixed term (regardless of how the transaction is characterized), the Corresponding Source conveyed under this section must be accompanied by the Installation Information. But this requirement does not apply if neither you nor any third party retains the ability to install modified object code on the User Product (for example, the work has been installed in ROM). The requirement to provide Installation Information does not include a requirement to continue to provide support service, warranty, or updates for a work that has been modified or installed by the recipient, or for the User Product in which it has been modified or installed. Access to a network may be denied when the modification itself materially and adversely affects the operation of the network or violates the rules and protocols for communication across the network. Corresponding Source conveyed, and Installation Information provided, in accord with this section must be in a format that is publicly documented (and with an implementation available to the public in source code form), and must require no special password or key for unpacking, reading or copying. 7. Additional Terms. "Additional permissions" are terms that supplement the terms of this License by making exceptions from one or more of its conditions. Additional permissions that are applicable to the entire Program shall be treated as though they were included in this License, to the extent that they are valid under applicable law. If additional permissions apply only to part of the Program, that part may be used separately under those permissions, but the entire Program remains governed by this License without regard to the additional permissions. When you convey a copy of a covered work, you may at your option remove any additional permissions from that copy, or from any part of it. (Additional permissions may be written to require their own removal in certain cases when you modify the work.) You may place additional permissions on material, added by you to a covered work, for which you have or can give appropriate copyright permission. Notwithstanding any other provision of this License, for material you add to a covered work, you may (if authorized by the copyright holders of that material) supplement the terms of this License with terms: a) Disclaiming warranty or limiting liability differently from the terms of sections 15 and 16 of this License; or b) Requiring preservation of specified reasonable legal notices or author attributions in that material or in the Appropriate Legal Notices displayed by works containing it; or c) Prohibiting misrepresentation of the origin of that material, or requiring that modified versions of such material be marked in reasonable ways as different from the original version; or d) Limiting the use for publicity purposes of names of licensors or authors of the material; or e) Declining to grant rights under trademark law for use of some trade names, trademarks, or service marks; or f) Requiring indemnification of licensors and authors of that material by anyone who conveys the material (or modified versions of it) with contractual assumptions of liability to the recipient, for any liability that these contractual assumptions directly impose on those licensors and authors. All other non-permissive additional terms are considered "further restrictions" within the meaning of section 10. If the Program as you received it, or any part of it, contains a notice stating that it is governed by this License along with a term that is a further restriction, you may remove that term. If a license document contains a further restriction but permits relicensing or conveying under this License, you may add to a covered work material governed by the terms of that license document, provided that the further restriction does not survive such relicensing or conveying. If you add terms to a covered work in accord with this section, you must place, in the relevant source files, a statement of the additional terms that apply to those files, or a notice indicating where to find the applicable terms. Additional terms, permissive or non-permissive, may be stated in the form of a separately written license, or stated as exceptions; the above requirements apply either way. 8. Termination. You may not propagate or modify a covered work except as expressly provided under this License. Any attempt otherwise to propagate or modify it is void, and will automatically terminate your rights under this License (including any patent licenses granted under the third paragraph of section 11). However, if you cease all violation of this License, then your license from a particular copyright holder is reinstated (a) provisionally, unless and until the copyright holder explicitly and finally terminates your license, and (b) permanently, if the copyright holder fails to notify you of the violation by some reasonable means prior to 60 days after the cessation. Moreover, your license from a particular copyright holder is reinstated permanently if the copyright holder notifies you of the violation by some reasonable means, this is the first time you have received notice of violation of this License (for any work) from that copyright holder, and you cure the violation prior to 30 days after your receipt of the notice. Termination of your rights under this section does not terminate the licenses of parties who have received copies or rights from you under this License. If your rights have been terminated and not permanently reinstated, you do not qualify to receive new licenses for the same material under section 10. 9. Acceptance Not Required for Having Copies. You are not required to accept this License in order to receive or run a copy of the Program. Ancillary propagation of a covered work occurring solely as a consequence of using peer-to-peer transmission to receive a copy likewise does not require acceptance. However, nothing other than this License grants you permission to propagate or modify any covered work. These actions infringe copyright if you do not accept this License. Therefore, by modifying or propagating a covered work, you indicate your acceptance of this License to do so. 10. Automatic Licensing of Downstream Recipients. Each time you convey a covered work, the recipient automatically receives a license from the original licensors, to run, modify and propagate that work, subject to this License. You are not responsible for enforcing compliance by third parties with this License. An "entity transaction" is a transaction transferring control of an organization, or substantially all assets of one, or subdividing an organization, or merging organizations. If propagation of a covered work results from an entity transaction, each party to that transaction who receives a copy of the work also receives whatever licenses to the work the party's predecessor in interest had or could give under the previous paragraph, plus a right to possession of the Corresponding Source of the work from the predecessor in interest, if the predecessor has it or can get it with reasonable efforts. You may not impose any further restrictions on the exercise of the rights granted or affirmed under this License. For example, you may not impose a license fee, royalty, or other charge for exercise of rights granted under this License, and you may not initiate litigation (including a cross-claim or counterclaim in a lawsuit) alleging that any patent claim is infringed by making, using, selling, offering for sale, or importing the Program or any portion of it. 11. Patents. A "contributor" is a copyright holder who authorizes use under this License of the Program or a work on which the Program is based. The work thus licensed is called the contributor's "contributor version". A contributor's "essential patent claims" are all patent claims owned or controlled by the contributor, whether already acquired or hereafter acquired, that would be infringed by some manner, permitted by this License, of making, using, or selling its contributor version, but do not include claims that would be infringed only as a consequence of further modification of the contributor version. For purposes of this definition, "control" includes the right to grant patent sublicenses in a manner consistent with the requirements of this License. Each contributor grants you a non-exclusive, worldwide, royalty-free patent license under the contributor's essential patent claims, to make, use, sell, offer for sale, import and otherwise run, modify and propagate the contents of its contributor version. In the following three paragraphs, a "patent license" is any express agreement or commitment, however denominated, not to enforce a patent (such as an express permission to practice a patent or covenant not to sue for patent infringement). To "grant" such a patent license to a party means to make such an agreement or commitment not to enforce a patent against the party. If you convey a covered work, knowingly relying on a patent license, and the Corresponding Source of the work is not available for anyone to copy, free of charge and under the terms of this License, through a publicly available network server or other readily accessible means, then you must either (1) cause the Corresponding Source to be so available, or (2) arrange to deprive yourself of the benefit of the patent license for this particular work, or (3) arrange, in a manner consistent with the requirements of this License, to extend the patent license to downstream recipients. "Knowingly relying" means you have actual knowledge that, but for the patent license, your conveying the covered work in a country, or your recipient's use of the covered work in a country, would infringe one or more identifiable patents in that country that you have reason to believe are valid. If, pursuant to or in connection with a single transaction or arrangement, you convey, or propagate by procuring conveyance of, a covered work, and grant a patent license to some of the parties receiving the covered work authorizing them to use, propagate, modify or convey a specific copy of the covered work, then the patent license you grant is automatically extended to all recipients of the covered work and works based on it. A patent license is "discriminatory" if it does not include within the scope of its coverage, prohibits the exercise of, or is conditioned on the non-exercise of one or more of the rights that are specifically granted under this License. You may not convey a covered work if you are a party to an arrangement with a third party that is in the business of distributing software, under which you make payment to the third party based on the extent of your activity of conveying the work, and under which the third party grants, to any of the parties who would receive the covered work from you, a discriminatory patent license (a) in connection with copies of the covered work conveyed by you (or copies made from those copies), or (b) primarily for and in connection with specific products or compilations that contain the covered work, unless you entered into that arrangement, or that patent license was granted, prior to 28 March 2007. Nothing in this License shall be construed as excluding or limiting any implied license or other defenses to infringement that may otherwise be available to you under applicable patent law. 12. No Surrender of Others' Freedom. If 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 convey a covered work so as to satisfy simultaneously your obligations under this License and any other pertinent obligations, then as a consequence you may not convey it at all. For example, if you agree to terms that obligate you to collect a royalty for further conveying from those to whom you convey the Program, the only way you could satisfy both those terms and this License would be to refrain entirely from conveying the Program. 13. Use with the GNU Affero General Public License. Notwithstanding any other provision of this License, you have permission to link or combine any covered work with a work licensed under version 3 of the GNU Affero General Public License into a single combined work, and to convey the resulting work. The terms of this License will continue to apply to the part which is the covered work, but the special requirements of the GNU Affero General Public License, section 13, concerning interaction through a network will apply to the combination as such. 14. Revised Versions of this License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 Program specifies that a certain numbered version of the GNU General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that numbered version or of any later version published by the Free Software Foundation. If the Program does not specify a version number of the GNU General Public License, you may choose any version ever published by the Free Software Foundation. If the Program specifies that a proxy can decide which future versions of the GNU General Public License can be used, that proxy's public statement of acceptance of a version permanently authorizes you to choose that version for the Program. Later license versions may give you additional or different permissions. However, no additional obligations are imposed on any author or copyright holder as a result of your choosing to follow a later version. 15. Disclaimer of Warranty. THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "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 PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 16. Limitation of Liability. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS THE PROGRAM 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 PROGRAM (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 PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. 17. Interpretation of Sections 15 and 16. If the disclaimer of warranty and limitation of liability provided above cannot be given local legal effect according to their terms, reviewing courts shall apply local law that most closely approximates an absolute waiver of all civil liability in connection with the Program, unless a warranty or assumption of liability accompanies a copy of the Program in return for a fee. END OF TERMS AND CONDITIONS How to Apply These Terms to Your New Programs If you develop a new program, and you want it to be of the greatest possible use to the public, the best way to achieve this is to make it free software which everyone can redistribute and change under these terms. To do so, attach the following notices to the program. It is safest to attach them to the start of each source file to most effectively state 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 program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . Also add information on how to contact you by electronic and paper mail. If the program does terminal interaction, make it output a short notice like this when it starts in an interactive mode: Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. This is free software, and you are welcome to redistribute it under certain conditions; type `show c' for details. The hypothetical commands `show w' and `show c' should show the appropriate parts of the General Public License. Of course, your program's commands might be different; for a GUI interface, you would use an "about box". You should also get your employer (if you work as a programmer) or school, if any, to sign a "copyright disclaimer" for the program, if necessary. For more information on this, and how to apply and follow the GNU GPL, see . The GNU General Public License does not permit incorporating your program into proprietary programs. If your program is a subroutine library, you may consider it more useful to permit linking proprietary applications with the library. If this is what you want to do, use the GNU Lesser General Public License instead of this License. But first, please read . jzmq-3.1.0/COPYING.LESSER000066400000000000000000000226031236001602100145150ustar00rootroot00000000000000 GNU LESSER GENERAL PUBLIC LICENSE Version 3, 29 June 2007 Copyright (C) 2007 Free Software Foundation, Inc. Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed. This version of the GNU Lesser General Public License incorporates the terms and conditions of version 3 of the GNU General Public License, supplemented by the additional permissions listed below. 0. Additional Definitions. As used herein, "this License" refers to version 3 of the GNU Lesser General Public License, and the "GNU GPL" refers to version 3 of the GNU General Public License. "The Library" refers to a covered work governed by this License, other than an Application or a Combined Work as defined below. An "Application" is any work that makes use of an interface provided by the Library, but which is not otherwise based on the Library. Defining a subclass of a class defined by the Library is deemed a mode of using an interface provided by the Library. A "Combined Work" is a work produced by combining or linking an Application with the Library. The particular version of the Library with which the Combined Work was made is also called the "Linked Version". The "Minimal Corresponding Source" for a Combined Work means the Corresponding Source for the Combined Work, excluding any source code for portions of the Combined Work that, considered in isolation, are based on the Application, and not on the Linked Version. The "Corresponding Application Code" for a Combined Work means the object code and/or source code for the Application, including any data and utility programs needed for reproducing the Combined Work from the Application, but excluding the System Libraries of the Combined Work. 1. Exception to Section 3 of the GNU GPL. You may convey a covered work under sections 3 and 4 of this License without being bound by section 3 of the GNU GPL. 2. Conveying Modified Versions. If you modify a copy of the Library, and, in your modifications, a facility refers to a function or data to be supplied by an Application that uses the facility (other than as an argument passed when the facility is invoked), then you may convey a copy of the modified version: a) under this License, provided that you make a good faith effort to ensure that, in the event an Application does not supply the function or data, the facility still operates, and performs whatever part of its purpose remains meaningful, or b) under the GNU GPL, with none of the additional permissions of this License applicable to that copy. 3. Object Code Incorporating Material from Library Header Files. The object code form of an Application may incorporate material from a header file that is part of the Library. You may convey such object code under terms of your choice, provided that, if the incorporated material is not limited to numerical parameters, data structure layouts and accessors, or small macros, inline functions and templates (ten or fewer lines in length), you do both of the following: a) Give prominent notice with each copy of the object code that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the object code with a copy of the GNU GPL and this license document. 4. Combined Works. You may convey a Combined Work under terms of your choice that, taken together, effectively do not restrict modification of the portions of the Library contained in the Combined Work and reverse engineering for debugging such modifications, if you also do each of the following: a) Give prominent notice with each copy of the Combined Work that the Library is used in it and that the Library and its use are covered by this License. b) Accompany the Combined Work with a copy of the GNU GPL and this license document. c) For a Combined Work that displays copyright notices during execution, include the copyright notice for the Library among these notices, as well as a reference directing the user to the copies of the GNU GPL and this license document. d) Do one of the following: 0) Convey the Minimal Corresponding Source under the terms of this License, and the Corresponding Application Code in a form suitable for, and under terms that permit, the user to recombine or relink the Application with a modified version of the Linked Version to produce a modified Combined Work, in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source. 1) Use a suitable shared library mechanism for linking with the Library. A suitable mechanism is one that (a) uses at run time a copy of the Library already present on the user's computer system, and (b) will operate properly with a modified version of the Library that is interface-compatible with the Linked Version. e) Provide Installation Information, but only if you would otherwise be required to provide such information under section 6 of the GNU GPL, and only to the extent that such information is necessary to install and execute a modified version of the Combined Work produced by recombining or relinking the Application with a modified version of the Linked Version. (If you use option 4d0, the Installation Information must accompany the Minimal Corresponding Source and Corresponding Application Code. If you use option 4d1, you must provide the Installation Information in the manner specified by section 6 of the GNU GPL for conveying Corresponding Source.) 5. Combined Libraries. 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 that are not Applications and are not covered by this License, and convey such a combined library under terms of your choice, if you do both of the following: a) Accompany the combined library with a copy of the same work based on the Library, uncombined with any other library facilities, conveyed under the terms of this License. b) Give prominent notice with the combined library that part of it is a work based on the Library, and explaining where to find the accompanying uncombined form of the same work. 6. Revised Versions of the GNU Lesser General Public License. The Free Software Foundation may publish revised and/or new versions of the GNU 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 as you received it specifies that a certain numbered version of the GNU Lesser General Public License "or any later version" applies to it, you have the option of following the terms and conditions either of that published version or of any later version published by the Free Software Foundation. If the Library as you received it does not specify a version number of the GNU Lesser General Public License, you may choose any version of the GNU Lesser General Public License ever published by the Free Software Foundation. If the Library as you received it specifies that a proxy can decide whether future versions of the GNU Lesser General Public License shall apply, that proxy's public statement of acceptance of any version is permanent authorization for you to choose that version for the Library. -------------------------------------------------------------------------------- SPECIAL EXCEPTION GRANTED BY IMATIX As a special exception, iMatix gives you permission to link this library with independent modules to produce an executable, regardless of the license terms of these independent modules, and to copy and distribute the resulting executable under terms of your choice, provided that you also meet, for each linked independent module, the terms and conditions of the license of that module. An independent module is a module which is not derived from or based on this library. If you modify this library, you must extend this exception to your version of the library. -------------------------------------------------------------------------------- Parts of the software are licensed under the MIT (X11) license as follows: Copyright (c) 2007-2010 Contributors as listed in AUTHORS 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. jzmq-3.1.0/ChangeLog000077700000000000000000000000001236001602100164412Changelog.mdustar00rootroot00000000000000jzmq-3.1.0/Changelog.md000066400000000000000000000011531236001602100146740ustar00rootroot00000000000000# Changelog * Remove assert where runtime errors are more appropriate * Use utf8 when compiling java * Add unit test for REQ/REP send more * Update comment on ZDispatcher to warn users about busy spin wait strategy * Fix regression where compatibility with zmq 2.1.X was broken by zero copy ## v2.1.1 - February 16, 2013 * Add zero copy API to send and recv * Remove asserts from get_context JNI * Add ZLoop support * Poller rewrite * No longer c assert when trying to write to a closed Socket * Add a continuous integration support through travis-ci ## v2.1.0 - February 12, 2013 * First release to Maven Central jzmq-3.1.0/Makefile.am000066400000000000000000000001751236001602100145220ustar00rootroot00000000000000SHELL = /bin/sh ACLOCAL_AMFLAGS = -I config SUBDIRS = src/main/c++ src/main/perf DIST_SUBDIRS = src/main/c++ src/main/perf jzmq-3.1.0/NEWS000066400000000000000000000000001236001602100131500ustar00rootroot00000000000000jzmq-3.1.0/README000077700000000000000000000000001236001602100146152README.mdustar00rootroot00000000000000jzmq-3.1.0/README-PERF000066400000000000000000000003071236001602100140750ustar00rootroot00000000000000First you have to compile library, follow README. Performance utilities must be executed from perf directory (cd perf). More informations can be found here http://www.zeromq.org/results:perf-howto.jzmq-3.1.0/README.md000066400000000000000000000043161236001602100137460ustar00rootroot00000000000000What is JZMQ? ------------- This is the Java language binding for libzmq (aka ZeroMQ, 0MQ). [![Build Status](https://travis-ci.org/zeromq/jzmq.png?branch=master)](https://travis-ci.org/zeromq/jzmq) The latest [javadocs](http://zeromq.github.com/jzmq/javadocs/). Building and Installing JZMQ ---------------------------- To build you need to have the libzmq library already installed, then you run: ```bash ./autogen.sh ./configure make make install ``` Avoiding JNI ------------ JZMQ uses JNI to wrap libzmq for the best performance. If performance isn't your primary goal, look at the [JeroMQ](https://github.com/zeromq/jeromq) project, which is a pure Java implementation that provides an identical API to JZMQ, and uses the same protocol. Building Packages ----------------- To build a Debian package, run: ```bash $ dpkg-buildpackage -rfakeroot ``` To build an RPM package, run: ```bash $ rpmbuild -tb jzmq-X.Y.Z.tar.gz ``` Where X.Y.Z is replaced with the version that you've downloaded. If configure can't find your libzmq installation, you can tell it where to look, using e.g. `--with-zeromq=/usr/local`. You may want to take a look at http://www.zeromq.org/docs:tuning-zeromq for additional hints. For more information, refer to the ØMQ website at http://www.zeromq.org/. On Mac OS X you may need to compile and make install pkg-config if configure fails with "syntax error near unexpected token newline". See http://stackoverflow.com/questions/3522248/how-do-i-compile-jzmq-for-zeromq-on-osx for details. You may also need to symlink the header files of your standard Java installation (e.g. `/Developer/SDKs/MacOSX10.6.sdk/System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Headers/*.h`) into a suitable directory (e.g. `/usr/local/include`) and point the `JAVA_HOME` environment variable to the parent directory (e.g.`/usr/local`). ## Acknowledgements YourKit is kindly supporting ZeroMQ project with its full-featured [Java Profiler](http://www.yourkit.com/java/profiler/index.jsp). Copying ------- Free use of this software is granted under the terms of the GNU Lesser General Public License (LGPL). For details see the files `COPYING` and `COPYING.LESSER` included with the Java binding for ØMQ. jzmq-3.1.0/autogen.sh000077500000000000000000000031221236001602100144620ustar00rootroot00000000000000#!/bin/sh # Copyright (c) 2007-2010 iMatix Corporation # # This file is part of 0MQ. # # 0MQ is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 3 of the License, or # (at your option) any later version. # 0MQ is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # You should have received a copy of the GNU General Public License # along with this program. If not, see . # Script to generate all required files from fresh git checkout. command -v pkg-config >/dev/null 2>&1 if [ $? -ne 0 ]; then echo "autogen.sh: error: could not find pkg-config. pkg-config is required to run autogen.sh." 1>&2 exit 1 fi command -v libtool >/dev/null 2>&1 if [ $? -ne 0 ]; then echo "autogen.sh: error: could not find libtool. libtool is required to run autogen.sh." 1>&2 exit 1 fi command -v autoreconf >/dev/null 2>&1 if [ $? -ne 0 ]; then echo "autogen.sh: error: could not find autoreconf. autoconf and automake are required to run autogen.sh." 1>&2 exit 1 fi mkdir -p ./config if [ $? -ne 0 ]; then echo "autogen.sh: error: could not create directory: ./config." 1>&2 exit 1 fi autoreconf --install --force --verbose -I config if [ $? -ne 0 ]; then echo "autogen.sh: error: autoreconf exited with status $?" 1>&2 exit 1 fi jzmq-3.1.0/builds/000077500000000000000000000000001236001602100137455ustar00rootroot00000000000000jzmq-3.1.0/builds/msvc/000077500000000000000000000000001236001602100147155ustar00rootroot00000000000000jzmq-3.1.0/builds/msvc/config.hpp000066400000000000000000000013441236001602100166750ustar00rootroot00000000000000/* Copyright (c) 2007-2010 iMatix Corporation This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program. If not, see . */ jzmq-3.1.0/builds/msvc/jzmq/000077500000000000000000000000001236001602100156765ustar00rootroot00000000000000jzmq-3.1.0/builds/msvc/jzmq/jzmq.vcproj000077500000000000000000000236061236001602100201160ustar00rootroot00000000000000 jzmq-3.1.0/builds/msvc/jzmq/jzmq.vcxproj000077500000000000000000000567661236001602100203230ustar00rootroot00000000000000 Debug Win32 Debug x64 Release Win32 Release x64 {D4FC8AD4-EB3C-46AA-A67B-90D290A024F1} jzmq DynamicLibrary v110 MultiByte true DynamicLibrary v110 MultiByte true DynamicLibrary v110 MultiByte DynamicLibrary v110 MultiByte <_ProjectFileVersion>11.0.61030.0 $(SolutionDir)$(Configuration)\ $(Configuration)\ $(SolutionDir)$(Configuration)\..\..\..\lib\ $(Configuration)\ C:\ZeroMQ\include;C:\Program Files %28x86%29\Java\jdk1.6.0\include;C:\Program Files %28x86%29\Java\jdk1.6.0\include\win32;$(IncludePath) C:\ZeroMQ\lib;$(LibraryPath) C:\ZeroMQ\include;C:\Program Files\Java\jdk1.7.0\include;C:\Program Files\Java\jdk1.7.0\include\win32;$(IncludePath) C:\ZeroMQ\lib;$(LibraryPath) Compiling Java classes javac ..\..\..\src\main\java\org\zeromq\ZMQ.java ..\..\..\src\main\java\org\zeromq\ZMQException.java ..\..\..\src\main\java\org\zeromq\ZMQForwarder.java ..\..\..\src\main\java\org\zeromq\ZMQQueue.java ..\..\..\src\main\java\org\zeromq\ZMQStreamer.java ..\..\..\src\main\java\org\zeromq\EmbeddedLibraryTools.java ..\..\..\src\main\java\org\zeromq\App.java ..\..\..\src\main\java\org\zeromq\ZContext.java ..\..\..\src\main\java\org\zeromq\ZDispatcher.java ..\..\..\src\main\java\org\zeromq\ZFrame.java ..\..\..\src\main\java\org\zeromq\ZMsg.java Disabled true EnableFastChecks MultiThreadedDebugDLL Level3 EditAndContinue libzmq.lib;%(AdditionalDependencies) ../../../lib/jzmq.dll true MachineX86 Creating JAR archive cd ..\..\..\src\main\java\ jar -cvf ..\..\..\lib\zmq.jar org\zeromq\*.class Compiling Java classes javac ..\..\..\src\main\java\org\zeromq\ZMQ.java ..\..\..\src\main\java\org\zeromq\ZMQException.java ..\..\..\src\main\java\org\zeromq\ZMQForwarder.java ..\..\..\src\main\java\org\zeromq\ZMQQueue.java ..\..\..\src\main\java\org\zeromq\ZMQStreamer.java ..\..\..\src\main\java\org\zeromq\EmbeddedLibraryTools.java ..\..\..\src\main\java\org\zeromq\App.java ..\..\..\src\main\java\org\zeromq\ZContext.java ..\..\..\src\main\java\org\zeromq\ZDispatcher.java ..\..\..\src\main\java\org\zeromq\ZFrame.java ..\..\..\src\main\java\org\zeromq\ZMsg.java Disabled EnableFastChecks MultiThreadedDebugDLL Level3 ProgramDatabase libzmq.lib;%(AdditionalDependencies) ../../../lib/jzmq.dll true Creating JAR archive cd ..\..\..\src\main\java\ jar -cvf ..\..\..\lib\zmq.jar org\zeromq\*.class Compiling Java classes copy ..\config.hpp ..\..\..\src\main\c++\ javac ..\..\..\src\main\java\org\zeromq\ZMQ.java ..\..\..\src\main\java\org\zeromq\ZMQException.java ..\..\..\src\main\java\org\zeromq\ZMQForwarder.java ..\..\..\src\main\java\org\zeromq\ZMQQueue.java ..\..\..\src\main\java\org\zeromq\ZMQStreamer.java ..\..\..\src\main\java\org\zeromq\EmbeddedLibraryTools.java ..\..\..\src\main\java\org\zeromq\App.java ..\..\..\src\main\java\org\zeromq\ZContext.java ..\..\..\src\main\java\org\zeromq\ZDispatcher.java ..\..\..\src\main\java\org\zeromq\ZFrame.java ..\..\..\src\main\java\org\zeromq\ZMsg.java MaxSpeed true MultiThreadedDLL true Level3 ProgramDatabase libzmq.lib;%(AdditionalDependencies) ../../../lib/jzmq.dll true true true MachineX86 Creating JAR archive cd ..\..\..\src\main\java jar -cvf ..\..\..\lib\zmq.jar org\zeromq\*.class Compiling Java classes copy ..\config.hpp ..\..\..\src\main\c++\ javac ..\..\..\src\main\java\org\zeromq\ZMQ.java ..\..\..\src\main\java\org\zeromq\ZMQException.java ..\..\..\src\main\java\org\zeromq\ZMQForwarder.java ..\..\..\src\main\java\org\zeromq\ZMQQueue.java ..\..\..\src\main\java\org\zeromq\ZMQStreamer.java ..\..\..\src\main\java\org\zeromq\EmbeddedLibraryTools.java ..\..\..\src\main\java\org\zeromq\App.java ..\..\..\src\main\java\org\zeromq\ZContext.java ..\..\..\src\main\java\org\zeromq\ZDispatcher.java ..\..\..\src\main\java\org\zeromq\ZFrame.java ..\..\..\src\main\java\org\zeromq\ZMsg.java MaxSpeed true MultiThreadedDLL true Level3 ProgramDatabase libzmq.lib;%(AdditionalDependencies) ../../../lib/jzmq.dll true true true Creating JAR archive cd ..\..\..\src\main\java jar -cvf ..\..\..\lib\zmq.jar org\zeromq\*.class Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQ javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQ org_zeromq_ZMQ.h;%(Outputs) org_zeromq_ZMQ.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQ javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQ org_zeromq_ZMQ.h;%(Outputs) org_zeromq_ZMQ.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQException javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQException org_zeromq_ZMQException.h;%(Outputs) org_zeromq_ZMQException.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQException javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQException org_zeromq_ZMQException.h;%(Outputs) org_zeromq_ZMQException.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQForwarder javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQForwarder org_zeromq_ZMQForwarder.h;%(Outputs) org_zeromq_ZMQForwarder.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQForwarder javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQForwarder org_zeromq_ZMQForwarder.h;%(Outputs) org_zeromq_ZMQForwarder.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQQueue javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQQueue org_zeromq_ZMQQueue.h;%(Outputs) org_zeromq_ZMQQueue.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQQueue javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQQueue org_zeromq_ZMQQueue.h;%(Outputs) org_zeromq_ZMQQueue.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQStreamer javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQStreamer org_zeromq_ZMQSrteamer.h;%(Outputs) org_zeromq_ZMQSrteamer.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQStreamer javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.ZMQStreamer org_zeromq_ZMQSrteamer.h;%(Outputs) org_zeromq_ZMQSrteamer.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.EmbeddedLibraryTools javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.EmbeddedLibraryTools org_zeromq_ZMQSrteamer.h;%(Outputs) org_zeromq_ZMQSrteamer.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.EmbeddedLibraryTools javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.EmbeddedLibraryTools org_zeromq_ZMQSrteamer.h;%(Outputs) org_zeromq_ZMQSrteamer.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.App javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.App org_zeromq_ZMQSrteamer.h;%(Outputs) org_zeromq_ZMQSrteamer.h;%(Outputs) Generating JNI header Generating JNI header javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.App javah -jni -classpath ..\..\..\src\main\java -d ..\..\..\src\main\c++ org.zeromq.App org_zeromq_ZMQSrteamer.h;%(Outputs) org_zeromq_ZMQSrteamer.h;%(Outputs) jzmq-3.1.0/builds/msvc/local_lat/000077500000000000000000000000001236001602100166475ustar00rootroot00000000000000jzmq-3.1.0/builds/msvc/local_lat/local_lat.vcproj000066400000000000000000000033171236001602100220320ustar00rootroot00000000000000 jzmq-3.1.0/builds/msvc/local_lat/local_lat.vcxproj000077500000000000000000000134141236001602100222240ustar00rootroot00000000000000 Debug Win32 Debug x64 Release Win32 Release x64 {6E023743-6824-46E4-A7E2-F9CEAD0D8A1D} local_lat Utility v110 MultiByte true Utility v110 MultiByte true Utility v110 MultiByte Utility v110 MultiByte <_ProjectFileVersion>11.0.61030.0 $(SolutionDir)$(Configuration)\ $(Configuration)\ $(SolutionDir)$(Configuration)\ $(Configuration)\ Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_lat.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_lat.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_lat.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_lat.java {d4fc8ad4-eb3c-46aa-a67b-90d290a024f1} false jzmq-3.1.0/builds/msvc/local_thr/000077500000000000000000000000001236001602100166645ustar00rootroot00000000000000jzmq-3.1.0/builds/msvc/local_thr/local_thr.vcproj000066400000000000000000000033171236001602100220640ustar00rootroot00000000000000 jzmq-3.1.0/builds/msvc/local_thr/local_thr.vcxproj000077500000000000000000000134141236001602100222560ustar00rootroot00000000000000 Debug Win32 Debug x64 Release Win32 Release x64 {BA759269-B4F7-44EA-82D3-BE69FACAE8E8} local_thr Utility v110 MultiByte true Utility v110 MultiByte true Utility v110 MultiByte Utility v110 MultiByte <_ProjectFileVersion>11.0.61030.0 $(SolutionDir)$(Configuration)\ $(Configuration)\ $(SolutionDir)$(Configuration)\ $(Configuration)\ Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_thr.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_thr.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_thr.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\local_thr.java {d4fc8ad4-eb3c-46aa-a67b-90d290a024f1} false jzmq-3.1.0/builds/msvc/msvc.sln000066400000000000000000000052411236001602100164050ustar00rootroot00000000000000 Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2012 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "jzmq", "jzmq\jzmq.vcxproj", "{D4FC8AD4-EB3C-46AA-A67B-90D290A024F1}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "local_lat", "local_lat\local_lat.vcxproj", "{6E023743-6824-46E4-A7E2-F9CEAD0D8A1D}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "remote_lat", "remote_lat\remote_lat.vcxproj", "{A5D76DBB-258B-4A1D-8843-4E133E456245}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "local_thr", "local_thr\local_thr.vcxproj", "{BA759269-B4F7-44EA-82D3-BE69FACAE8E8}" EndProject Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "remote_thr", "remote_thr\remote_thr.vcxproj", "{D1423DF1-C423-4C85-916D-B5E9F1445931}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|Win32 = Debug|Win32 Release|Win32 = Release|Win32 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {D4FC8AD4-EB3C-46AA-A67B-90D290A024F1}.Debug|Win32.ActiveCfg = Release|x64 {D4FC8AD4-EB3C-46AA-A67B-90D290A024F1}.Debug|Win32.Build.0 = Release|x64 {D4FC8AD4-EB3C-46AA-A67B-90D290A024F1}.Release|Win32.ActiveCfg = Release|Win32 {D4FC8AD4-EB3C-46AA-A67B-90D290A024F1}.Release|Win32.Build.0 = Release|Win32 {6E023743-6824-46E4-A7E2-F9CEAD0D8A1D}.Debug|Win32.ActiveCfg = Release|Win32 {6E023743-6824-46E4-A7E2-F9CEAD0D8A1D}.Debug|Win32.Build.0 = Release|Win32 {6E023743-6824-46E4-A7E2-F9CEAD0D8A1D}.Release|Win32.ActiveCfg = Release|Win32 {6E023743-6824-46E4-A7E2-F9CEAD0D8A1D}.Release|Win32.Build.0 = Release|Win32 {A5D76DBB-258B-4A1D-8843-4E133E456245}.Debug|Win32.ActiveCfg = Release|Win32 {A5D76DBB-258B-4A1D-8843-4E133E456245}.Debug|Win32.Build.0 = Release|Win32 {A5D76DBB-258B-4A1D-8843-4E133E456245}.Release|Win32.ActiveCfg = Release|Win32 {A5D76DBB-258B-4A1D-8843-4E133E456245}.Release|Win32.Build.0 = Release|Win32 {BA759269-B4F7-44EA-82D3-BE69FACAE8E8}.Debug|Win32.ActiveCfg = Release|Win32 {BA759269-B4F7-44EA-82D3-BE69FACAE8E8}.Debug|Win32.Build.0 = Release|Win32 {BA759269-B4F7-44EA-82D3-BE69FACAE8E8}.Release|Win32.ActiveCfg = Release|Win32 {BA759269-B4F7-44EA-82D3-BE69FACAE8E8}.Release|Win32.Build.0 = Release|Win32 {D1423DF1-C423-4C85-916D-B5E9F1445931}.Debug|Win32.ActiveCfg = Release|Win32 {D1423DF1-C423-4C85-916D-B5E9F1445931}.Debug|Win32.Build.0 = Release|Win32 {D1423DF1-C423-4C85-916D-B5E9F1445931}.Release|Win32.ActiveCfg = Release|Win32 {D1423DF1-C423-4C85-916D-B5E9F1445931}.Release|Win32.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal jzmq-3.1.0/builds/msvc/remote_lat/000077500000000000000000000000001236001602100170505ustar00rootroot00000000000000jzmq-3.1.0/builds/msvc/remote_lat/remote_lat.vcproj000066400000000000000000000033241236001602100224320ustar00rootroot00000000000000 jzmq-3.1.0/builds/msvc/remote_lat/remote_lat.vcxproj000077500000000000000000000134221236001602100226250ustar00rootroot00000000000000 Debug Win32 Debug x64 Release Win32 Release x64 {A5D76DBB-258B-4A1D-8843-4E133E456245} remote_lat Utility v110 MultiByte true Utility v110 MultiByte true Utility v110 MultiByte Utility v110 MultiByte <_ProjectFileVersion>11.0.61030.0 $(SolutionDir)$(Configuration)\ $(Configuration)\ $(SolutionDir)$(Configuration)\ $(Configuration)\ Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\remote_lat.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\remote_lat.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\remote_lat.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src\main\perf ..\..\..\src\main\perf\remote_lat.java {d4fc8ad4-eb3c-46aa-a67b-90d290a024f1} false jzmq-3.1.0/builds/msvc/remote_thr/000077500000000000000000000000001236001602100170655ustar00rootroot00000000000000jzmq-3.1.0/builds/msvc/remote_thr/remote_thr.vcproj000066400000000000000000000033241236001602100224640ustar00rootroot00000000000000 jzmq-3.1.0/builds/msvc/remote_thr/remote_thr.vcxproj000077500000000000000000000133521236001602100226610ustar00rootroot00000000000000 Debug Win32 Debug x64 Release Win32 Release x64 {D1423DF1-C423-4C85-916D-B5E9F1445931} remote_thr Utility v110 MultiByte true Utility v110 MultiByte true Utility v110 MultiByte Utility v110 MultiByte <_ProjectFileVersion>11.0.61030.0 $(SolutionDir)$(Configuration)\ $(Configuration)\ $(SolutionDir)$(Configuration)\ $(Configuration)\ Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src ..\..\..\src\main\perf\remote_thr.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src ..\..\..\src\main\perf\remote_thr.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src ..\..\..\src\main\perf\remote_thr.java Compiling Java classes javac -classpath ..\..\..\lib\zmq.jar;..\..\..\src ..\..\..\src\main\perf\remote_thr.java {d4fc8ad4-eb3c-46aa-a67b-90d290a024f1} false jzmq-3.1.0/config/000077500000000000000000000000001236001602100137305ustar00rootroot00000000000000jzmq-3.1.0/config/ax_jni_include_dir.m4000066400000000000000000000102221236001602100200000ustar00rootroot00000000000000# =========================================================================== # http://www.gnu.org/software/autoconf-archive/ax_jni_include_dir.html # =========================================================================== # # SYNOPSIS # # AX_JNI_INCLUDE_DIR # # DESCRIPTION # # AX_JNI_INCLUDE_DIR finds include directories needed for compiling # programs using the JNI interface. # # JNI include directories are usually in the java distribution This is # deduced from the value of JAVAC. When this macro completes, a list of # directories is left in the variable JNI_INCLUDE_DIRS. # # Example usage follows: # # AX_JNI_INCLUDE_DIR # # for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS # do # CPPFLAGS="$CPPFLAGS -I$JNI_INCLUDE_DIR" # done # # If you want to force a specific compiler: # # - at the configure.in level, set JAVAC=yourcompiler before calling # AX_JNI_INCLUDE_DIR # # - at the configure level, setenv JAVAC # # Note: This macro can work with the autoconf M4 macros for Java programs. # This particular macro is not part of the original set of macros. # # LICENSE # # Copyright (c) 2008 Don Anderson # # Copying and distribution of this file, with or without modification, are # permitted in any medium without royalty provided the copyright notice # and this notice are preserved. This file is offered as-is, without any # warranty. #serial 7 AU_ALIAS([AC_JNI_INCLUDE_DIR], [AX_JNI_INCLUDE_DIR]) AC_DEFUN([AX_JNI_INCLUDE_DIR],[ JNI_INCLUDE_DIRS="" test "x$JAVAC" = x && AC_MSG_ERROR(['\$JAVAC' undefined]) AC_PATH_PROG([_ACJNI_JAVAC], [$JAVAC], [no], [$PATH$PATH_SEPARATOR/]) test "x$_ACJNI_JAVAC" = xno && AC_MSG_ERROR([$JAVAC could not be found in path]) _ACJNI_FOLLOW_SYMLINKS("$_ACJNI_JAVAC") _JTOPDIR=`echo "$_ACJNI_FOLLOWED" | sed -e 's://*:/:g' -e 's:/[[^/]]*$::'` case "$host_os" in darwin*) _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'` _JINC="$_JTOPDIR/Headers" if ! test -d "$_JINC"; then _JTOPDIR="$(/usr/libexec/java_home)" _JINC="$_JTOPDIR/include" fi;; *) _JINC="$_JTOPDIR/include";; esac #_AS_ECHO_LOG([_JTOPDIR=$_JTOPDIR]) #_AS_ECHO_LOG([_JINC=$_JINC]) # On Mac OS X 10.6.4, jni.h is a symlink: # /System/Library/Frameworks/JavaVM.framework/Versions/Current/Headers/jni.h # -> ../../CurrentJDK/Headers/jni.h. if test -f "$_JINC/jni.h" || test -L "$_JINC/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JINC" else _JTOPDIR=`echo "$_JTOPDIR" | sed -e 's:/[[^/]]*$::'` if test -f "$_JTOPDIR/include/jni.h"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include" else AC_MSG_ERROR([cannot find java include files]) fi fi # get the likely subdirectories for system specific java includes case "$host_os" in bsdi*) _JNI_INC_SUBDIRS="bsdos";; linux*) _JNI_INC_SUBDIRS="linux genunix";; darwin*) _JNI_INC_SUBDIRS="darwin";; osf*) _JNI_INC_SUBDIRS="alpha";; solaris*) _JNI_INC_SUBDIRS="solaris";; mingw*) _JNI_INC_SUBDIRS="win32";; cygwin*) _JNI_INC_SUBDIRS="win32";; *) _JNI_INC_SUBDIRS="genunix";; esac # add any subdirectories that are present for JINCSUBDIR in $_JNI_INC_SUBDIRS do if test -d "$_JTOPDIR/include/$JINCSUBDIR"; then JNI_INCLUDE_DIRS="$JNI_INCLUDE_DIRS $_JTOPDIR/include/$JINCSUBDIR" fi done ]) # _ACJNI_FOLLOW_SYMLINKS # Follows symbolic links on , # finally setting variable _ACJNI_FOLLOWED # ---------------------------------------- AC_DEFUN([_ACJNI_FOLLOW_SYMLINKS],[ # find the include directory relative to the javac executable _cur="$1" while ls -ld "$_cur" 2>/dev/null | grep " -> " >/dev/null; do AC_MSG_CHECKING([symlink for $_cur]) _slink=`ls -ld "$_cur" | sed 's/.* -> //'` case "$_slink" in /*) _cur="$_slink";; # 'X' avoids triggering unwanted echo options. *) _cur=`echo "X$_cur" | sed -e 's/^X//' -e 's:[[^/]]*$::'`"$_slink";; esac AC_MSG_RESULT([$_cur]) done _ACJNI_FOLLOWED="$_cur" ])# _ACJNI jzmq-3.1.0/configure.in000066400000000000000000000074061236001602100150030ustar00rootroot00000000000000# -*- Autoconf -*- # Process this file with autoconf to produce a configure script. # AC_PREREQ(2.59) # # Change the version number below after doing a public release. # The version in git should reflect the *next* version planned. # Version must be MAJOR.MINOR.PATCH otherwise things will break. # AC_INIT([jzmq],[4.0.0],[zeromq-dev@lists.zeromq.org]) AC_CONFIG_AUX_DIR(config) AC_CONFIG_MACRO_DIR(config) AC_CONFIG_HEADERS(src/main/c++/config.hpp) AM_INIT_AUTOMAKE(tar-ustar) # # Libtool -version-info (ABI version) # # Currently 0.0.0 ("unstable"). Don't change this unless you # know exactly what you're doing and have read and understand # http://www.gnu.org/software/libtool/manual/html_node/Updating-version-info.html # # libjzmq -version-info JLTVER="0:0:0" AC_SUBST(JLTVER) # Checks for programs. AC_PROG_LIBTOOL #AC_PROG_RANLIB # AC_PROG_SED AC_PROG_AWK AM_PROG_CC_C_O AC_PROG_CXX AC_LANG(C++) # Set default CPPFLAGS for reentrant code CPPFLAGS="-D_REENTRANT -D_THREAD_SAFE $CPPFLAGS" # Check for zeromq library zeromq_prefix=detect AC_ARG_WITH([zeromq], [AS_HELP_STRING([--with-zeromq=PREFIX], [build with ZeroMQ library installed in PREFIX [default=autodetect]])], [case "x$withval" in xno) AC_MSG_ERROR([jzmq requires the ZeroMQ library]) ;; xyes|x) ;; *) CPPFLAGS="$CPPFLAGS -I${withval}/include" LDFLAGS="$LDFLAGS -L${withval}/lib" zeromq_prefix=${withval} ;; esac ] ) if test "x$zeromq_prefix" = "xdetect"; then PKG_CHECK_MODULES( [ZeroMQ], [libzmq], [zeromq_prefix=pkgconfig], [zeromq_prefix=]) if test "x$zeromq_prefix" = "xpkgconfig"; then CPPFLAGS="$CPPFLAGS ${ZeroMQ_CFLAGS}" LDFLAGS="$LDFLAGS ${ZeroMQ_LIBS}" fi fi AC_ARG_ENABLE([version], [AS_HELP_STRING([--enable-version], [builds with version information embedded [default=yes]])]) AM_CONDITIONAL(DISABLE_VERSION, test "x$enable_version" = "xno") AC_CHECK_HEADER([zmq.h], [], [AC_MSG_ERROR([cannot find zmq.h])]) AC_ARG_ENABLE([self-contained], [AS_HELP_STRING([--enable-self-contained], [generates a library that embeds all its external dependencies [default=no]])]) AC_ARG_ENABLE([self-contained-uuid], [AS_HELP_STRING([--enable-self-contained-uuid], [embeds the libuuid dependency in the shared object [default=no]])]) AC_CHECK_LIB([zmq], [zmq_init], [ if test "x$enable_self_contained" = "xyes"; then LDFLAGS="$LDFLAGS -Wl,-Bstatic -Wl,-lzmq -Wl,-Bdynamic" else LIBS="-lzmq $LIBS" fi if test "x$enable_self_contained_uuid" = "xyes"; then LDFLAGS="$LDFLAGS -Wl,-luuid" fi ], [AC_MSG_ERROR([cannot link with -lzmq])]) # Check for JDK test "x$JAVAC" = x && AC_CHECK_PROGS(JAVAC, javac -encoding ut8) test "x$JAVAC" = x && AC_MSG_ERROR([cannot find javac]) AC_SUBST(JAVAC) test "x$JAVAH" = x && AC_CHECK_PROGS(JAVAH, javah) test "x$JAVAH" = x && AC_MSG_ERROR([cannot find javah]) AC_SUBST(JAVAH) test "x$JAR" = x && AC_CHECK_PROGS(JAR, jar) test "x$JAR" = x && AC_MSG_ERROR([cannot find jar]) AC_SUBST(JAR) JAVAROOT=. AC_SUBST(JAVAROOT) # Checks for libraries. AX_JNI_INCLUDE_DIR for JNI_INCLUDE_DIR in $JNI_INCLUDE_DIRS; do CPPFLAGS="$CPPFLAGS -I$JNI_INCLUDE_DIR" done AC_SUBST(CPPFLAGS) # Checks for typedefs, structures, and compiler characteristics. AC_C_CONST AC_TYPE_SIZE_T AC_OUTPUT(Makefile src/main/c++/Makefile src/main/perf/Makefile) # On Linux patch libtool to delete hardcoded paths (rpath). case "${host_os}" in *linux*) sed < libtool > libtool-2 \ 's/^hardcode_libdir_flag_spec.*$'/'hardcode_libdir_flag_spec=" "/' mv libtool-2 libtool chmod 755 libtool ;; esac jzmq-3.1.0/debian/000077500000000000000000000000001236001602100137055ustar00rootroot00000000000000jzmq-3.1.0/debian/changelog000066400000000000000000000057421236001602100155670ustar00rootroot00000000000000jzmq (3.1.0-1) precise; urgency=low * Check changelog for updates -- Trevor Bernard Thu, 10 Oct 2013 13:07:44 -0300 jzmq (2.2.2-1) precise; urgency=low * Fix issue #241 - Fix travis-ci build * Update the appropriate build files to the correct version -- Trevor Bernard Thu, 01 Aug 2013 09:02:27 -0300 jzmq (2.2.1-1) precise; urgency=low * Fix issue ZeroMQ 2.x compatibility -- Trevor Bernard Mon, 29 Jul 2013 13:06:19 -0300 jzmq (2.2.0-1) precise; urgency=low * Add toString method to ZMsg * Fix README, plus note about JeroMQ * Add unit test for issue #216 * Fix NullPointerException in Poller and fix bad null login in JNI * Fix issue #81 - invalid conversion from 'const jbyte*' to 'jbyte*' * Fix zero copy send * Add ByteBuffer API for send and recv * Fix issue #226 - Socket and Context now implement CLoseable * Fix issue #228 - Socket and Context no longer override finalize -- Trevor Bernard Mon, 27 May 2013 21:46:40 -0300 jzmq (2.1.3-1) precise; urgency=low * Fix issue #200 - Correct inaccurate javadocs for setTCPKeepAliveInterval and setTCPKeepAliveIdle * Fixed unregisterInternal to skip PollItems which were nulled by a previous unregisterInternal. * Fix Issue #203 - An overriding instance method doesn't have to throw exceptions specified by it's superclass. * Prevent EINVAL in setsockopt * Fix issue #197 - Only sign artifacts when it's time to release * Create CMakeLists.txt * Work around to a Locale javac bug * test added to verify sockopt ZMQ_XPUB_VERBOSE * Add set method for sockopt ZMQ_XPUB_VERBOSE * recvZeroCopy failure is hidden by failure to set position on ByteBuffer * Fix #186 - Enforce only calling finalize once in Socket and Context * Fixed ZMQ.Socket.setRecoveryInterval() to work with v3.0.0 and up. -- Trevor Bernard Sun, 14 Apr 2013 21:04:55 -0300 jzmq (2.1.2-1) precise; urgency=low * Remove assert where runtime errors are more appropriate * Use utf8 when compiling java * Add unit test for REQ/REP send more * Update comment on ZDispatcher to warn users about busy spin wait strategy * Fix regression where compatibility with zmq 2.1.X was broken by zero copy -- Trevor Bernard Sun, 17 Feb 2013 20:38:05 -0400 jzmq (2.1.1-1) precise; urgency=low * Add zero copy API to send and recv * Remove asserts from get_context JNI * Add ZLoop support * Poller rewrite * No longer c assert when trying to write to a closed Socket * Add a continuous integration support through travis-ci -- Trevor Bernard Sun, 17 Feb 2013 20:38:05 -0400 jzmq (2.1.0-1) unstable; urgency=low * Development release -- Alois Bělaška Thu, 09 Dec 2010 11:44:56 +0100 jzmq (2.0.9-1) unstable; urgency=low * Initial release -- Alois Bělaška Wed, 08 Dec 2010 11:15:56 +0100 jzmq-3.1.0/debian/compat000066400000000000000000000000021236001602100151030ustar00rootroot000000000000007 jzmq-3.1.0/debian/control000066400000000000000000000016351236001602100153150ustar00rootroot00000000000000Source: jzmq Section: libs Priority: optional Maintainer: Alois Belaska Build-Depends: debhelper (>= 7), libzmq-dev [amd64 i386]|libzmq3-dev [amd64 i386], sun-java6-jdk | openjdk-6-jdk, libpgm-dev, pkg-config, libtool, autoconf Standards-Version: 3.9.1 Homepage: https://github.com/zeromq/jzmq Package: jzmq Architecture: any Depends: libzmq0 (>= 2.0.10)| libzmq1 (>= 2.0.10), libpgm|libpgm-5.1-0, ${shlibs:Depends}, ${misc:Depends} Description: The Java ZeroMQ bindings The 0MQ lightweight messaging kernel is a library which extends the standard socket interfaces with features traditionally provided by specialised messaging middleware products. 0MQ sockets provide an abstraction of asynchronous message queues, multiple messaging patterns, message filtering (subscriptions), seamless access to multiple transport protocols and more. This package contains the Java Bindings for ZeroMQ. jzmq-3.1.0/debian/copyright000066400000000000000000000101201236001602100156320ustar00rootroot00000000000000This package was debianized by Alois Belaska The packaging scripts are ©2009-2010 by these authors and are distributed under the same terms as the zeromq library (LGPL 2 or later.) Licensing information for 0MQ ----------------------------- Project homepage, with original source code: http://www.zeromq.org/ Copyright and Upstream Authors: Copyright © 2007-2010 iMatix Corporation License: This package is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This package is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this package; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA On Debian systems, the complete text of the GNU Lesser General Public License can be found in `/usr/share/common-licenses/LGPL'. iMatix also offers commercial licenses for 0MQ. Licensing information for the included OpenPGM library ------------------------------------------------------ Project homepage, with original source code: http://code.google.com/p/openpgm/ Copyright and Upstream Authors: Copyright © 2006-2010 Miru Limited. Copyright © 1995, 1996, 2001, 2003 Free Software Foundation, Inc. Copyright © 2002, 2003 Andi Kleen, SuSE Labs. License: Most of OpenPGM is licensed under the terms of the GNU Lesser Public License, the LGPL, see the file COPYING for details. The ultra-high performance partial checksum & folding routines that are taken from the Linux kernel and licensed under the terms of the GNU General Public License, the GPL, see the file COPYING.GPL for details. Hence you should treat the libraries libpgm, libpgmsnmp, and libpgmhttp of OpenPGM as being LGPL licensed and the library libpgmplus as being GPL licensed. (Packager's note: "GPL" in the context of the Linux kernel means GPL 2. 0MQ doesn't use those files during build or runtime, so it is not relevant for the license of zeromq itself.)) Commercial licenses are also offered. On Debian systems, the complete text of the GNU Lesser General Public License can be found in `/usr/share/common-licenses/LGPL'. On Debian systems, the complete text of the GNU General Public License can be found in `/usr/share/common-licenses/GPL-2'. Licensing information for the included XMLParser library -------------------------------------------------------- From xmlParser.hpp: Copyright (c) 2002, Frank Vanden Berghen All rights reserved. The following license terms apply to projects that are in some way related to the "ZeroMQ project", including applications using "ZeroMQ project" and tools developed for enhancing "ZeroMQ project". All other projects (not related to "ZeroMQ project") have to use this code under the Aladdin Free Public License (AFPL) See the file "AFPL-license.txt" for more informations about the AFPL license. (see http://www.artifex.com/downloads/doc/Public.htm for detailed AFPL terms) 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 Frank Vanden Berghen nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. jzmq-3.1.0/debian/docs000066400000000000000000000000241236001602100145540ustar00rootroot00000000000000AUTHORS NEWS README jzmq-3.1.0/debian/jzmq.install000066400000000000000000000000531236001602100162540ustar00rootroot00000000000000usr/lib/libjzmq.so* usr/share/java/zmq.jar jzmq-3.1.0/debian/rules000077500000000000000000000022641236001602100147710ustar00rootroot00000000000000#!/usr/bin/make -f #export DH_VERBOSE=1 DEB_HOST_ARCH := $(shell dpkg-architecture -qDEB_HOST_ARCH) ifneq (,$(filter parallel=%,$(DEB_BUILD_OPTIONS))) NUMJOBS = $(patsubst parallel=%,%,$(filter parallel=%,$(DEB_BUILD_OPTIONS))) MAKEFLAGS += -j$(NUMJOBS) endif configure: configure-stamp configure-stamp: dh_testdir ./autogen.sh ./configure $(CROSS) \ --prefix=/usr \ CFLAGS="$(CFLAGS)" \ LDFLAGS="-Wl,--as-needed -Wl,-z,defs" \ touch configure-stamp build: build-stamp build-stamp: configure-stamp dh_testdir $(MAKE) $(MAKEFLAGS) touch $@ clean: dh_testdir dh_testroot rm -f build-stamp configure-stamp if [ -e Makefile ]; then make distclean; fi rm -rf config.log dh_clean install: build dh_testdir dh_testroot dh_prep dh_installdirs $(MAKE) DESTDIR=$(CURDIR)/debian/tmp install binary-indep: build install binary-arch: build install dh_testdir dh_testroot dh_install dh_installchangelogs dh_installdocs dh_lintian dh_link dh_compress dh_fixperms dh_makeshlibs dh_installdeb dh_shlibdeps dh_gencontrol dh_md5sums dh_builddeb binary: binary-indep binary-arch .PHONY: build clean binary-indep binary-arch binary install configure jzmq-3.1.0/jzmq.spec000066400000000000000000000043771236001602100143330ustar00rootroot00000000000000Name: jzmq Version: 3.1.0 Release: 1%{?dist} Summary: The Java ZeroMQ bindings Group: Applications/Internet License: LGPLv3+ URL: http://www.zeromq.org/ Source: http://www.zeromq.org/local--files/area:download/%{name}-%{version}.tar.gz Prefix: %{_prefix} Buildroot: %{_tmppath}/%{name}-%{version}-%{release}-root BuildRequires: gcc, make, gcc-c++, libstdc++-devel Requires: libstdc++, zeromq %description The 0MQ lightweight messaging kernel is a library which extends the standard socket interfaces with features traditionally provided by specialised messaging middleware products. 0MQ sockets provide an abstraction of asynchronous message queues, multiple messaging patterns, message filtering (subscriptions), seamless access to multiple transport protocols and more. This package contains the Java Bindings for ZeroMQ. %package devel Summary: Development files and static library for the Java Bindings for the ZeroMQ library. Group: Development/Libraries Requires: %{name} = %{version}-%{release}, pkgconfig %description devel The 0MQ lightweight messaging kernel is a library which extends the standard socket interfaces with features traditionally provided by specialised messaging middleware products. 0MQ sockets provide an abstraction of asynchronous message queues, multiple messaging patterns, message filtering (subscriptions), seamless access to multiple transport protocols and more. This package contains Java Bindings for ZeroMQ related development libraries and header files. %prep %setup -q ./autogen.sh %build %configure %{__make} %install [ "%{buildroot}" != "/" ] && %{__rm} -rf %{buildroot} # Install the package to build area %makeinstall %post /sbin/ldconfig %postun /sbin/ldconfig %clean [ "%{buildroot}" != "/" ] && %{__rm} -rf %{buildroot} %files %defattr(-,root,root,-) # docs in the main package %doc AUTHORS ChangeLog COPYING COPYING.LESSER NEWS README # libraries %{_libdir}/libjzmq.so* /usr/share/java/zmq.jar %files devel %defattr(-,root,root,-) %{_libdir}/libjzmq.la %{_libdir}/libjzmq.a %changelog * Thu Dec 09 2010 Alois Belaska - version of package changed to 2.1.0 * Tue Sep 21 2010 Stefan Majer - Initial packaging jzmq-3.1.0/maven.readme000066400000000000000000000055421236001602100147560ustar00rootroot00000000000000Depend on JZMQ ============== Add the following to your pom.xml: org.zeromq jzmq ${jzmq.version} compile org.zeromq jzmq ${jzmq.version} native-${os.arch}-${native.os} ${os.name} Windows windows Windows If you're not supporting Windows, you can remove the and elements and replace "${native.os}" with "${os.name}". Build JZMQ artifacts ==================== 1. Build native binary. On Linux, this is: ./autogen.sh && ./configure && make 2. Package with Maven: mvn clean package 3. Look in the target/ directory for jzmq-[version].jar and jzmq-[version]-native-[arch]-[os].jar. Deploy snapshots ================ 1. Check that the correct version is set in pom.xml. The version should end in "-SNAPSHOT". 2. Build as above. 3. Deploy with Maven: mvn deploy 4. You can deploy individual native JARs like so: mvn deploy:deploy-file -Durl=https://oss.sonatype.org/content/repositories/snapshots/ -DrepositoryId=sonatype-nexus-snapshots -DpomFile=pom.xml -Dclassifier=native-[arch]-[os] -Dfile=target/jzmq-[version]-native-[arch]-[os].jar Release ======= 1. Check that the correct version is set in pom.xml. The version should end in "-SNAPSHOT". 2. Build as above. 3. Clean up: mvn release:clean 4. Do a dry run: mvn release:prepare -DdryRun 5. If all goes well, it's time to release. Since this alters git repository state, it's best to create another branch: git checkout -b release-[version] 6. Do the release, accepting the default values when prompted: mvn release:clean release:prepare release:perform 7. You can deploy individual native JARs like so: mvn gpg:sign-and-deploy-file -Durl=https://oss.sonatype.org/service/local/staging/deploy/maven2/ -DrepositoryId=sonatype-nexus-staging -DpomFile=pom.xml -Dclassifier=native-[arch]-[os] -Dfile=target/jzmq-[version]-native-[arch]-[os].jar 8. Move the artifacts out of staging as instructed at https://docs.sonatype.org/display/Repository/Sonatype+OSS+Maven+Repository+Usage+Guide 9. Once everything's done, merge the release branch back into master: git checkout master git merge release-[version] git commit -m "merge completed release branch [version]" 10. Push to github: git push If anything goes wrong during step 6, you can roll back with the following commands: git tag -d v[version] git branch -D release-[version]jzmq-3.1.0/nativejar.xml000066400000000000000000000010341236001602100151660ustar00rootroot00000000000000 native-${native.arch}-${native.os}${native.distro}${native.zmq.version} jar false ${native.path.resolved} NATIVE/${native.arch}/${native.os} 0644 jzmq-3.1.0/pom.xml000066400000000000000000000223551236001602100140070ustar00rootroot00000000000000 4.0.0 org.sonatype.oss oss-parent 7 org.zeromq jzmq 3.1.0 jar jzmq The 0MQ lightweight messaging kernel is a library which extends the standard socket interfaces with features traditionally provided by specialised messaging middleware products. 0MQ sockets provide an abstraction of asynchronous message queues, multiple messaging patterns, message filtering (subscriptions), seamless access to multiple transport protocols and more. This package contains the Java Bindings for ZeroMQ. https://zeromq.org/ scm:git:git://github.com/zeromq/jzmq.git scm:git:ssh://git@github.com/zeromq/jzmq.git https://github.com/zeromq/jzmq v3.1.0 LGPLv3+ http://www.gnu.org/licenses/lgpl.txt zeromq The ØMQ project UTF-8 1.6 1.6 2.3 1.0 2.6 2.3.1 2.7 2.5 1.7 1.4 2.1.2 4.8.2 ${os.arch} ${native.path} ${native.library-path} Linux os.name Linux ${os.name} src/main/c++/.libs/libjzmq.so src/main/c++/.libs/ Windows windows Windows lib/jzmq.dll lib Mac mac ${os.name} src/main/c++/.libs/libjzmq.dylib src/main/c++/.libs/ os-distro os.distro -${os.distro} zmq-version zmq.version -${zmq.version} release ..${file.separator}..${file.separator}${native.path} ..${file.separator}..${file.separator}${native.library-path} deploy-local-maven maven.releases ${env.RELEASE_REPO} maven.snapshots ${env.SNAPSHOT_REPO} junit junit ${junit.version} test org.apache.maven.plugins maven-gpg-plugin 1.4 sign-artifacts verify sign maven-assembly-plugin ${maven-assembly-plugin.version} nativejar.xml make-assembly package single org.codehaus.mojo buildnumber-maven-plugin ${maven-buildnumber-plugin.version} validate create false false buildTimestamp {0,date,yyyy-MM-dd HH:mm Z} org.apache.maven.plugins maven-release-plugin ${maven-release-plugin.version} true false release v@{project.version} org.apache.maven.plugins maven-scm-plugin ${maven-scm-plugin.version} org.apache.maven.plugins maven-jar-plugin ${maven-jar-plugin.version} true true ${buildNumber} ${buildTimestamp} org.apache.maven.plugins maven-surefire-plugin 2.16 once -Djava.library.path=${native.library-path.resolved} org.apache.maven.plugins maven-shade-plugin ${maven-shade-plugin.version} package shade org.zeromq.App org.apache.maven.plugins maven-deploy-plugin ${maven-deploy-plugin.version} org.apache.maven.plugins maven-source-plugin ${maven-source-plugin.version} attach-sources jar org.apache.maven.plugins maven-javadoc-plugin ${maven-javadoc-plugin.version} attach-javadoc jar jzmq-3.1.0/src/000077500000000000000000000000001236001602100132525ustar00rootroot00000000000000jzmq-3.1.0/src/main/000077500000000000000000000000001236001602100141765ustar00rootroot00000000000000jzmq-3.1.0/src/main/c++/000077500000000000000000000000001236001602100145465ustar00rootroot00000000000000jzmq-3.1.0/src/main/c++/Context.cpp000066400000000000000000000064271236001602100167070ustar00rootroot00000000000000/* Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include #include #include "jzmq.hpp" #include "util.hpp" #include "org_zeromq_ZMQ_Context.h" static jfieldID contextptrFID; static void ensure_context (JNIEnv *env, jobject obj); static void *get_context (JNIEnv *env, jobject obj); static void put_context (JNIEnv *env, jobject obj, void *s); /** * Called to construct a Java Context object. */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Context_construct (JNIEnv *env, jobject obj, jint io_threads) { void *c = get_context (env, obj); if (c) return; c = zmq_init (io_threads); int err = zmq_errno(); put_context (env, obj, c); if (c == NULL) { raise_exception (env, err); return; } } /** * Called to destroy a Java Context object. */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Context_destroy (JNIEnv *env, jobject obj) { void *c = get_context (env, obj); if (! c) return; int rc = zmq_term (c); int err = zmq_errno(); c = NULL; put_context (env, obj, c); if (rc != 0) { raise_exception (env, err); return; } } JNIEXPORT jboolean JNICALL Java_org_zeromq_ZMQ_00024Context_setMaxSockets (JNIEnv * env, jobject obj, jint maxSockets) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) void *c = get_context (env, obj); if (! c) return JNI_FALSE; int result = zmq_ctx_set (c, ZMQ_MAX_SOCKETS, maxSockets); return result == 0; #else return JNI_FALSE; #endif } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_00024Context_getMaxSockets (JNIEnv *env, jobject obj) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) void *c = get_context (env, obj); if (! c) return -1; return zmq_ctx_get (c, ZMQ_MAX_SOCKETS); #else return -1; #endif } /** * Make sure we have a valid pointer to Java's Context::contextHandle. */ static void ensure_context (JNIEnv *env, jobject obj) { if (contextptrFID == NULL) { jclass cls = env->GetObjectClass (obj); assert (cls); contextptrFID = env->GetFieldID (cls, "contextHandle", "J"); assert (contextptrFID); env->DeleteLocalRef (cls); } } /** * Get the value of Java's Context::contextHandle. */ static void *get_context (JNIEnv *env, jobject obj) { ensure_context (env, obj); void *s = (void*) env->GetLongField (obj, contextptrFID); return s; } /** * Set the value of Java's Context::contextHandle. */ static void put_context (JNIEnv *env, jobject obj, void *s) { ensure_context (env, obj); env->SetLongField (obj, contextptrFID, (jlong) s); } jzmq-3.1.0/src/main/c++/Event.cpp000066400000000000000000000110031236001602100163260ustar00rootroot00000000000000#include #include #include #include #include "jzmq.hpp" #include "util.hpp" #include "org_zeromq_ZMQ_Event.h" static jmethodID constructor; JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Event_nativeInit (JNIEnv *env, jclass cls) { constructor = env->GetMethodID(cls, "", "(IILjava/lang/String;)V"); assert(constructor); } static zmq_msg_t* read_msg(JNIEnv *env, void *socket, zmq_msg_t *msg, int flags) { int rc = zmq_msg_init (msg); if (rc != 0) { raise_exception (env, zmq_errno()); return NULL; } #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) rc = zmq_recvmsg (socket, msg, flags); #else rc = zmq_recv (socket, msg, flags); #endif int err = zmq_errno(); if (rc < 0 && err == EAGAIN) { rc = zmq_msg_close (msg); err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return NULL; } return NULL; } if (rc < 0) { raise_exception (env, err); rc = zmq_msg_close (msg); err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return NULL; } return NULL; } return msg; } JNIEXPORT jobject JNICALL Java_org_zeromq_ZMQ_00024Event_recv (JNIEnv *env, jclass cls, jlong socket, jint flags) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,2) zmq_event_t event; zmq_msg_t event_msg; // read event message if (!read_msg(env, (void *) socket, &event_msg, flags)) return NULL; #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,0,0) assert (zmq_msg_more(&event_msg) != 0); // copy event data to event struct char *data = (char *) zmq_msg_data(&event_msg); memcpy(&event.event, data, sizeof(event.event)); memcpy(&event.value, data + sizeof(event.event), sizeof(event.value)); if (zmq_msg_close(&event_msg) < 0) { raise_exception(env, zmq_errno()); return NULL; } char addr[1025]; char *paddr; zmq_msg_t addr_msg; // read address message if (!read_msg(env, (void *) socket, &addr_msg, flags)) return NULL; assert (zmq_msg_more(&addr_msg) == 0); // copy the address string const size_t len = zmq_msg_size(&addr_msg); paddr = (char *)(len >= sizeof(addr) ? malloc(len + 1) : &addr); memcpy(paddr, zmq_msg_data(&addr_msg), len); *(paddr + len) = '\0'; if (zmq_msg_close(&addr_msg) < 0) { raise_exception(env, zmq_errno()); return NULL; } jstring address = env->NewStringUTF(paddr); if (len >= sizeof(addr)) free(paddr); assert(address); return env->NewObject(cls, constructor, event.event, event.value, address); #else assert (zmq_msg_more(&event_msg) == 0); // copy event data to event struct memcpy (&event, zmq_msg_data (&event_msg), sizeof(event)); if (zmq_msg_close(&event_msg) < 0) { raise_exception(env, zmq_errno()); return NULL; } // the addr part is a pointer to a c string that libzmq might have already called free on // it is not to be trusted so better not use it at all switch (event.event) { case ZMQ_EVENT_CONNECTED: return env->NewObject(cls, constructor, event.event, event.data.connected.fd, NULL); case ZMQ_EVENT_CONNECT_DELAYED: return env->NewObject(cls, constructor, event.event, event.data.connect_delayed.err, NULL); case ZMQ_EVENT_CONNECT_RETRIED: return env->NewObject(cls, constructor, event.event, event.data.connect_retried.interval, NULL); case ZMQ_EVENT_LISTENING: return env->NewObject(cls, constructor, event.event, event.data.listening.fd, NULL); case ZMQ_EVENT_BIND_FAILED: return env->NewObject(cls, constructor, event.event, event.data.bind_failed.err, NULL); case ZMQ_EVENT_ACCEPTED: return env->NewObject(cls, constructor, event.event, event.data.accepted.fd, NULL); case ZMQ_EVENT_ACCEPT_FAILED: return env->NewObject(cls, constructor, event.event, event.data.accept_failed.err, NULL); case ZMQ_EVENT_CLOSED: return env->NewObject(cls, constructor, event.event, event.data.closed.fd, NULL); case ZMQ_EVENT_CLOSE_FAILED: return env->NewObject(cls, constructor, event.event, event.data.close_failed.err, NULL); case ZMQ_EVENT_DISCONNECTED: return env->NewObject(cls, constructor, event.event, event.data.disconnected.fd, NULL); default: return NULL; } #endif // ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,0,0) #else return NULL; #endif // ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,2) } jzmq-3.1.0/src/main/c++/Makefile.am000066400000000000000000000035441236001602100166100ustar00rootroot00000000000000jarfile = zmq.jar jardir = $(datadir)/java JZMQ_JAVA_FILES = \ ../java/org/zeromq/EmbeddedLibraryTools.java \ ../java/org/zeromq/ZAuth.java \ ../java/org/zeromq/ZContext.java \ ../java/org/zeromq/ZDispatcher.java \ ../java/org/zeromq/ZFrame.java \ ../java/org/zeromq/ZLoop.java \ ../java/org/zeromq/ZMQ.java \ ../java/org/zeromq/ZMQException.java \ ../java/org/zeromq/ZMQForwarder.java \ ../java/org/zeromq/ZMQQueue.java \ ../java/org/zeromq/ZMQStreamer.java \ ../java/org/zeromq/ZMsg.java \ ../java/org/zeromq/ZThread.java JZMQ_CPP_FILES = \ ZMQ.cpp \ Context.cpp \ Socket.cpp \ Poller.cpp \ Event.cpp \ util.cpp JZMQ_H_FILES = \ org_zeromq_ZMQ.h \ org_zeromq_ZMQ_Context.h \ org_zeromq_ZMQ_Error.h \ org_zeromq_ZMQ_Event.h \ org_zeromq_ZMQ_PollItem.h \ org_zeromq_ZMQ_Poller.h \ org_zeromq_ZMQ_Socket.h JZMQ_HPP_FILES = \ util.hpp JZMQ_CLASS_FILES = org/zeromq/*.class $(jarfile): $(JAVAC) -d . $(JZMQ_JAVA_FILES) $(JAR) cf $(JARFLAGS) $@ $(JZMQ_CLASS_FILES) jar_DATA = $(jarfile) dist_noinst_JAVA = $(JZMQ_JAVA_FILES) lib_LTLIBRARIES = libjzmq.la libjzmq_la_SOURCES = $(JZMQ_CPP_FILES) nodist_libjzmq_la_SOURCES = \ $(JZMQ_H_FILES) \ $(JZMQ_HPP_FILES) libjzmq_la_CXXFLAGS = -Wall if DISABLE_VERSION libjzmq_la_LDFLAGS = -avoid-version else libjzmq_la_LDFLAGS = -version-info @JLTVER@ endif BUILT_SOURCES = \ $(JZMQ_H_FILES) CLEANFILES = \ -rf org \ $(JZMQ_H_FILES) \ $(JZMQ_CLASS_FILES) \ $(jarfile) $(JZMQ_H_FILES): $(jarfile) $(CLASSPATH_ENV) $(JAVAH) -jni -classpath . org.zeromq.ZMQ $(srcdir)/ZMQ.cpp: \ $(JZMQ_H_FILES) \ $(JZMQ_HPP_FILES) $(srcdir)/Context.cpp: \ org_zeromq_ZMQ_Context.h \ $(JZMQ_HPP_FILES) $(srcdir)/Socket.cpp: \ org_zeromq_ZMQ_Socket.h \ $(JZMQ_HPP_FILES) $(srcdir)/Poller.cpp: \ org_zeromq_ZMQ_Poller.h \ $(JZMQ_HPP_FILES) $(srcdir)/util.cpp: \ $(JZMQ_HPP_FILES) dist-hook: -rm $(distdir)/*.h jzmq-3.1.0/src/main/c++/Poller.cpp000066400000000000000000000114211236001602100165060ustar00rootroot00000000000000/* Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include #include #include "jzmq.hpp" #include "util.hpp" #include "org_zeromq_ZMQ_Poller.h" static jfieldID field_channel; static jfieldID field_socket; static jfieldID field_events; static jfieldID field_revents; static void *fetch_socket (JNIEnv *env, jobject socket); static int fetch_socket_fd (JNIEnv *env, jobject socket); JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_00024Poller_run_1poll (JNIEnv *env, jclass cls, jobjectArray socket_0mq, jint count, jlong timeout) { int ls = (int) count; if (ls <= 0) { return 0; } int ls_0mq = 0; if (socket_0mq) ls_0mq = env->GetArrayLength (socket_0mq); if (ls > ls_0mq) { return 0; } zmq_pollitem_t *pitem = new zmq_pollitem_t [ls]; short pc = 0; int rc = 0; // Add 0MQ sockets. Array containing them can be "sparse": there // may be null elements. The count argument has the real number // of valid sockets in the array. for (int i = 0; i < ls_0mq; ++i) { jobject s_0mq = env->GetObjectArrayElement (socket_0mq, i); if (!s_0mq) continue; void *s = fetch_socket (env, s_0mq); int fd = (s == NULL) ? fetch_socket_fd (env, s_0mq) : 0; if (s == NULL && fd < 0) { raise_exception (env, EINVAL); continue; } env->SetIntField (s_0mq, field_revents, 0); pitem [pc].socket = s; pitem [pc].fd = fd; pitem [pc].events = env->GetIntField (s_0mq, field_events); pitem [pc].revents = 0; ++pc; env->DeleteLocalRef (s_0mq); } // Count of non-null sockets must be equal to passed-in arg. if (pc == ls) { pc = 0; long tout = (long) timeout; rc = zmq_poll (pitem, ls, tout); } // Set 0MQ results. if (rc > 0 && ls > 0) { for (int i = 0; i < ls_0mq; ++i) { jobject s_0mq = env->GetObjectArrayElement (socket_0mq, i); if (!s_0mq) continue; env->SetIntField (s_0mq, field_revents, pitem [pc].revents); ++pc; env->DeleteLocalRef (s_0mq); } } else if (rc < 0) { raise_exception (env, zmq_errno()); } delete [] pitem; return rc; } /** * Get the value of socketHandle for the specified Java Socket. */ static void* fetch_socket (JNIEnv *env, jobject item){ static jmethodID get_socket_handle_mid = NULL; jclass cls; if (field_socket == NULL) { cls = env->GetObjectClass (item); assert (cls); field_channel = env->GetFieldID (cls, "channel", "Ljava/nio/channels/SelectableChannel;"); field_socket = env->GetFieldID (cls, "socket", "Lorg/zeromq/ZMQ$Socket;"); field_events = env->GetFieldID (cls, "events", "I"); field_revents = env->GetFieldID (cls, "revents", "I"); env->DeleteLocalRef (cls); } jobject socket = env->GetObjectField (item, field_socket); if (socket == NULL) return NULL; if (get_socket_handle_mid == NULL) { jclass cls = env->GetObjectClass (socket); assert (cls); get_socket_handle_mid = env->GetMethodID (cls, "getSocketHandle", "()J"); env->DeleteLocalRef (cls); assert (get_socket_handle_mid); } void *s = (void*) env->CallLongMethod (socket, get_socket_handle_mid); if (env->ExceptionCheck ()) { s = NULL; } return s; } /** * Get the file descriptor id of java.net.Socket. * returns 0 if socket is not a SelectableChannel * returns the file descriptor id or -1 on an error */ static int fetch_socket_fd (JNIEnv *env, jobject item){ jclass cls; jfieldID fid; jobject channel = env->GetObjectField (item, field_channel); if (channel == NULL) return -1; cls = env->GetObjectClass (channel); assert (cls); fid = env->GetFieldID (cls, "fdVal", "I"); env->DeleteLocalRef (cls); if (fid == NULL) return -1; /* return the descriptor */ int fd = env->GetIntField (channel, fid); return fd; } jzmq-3.1.0/src/main/c++/Socket.cpp000077500000000000000000000624271236001602100165200ustar00rootroot00000000000000/* Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include #include #include #include "jzmq.hpp" #include "util.hpp" #include "org_zeromq_ZMQ_Socket.h" static jfieldID socketHandleFID; static jmethodID contextHandleMID; static jmethodID limitMID; static jmethodID positionMID; static jmethodID setPositionMID; static zmq_msg_t* do_read(JNIEnv *env, jobject obj, zmq_msg_t *message, int flags); JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_nativeInit (JNIEnv *env, jclass c) { jclass bbcls = env->FindClass("java/nio/ByteBuffer"); limitMID = env->GetMethodID(bbcls, "limit", "()I"); positionMID = env->GetMethodID(bbcls, "position", "()I"); setPositionMID = env->GetMethodID(bbcls, "position", "(I)Ljava/nio/Buffer;"); env->DeleteLocalRef(bbcls); jclass contextcls = env->FindClass("org/zeromq/ZMQ$Context"); contextHandleMID = env->GetMethodID(contextcls, "getContextHandle", "()J"); env->DeleteLocalRef(contextcls); socketHandleFID = env->GetFieldID(c, "socketHandle", "J"); } inline void *get_socket (JNIEnv *env, jobject obj) { return (void*) env->GetLongField (obj, socketHandleFID); } inline void put_socket (JNIEnv *env, jobject obj, void *s) { env->SetLongField (obj, socketHandleFID, (jlong) s); } inline void *fetch_context (JNIEnv *env, jobject context) { return (void*) env->CallLongMethod (context, contextHandleMID); } static zmq_msg_t *do_read(JNIEnv *env, jobject obj, zmq_msg_t *message, int flags) { void *socket = get_socket (env, obj); int rc = zmq_msg_init (message); if (rc != 0) { raise_exception (env, zmq_errno()); return NULL; } #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) rc = zmq_recvmsg (socket, message, flags); #else rc = zmq_recv (socket, message, flags); #endif int err = zmq_errno(); if (rc < 0 && err == EAGAIN) { rc = zmq_msg_close (message); err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return NULL; } return NULL; } if (rc < 0) { raise_exception (env, err); rc = zmq_msg_close (message); err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return NULL; } return NULL; } return message; } JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_construct (JNIEnv *env, jobject obj, jobject context, jint type) { void *s = get_socket (env, obj); if (s) return; void *c = fetch_context (env, context); if (c == NULL) { raise_exception (env, EINVAL); return; } s = zmq_socket (c, type); int err = zmq_errno(); if (s == NULL) { raise_exception (env, err); return; } put_socket(env, obj, s); } /** * Called to destroy a Java Socket object. */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_destroy (JNIEnv *env, jobject obj) { void *s = get_socket (env, obj); if (! s) return; int rc = zmq_close (s); int err = zmq_errno(); s = NULL; put_socket (env, obj, s); if (rc != 0) { raise_exception (env, err); return; } } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_00024Socket_getLongSockopt (JNIEnv *env, jobject obj, jint option) { switch (option) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) case ZMQ_BACKLOG: case ZMQ_MAXMSGSIZE: case ZMQ_SNDHWM: case ZMQ_RCVHWM: case ZMQ_MULTICAST_HOPS: #else case ZMQ_HWM: case ZMQ_SWAP: case ZMQ_MCAST_LOOP: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0) case ZMQ_RCVTIMEO: case ZMQ_SNDTIMEO: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10) case ZMQ_RECONNECT_IVL: case ZMQ_RECONNECT_IVL_MAX: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0) case ZMQ_TYPE: case ZMQ_FD: case ZMQ_EVENTS: case ZMQ_LINGER: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) case ZMQ_TCP_KEEPALIVE: case ZMQ_TCP_KEEPALIVE_IDLE: case ZMQ_TCP_KEEPALIVE_CNT: case ZMQ_TCP_KEEPALIVE_INTVL: case ZMQ_IPV4ONLY: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) && ZMQ_VERSION < ZMQ_MAKE_VERSION(4,0,0) case ZMQ_DELAY_ATTACH_ON_CONNECT: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,0,0) case ZMQ_CONFLATE: case ZMQ_PLAIN_SERVER: case ZMQ_IMMEDIATE: #endif case ZMQ_AFFINITY: case ZMQ_RATE: case ZMQ_RECOVERY_IVL: case ZMQ_SNDBUF: case ZMQ_RCVBUF: case ZMQ_RCVMORE: { void *s = get_socket (env, obj); jlong ret = 0; int rc = 0; int err = 0; if ( (option == ZMQ_AFFINITY) #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0) || (option == ZMQ_FD) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) || (option == ZMQ_MAXMSGSIZE) #endif ) { int64_t optval = 0; size_t optvallen = sizeof(optval); rc = zmq_getsockopt (s, option, &optval, &optvallen); ret = (jlong) optval; } else { int optval = 0; size_t optvallen = sizeof(optval); rc = zmq_getsockopt (s, option, &optval, &optvallen); ret = (jlong) optval; } err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return 0L; } return ret; } default: raise_exception (env, EINVAL); return 0L; } } /** * Called by Java's Socket::getBytesSockopt(int option). */ JNIEXPORT jbyteArray JNICALL Java_org_zeromq_ZMQ_00024Socket_getBytesSockopt (JNIEnv *env, jobject obj, jint option) { switch (option) { case ZMQ_IDENTITY: #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,0,0) case ZMQ_PLAIN_USERNAME: case ZMQ_PLAIN_PASSWORD: #endif { void *s = get_socket (env, obj); // Warning: hard-coded limit here. char optval[1024]; size_t optvallen = 1024; int rc = zmq_getsockopt (s, option, optval, &optvallen); int err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return env->NewByteArray (0); } jbyteArray array = env->NewByteArray (optvallen); if (array == NULL) { raise_exception (env, EINVAL); return env->NewByteArray(0); } env->SetByteArrayRegion (array, 0, optvallen, (jbyte*) optval); return array; } default: raise_exception (env, EINVAL); return env->NewByteArray(0); } } /** * Called by Java's Socket::setLongSockopt(int option, long value). */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_setLongSockopt (JNIEnv *env, jobject obj, jint option, jlong value) { switch (option) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) case ZMQ_BACKLOG: case ZMQ_MAXMSGSIZE: case ZMQ_SNDHWM: case ZMQ_RCVHWM: case ZMQ_MULTICAST_HOPS: #else case ZMQ_HWM: case ZMQ_SWAP: case ZMQ_MCAST_LOOP: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0) case ZMQ_RCVTIMEO: case ZMQ_SNDTIMEO: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10) case ZMQ_RECONNECT_IVL: case ZMQ_RECONNECT_IVL_MAX: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0) case ZMQ_LINGER: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) case ZMQ_TCP_KEEPALIVE: case ZMQ_TCP_KEEPALIVE_IDLE: case ZMQ_TCP_KEEPALIVE_CNT: case ZMQ_TCP_KEEPALIVE_INTVL: case ZMQ_IPV4ONLY: case ZMQ_ROUTER_MANDATORY: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) && ZMQ_VERSION < ZMQ_MAKE_VERSION(4,0,0) case ZMQ_DELAY_ATTACH_ON_CONNECT: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,2) case ZMQ_XPUB_VERBOSE: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,0,0) case ZMQ_CONFLATE: case ZMQ_PLAIN_SERVER: case ZMQ_IMMEDIATE: case ZMQ_REQ_RELAXED: case ZMQ_REQ_CORRELATE: case ZMQ_PROBE_ROUTER: #endif case ZMQ_AFFINITY: case ZMQ_RATE: case ZMQ_RECOVERY_IVL: case ZMQ_SNDBUF: case ZMQ_RCVBUF: #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,1,0) case ZMQ_GSSAPI_SERVER: case ZMQ_GSSAPI_PLAINTEXT: #endif { void *s = get_socket (env, obj); int rc = 0; int err = 0; #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0) if( (option == ZMQ_LINGER) || (option == ZMQ_RATE) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,10) || (option == ZMQ_RECONNECT_IVL) || (option == ZMQ_RECONNECT_IVL_MAX) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,2,0) || (option == ZMQ_SNDTIMEO) || (option == ZMQ_RCVTIMEO) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) || (option == ZMQ_TCP_KEEPALIVE) || (option == ZMQ_TCP_KEEPALIVE_IDLE) || (option == ZMQ_TCP_KEEPALIVE_CNT) || (option == ZMQ_TCP_KEEPALIVE_INTVL) || (option == ZMQ_IPV4ONLY) || (option == ZMQ_ROUTER_MANDATORY) || (option == ZMQ_DELAY_ATTACH_ON_CONNECT) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,2) || (option == ZMQ_XPUB_VERBOSE) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) || (option == ZMQ_SNDBUF) || (option == ZMQ_RCVBUF) || (option == ZMQ_SNDHWM) || (option == ZMQ_RCVHWM) || (option == ZMQ_RECOVERY_IVL) || (option == ZMQ_BACKLOG) || (option == ZMQ_MULTICAST_HOPS) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,0,0) || (option == ZMQ_CONFLATE) || (option == ZMQ_PLAIN_SERVER) || (option == ZMQ_IMMEDIATE) || (option == ZMQ_REQ_RELAXED) || (option == ZMQ_REQ_CORRELATE) || (option == ZMQ_PROBE_ROUTER) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,1,0) || (option == ZMQ_GSSAPI_SERVER) || (option == ZMQ_GSSAPI_PLAINTEXT) #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(2,1,0) ) { int ival = (int) value; size_t optvallen = sizeof(ival); rc = zmq_setsockopt (s, option, &ival, optvallen); } else #endif { uint64_t optval = (uint64_t) value; size_t optvallen = sizeof(optval); rc = zmq_setsockopt (s, option, &optval, optvallen); } err = zmq_errno(); if (rc != 0 && err != ETERM) { raise_exception (env, err); } return; } default: raise_exception (env, EINVAL); return; } } /** * Called by Java's Socket::setBytesSockopt(int option, byte[] value). */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_setBytesSockopt (JNIEnv *env, jobject obj, jint option, jbyteArray value) { switch (option) { case ZMQ_IDENTITY: case ZMQ_SUBSCRIBE: case ZMQ_UNSUBSCRIBE: #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,0,0) case ZMQ_ZAP_DOMAIN: case ZMQ_PLAIN_USERNAME: case ZMQ_PLAIN_PASSWORD: #endif #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(4,1,0) case ZMQ_GSSAPI_PRINCIPAL: case ZMQ_GSSAPI_SERVICE_PRINCIPAL: #endif { if (value == NULL) { raise_exception (env, EINVAL); return; } void *s = get_socket (env, obj); jbyte *optval = env->GetByteArrayElements (value, NULL); if (! optval) { raise_exception (env, EINVAL); return; } size_t optvallen = env->GetArrayLength (value); int rc = zmq_setsockopt (s, option, optval, optvallen); int err = zmq_errno(); env->ReleaseByteArrayElements (value, optval, 0); if (rc != 0) { raise_exception (env, err); } return; } default: raise_exception (env, EINVAL); return; } } /** * Called by Java's Socket::bind(String addr). */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_bind (JNIEnv *env, jobject obj, jstring addr) { void *s = get_socket (env, obj); if (addr == NULL) { raise_exception (env, EINVAL); return; } const char *c_addr = env->GetStringUTFChars (addr, NULL); if (c_addr == NULL) { raise_exception (env, EINVAL); return; } int rc = zmq_bind (s, c_addr); int err = zmq_errno(); env->ReleaseStringUTFChars (addr, c_addr); if (rc != 0) { raise_exception (env, err); return; } } /** * Called by Java's Socket::unbind(String addr). */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_unbind (JNIEnv *env, jobject obj, jstring addr) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) void *s = get_socket (env, obj); if (addr == NULL) { raise_exception (env, EINVAL); return; } const char *c_addr = env->GetStringUTFChars (addr, NULL); if (c_addr == NULL) { raise_exception (env, EINVAL); return; } int rc = zmq_unbind (s, c_addr); int err = zmq_errno(); env->ReleaseStringUTFChars (addr, c_addr); if (rc != 0) { raise_exception (env, err); return; } #endif } /** * Called by Java's Socket::connect(String addr). */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_connect (JNIEnv *env, jobject obj, jstring addr) { void *s = get_socket (env, obj); if (addr == NULL) { raise_exception (env, EINVAL); return; } const char *c_addr = env->GetStringUTFChars (addr, NULL); if (c_addr == NULL) { raise_exception (env, EINVAL); return; } int rc = zmq_connect (s, c_addr); int err = zmq_errno(); env->ReleaseStringUTFChars (addr, c_addr); if (rc != 0) { raise_exception (env, err); return; } } /** * Called by Java's Socket::disconnect(String addr). */ JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_00024Socket_disconnect (JNIEnv *env, jobject obj, jstring addr) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) void *s = get_socket (env, obj); if (addr == NULL) { raise_exception (env, EINVAL); return; } const char *c_addr = env->GetStringUTFChars (addr, NULL); if (c_addr == NULL) { raise_exception (env, EINVAL); return; } int rc = zmq_disconnect (s, c_addr); int err = zmq_errno(); env->ReleaseStringUTFChars (addr, c_addr); if (rc != 0) { raise_exception (env, err); return; } #endif } typedef struct _jzmq_zerocopy_t { JNIEnv *env; jobject ref_buffer; } jzmq_zerocopy_t; static void s_delete_ref (void *ptr, void *hint) { jzmq_zerocopy_t *free_hint = (jzmq_zerocopy_t *)hint; free_hint->env->DeleteGlobalRef(free_hint->ref_buffer); delete free_hint; } #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) static jboolean s_zerocopy_init (JNIEnv *env, zmq_msg_t *message, jobject obj, jint length) { jobject ref_buffer = env->NewGlobalRef(obj); jzmq_zerocopy_t *free_hint = new jzmq_zerocopy_t; free_hint->env = env; free_hint->ref_buffer = ref_buffer; jbyte* buf = (jbyte*) env->GetDirectBufferAddress(ref_buffer); int rc = zmq_msg_init_data (message, buf, length, s_delete_ref, free_hint); if (rc != 0) { int err = zmq_errno(); raise_exception (env, err); return JNI_FALSE; } return JNI_TRUE; } #endif JNIEXPORT jboolean JNICALL Java_org_zeromq_ZMQ_00024Socket_sendZeroCopy (JNIEnv *env, jobject obj, jobject buffer, jint length, jint flags) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) int rc = 0; void *sock = get_socket (env, obj); // init the message zmq_msg_t message; jboolean retval = s_zerocopy_init (env, &message, buffer, length); if (retval == JNI_FALSE) return JNI_FALSE; rc = zmq_sendmsg (sock, &message, flags); if (rc == -1) { int err = zmq_errno(); zmq_msg_close (&message); raise_exception (env, err); return JNI_FALSE; } return JNI_TRUE; #else return JNI_FALSE; #endif } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_00024Socket_sendByteBuffer (JNIEnv *env, jobject obj, jobject buffer, jint flags) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) jbyte* buf = (jbyte*) env->GetDirectBufferAddress(buffer); if(buf == NULL) return -1; void *sock = get_socket (env, obj); int lim = env->CallIntMethod(buffer, limitMID); int pos = env->CallIntMethod(buffer, positionMID); int rem = pos <= lim ? lim - pos : 0; int rc = zmq_send(sock, buf + pos, rem, flags); if (rc > 0) env->CallVoidMethod(buffer, setPositionMID, pos + rc); if (rc == -1) { int err = zmq_errno(); raise_exception (env, err); return -1; } return rc; #else return JNI_FALSE; #endif } /** * Called by Java's Socket::send(byte [] msg, int offset, int flags). */ JNIEXPORT jboolean JNICALL Java_org_zeromq_ZMQ_00024Socket_send (JNIEnv *env, jobject obj, jbyteArray msg, jint offset, jint length, jint flags) { void *s = get_socket (env, obj); if (length < 0) { raise_exception(env, EINVAL); return JNI_FALSE; } zmq_msg_t message; int rc = zmq_msg_init_size (&message, length); int err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return JNI_FALSE; } void* pd = zmq_msg_data (&message); env->GetByteArrayRegion(msg, offset, length, (jbyte*) pd); #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) rc = zmq_sendmsg (s, &message, flags); #else rc = zmq_send (s, &message, flags); #endif err = zmq_errno(); if (rc < 0 && err == EAGAIN) { rc = zmq_msg_close (&message); err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return JNI_FALSE; } return JNI_FALSE; } if (rc < 0) { raise_exception (env, err); rc = zmq_msg_close (&message); err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return JNI_FALSE; } return JNI_FALSE; } rc = zmq_msg_close (&message); err = zmq_errno(); if (rc != 0) { raise_exception (env, err); return JNI_FALSE; } return JNI_TRUE; } inline void setByteBufferPosition(JNIEnv *env, jobject buffer, jint position) { jclass cls = env->GetObjectClass(buffer); jmethodID positionHandle = env->GetMethodID(cls, "position", "(I)Ljava/nio/Buffer;"); env->DeleteLocalRef(cls); env->CallVoidMethod(buffer, positionHandle, position); } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_00024Socket_recvZeroCopy (JNIEnv *env, jobject obj, jobject buffer, jint length, jint flags) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) jbyte* buf = (jbyte*) env->GetDirectBufferAddress(buffer); if(buf == NULL) return -1; void* sock = get_socket (env, obj); int rc = zmq_recv(sock, buf, length, flags); if (rc > 0) { int newpos = rc > length ? length : rc; setByteBufferPosition(env, buffer, newpos); } if(rc == -1) { int err = zmq_errno(); if(err != EAGAIN) { raise_exception (env, err); return 0; } } return rc; #else return -1; #endif } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_00024Socket_recvByteBuffer (JNIEnv *env, jobject obj, jobject buffer, jint flags) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,0,0) jbyte *buf = (jbyte*) env->GetDirectBufferAddress(buffer); if(buf == NULL) return -1; void *sock = get_socket (env, obj); int lim = env->CallIntMethod(buffer, limitMID); int pos = env->CallIntMethod(buffer, positionMID); int rem = pos <= lim ? lim - pos : 0; int read = zmq_recv(sock, buf + pos, rem, flags); if (read > 0) { read = read > rem ? rem : read; env->CallObjectMethod(buffer, setPositionMID, read + pos); return read; } else if(read == -1) { int err = zmq_errno(); if(err != EAGAIN) { raise_exception (env, err); return 0; } } return read; #else return JNI_FALSE; #endif } /** * Called by Java's Socket::recv(byte[] buffer, int offset, int len, int flags). */ JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_00024Socket_recv___3BIII (JNIEnv *env, jobject obj, jbyteArray buff, jint offset, jint len, jint flags) { zmq_msg_t message; if (!do_read(env,obj,&message,flags)) { return -1; } // No errors are defined for these two functions. Should they? int sz = zmq_msg_size (&message); void* pd = zmq_msg_data (&message); int stored = sz > len ? len : sz; env->SetByteArrayRegion (buff, offset, stored, (jbyte*) pd); int rc = zmq_msg_close(&message); if(rc == -1) { int err = zmq_errno(); raise_exception (env, err); return -1; } return stored; } /** * Called by Java's Socket::recv(int flags). */ JNIEXPORT jbyteArray JNICALL Java_org_zeromq_ZMQ_00024Socket_recv__I (JNIEnv *env, jobject obj, jint flags) { zmq_msg_t message; if (!do_read(env,obj,&message,flags)) { return NULL; } // No errors are defined for these two functions. Should they? int sz = zmq_msg_size (&message); void* pd = zmq_msg_data (&message); jbyteArray data = env->NewByteArray (sz); if (! data) { raise_exception (env, EINVAL); return NULL; } env->SetByteArrayRegion (data, 0, sz, (jbyte*) pd); int rc = zmq_msg_close(&message); if(rc == -1) { int err = zmq_errno(); raise_exception (env, err); return NULL; } return data; } JNIEXPORT jboolean JNICALL Java_org_zeromq_ZMQ_00024Socket_monitor (JNIEnv *env, jobject obj, jstring addr, jint events) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,0) void *socket = get_socket (env, obj); const char *c_addr = addr ? env->GetStringUTFChars (addr, NULL) : NULL; int rc = zmq_socket_monitor(socket , c_addr, events); int err = rc < 0 ? zmq_errno() : 0; env->ReleaseStringUTFChars (addr, c_addr); if (rc < 0) { raise_exception (env, err); return JNI_FALSE; } return JNI_TRUE; #else return JNI_FALSE; #endif } jzmq-3.1.0/src/main/c++/ZMQ.cpp000066400000000000000000000071421236001602100157250ustar00rootroot00000000000000/* Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include #include "jzmq.hpp" #include "org_zeromq_ZMQ.h" static void *get_socket (JNIEnv *env, jobject obj) { jclass cls = env->GetObjectClass(obj); jfieldID socketHandleFID = env->GetFieldID (cls, "socketHandle", "J"); env->DeleteLocalRef(cls); return (void*) env->GetLongField (obj, socketHandleFID); } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_version_1full (JNIEnv *env, jclass cls) { return ZMQ_VERSION; } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_version_1major (JNIEnv *env, jclass cls) { return ZMQ_VERSION_MAJOR; } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_version_1minor (JNIEnv *env, jclass cls) { return ZMQ_VERSION_MINOR; } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_version_1patch (JNIEnv *env, jclass cls) { return ZMQ_VERSION_PATCH; } JNIEXPORT jint JNICALL Java_org_zeromq_ZMQ_make_1version (JNIEnv *env, jclass cls, jint major, jint minor, jint patch) { return ZMQ_MAKE_VERSION(major, minor, patch); } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_ENOTSUP (JNIEnv *env, jclass cls) { return ENOTSUP; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_EPROTONOSUPPORT (JNIEnv *env, jclass cls) { return EPROTONOSUPPORT; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_ENOBUFS (JNIEnv *env, jclass cls) { return ENOBUFS; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_ENETDOWN (JNIEnv *env, jclass cls) { return ENETDOWN; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_EADDRINUSE (JNIEnv *env, jclass cls) { return EADDRINUSE; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_EADDRNOTAVAIL (JNIEnv *env, jclass cls) { return EADDRNOTAVAIL; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_ECONNREFUSED (JNIEnv *env, jclass cls) { return ECONNREFUSED; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_EINPROGRESS (JNIEnv *env, jclass cls) { return EINPROGRESS; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_EHOSTUNREACH (JNIEnv *env, jclass cls) { return EHOSTUNREACH; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_EMTHREAD (JNIEnv *env, jclass cls) { return EMTHREAD; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_EFSM (JNIEnv *env, jclass cls) { return EFSM; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_ENOCOMPATPROTO (JNIEnv *env, jclass cls) { return ENOCOMPATPROTO; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_ETERM (JNIEnv *env, jclass cls) { return ETERM; } JNIEXPORT jlong JNICALL Java_org_zeromq_ZMQ_ENOTSOCK (JNIEnv *env, jclass cls) { return ENOTSOCK; } JNIEXPORT void JNICALL Java_org_zeromq_ZMQ_run_1proxy (JNIEnv *env, jclass cls, jobject frontend_, jobject backend_, jobject capture_) { #if ZMQ_VERSION >= ZMQ_MAKE_VERSION(3,2,2) void *frontend = get_socket (env, frontend_); void *backend = get_socket (env, backend_); void *capture = NULL; if (capture_ != NULL) capture = get_socket (env, capture_); zmq_proxy (frontend, backend, capture); #endif } jzmq-3.1.0/src/main/c++/jzmq.hpp000066400000000000000000000027231236001602100162440ustar00rootroot00000000000000/* Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef __JZMQ_HPP_INCLUDED__ #define __JZMQ_HPP_INCLUDED__ #include "config.hpp" #if defined HAVE_INTTYPES_H #include #elif defined HAVE_STDINT_H #include #elif defined _MSC_VER #ifndef int8_t typedef signed __int8 int8_t; #endif #ifndef int16_t typedef __int16 int16_t; #endif #ifndef int32_t typedef __int32 int32_t; #endif #ifndef int64_t typedef __int64 int64_t; #endif #ifndef uint8_t typedef unsigned __int8 uint8_t; #endif #ifndef uint16_t typedef unsigned __int16 uint16_t; #endif #ifndef uint32_t typedef unsigned __int32 uint32_t; #endif #ifndef uint64_t typedef unsigned __int64 uint64_t; #endif #else #error "Don't know how to define stdint types on this platform" #endif #endif jzmq-3.1.0/src/main/c++/util.cpp000066400000000000000000000033131236001602100162270ustar00rootroot00000000000000/* Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #include #include #include "util.hpp" /** * Raise an exception that includes 0MQ's error message. */ void raise_exception (JNIEnv *env, int err) { // Get exception class. jclass exception_class = env->FindClass ("org/zeromq/ZMQException"); assert (exception_class); // Get exception class constructor jmethodID constructor_method = env->GetMethodID(exception_class, "", "(Ljava/lang/String;I)V"); assert (constructor_method); // Get text description of the exception. const char *err_desc = zmq_strerror (err); jstring err_str = env->NewStringUTF(err_desc); // Create exception class instance jthrowable exception = static_cast(env->NewObject( exception_class, constructor_method, err_str, err)); // Raise the exception. int rc = env->Throw (exception); env->DeleteLocalRef (exception_class); env->DeleteLocalRef (err_str); assert (rc == 0); } jzmq-3.1.0/src/main/c++/util.hpp000066400000000000000000000017461236001602100162440ustar00rootroot00000000000000/* Copyright (c) 2007-2013 Contributors as noted in the AUTHORS file This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ #ifndef __UTIL_HPP_INCLUDED__ #define __UTIL_HPP_INCLUDED__ #include /** * Raise an exception that includes 0MQ's error message. */ void raise_exception (JNIEnv *env, int err); #endif /* #ifndef __UTIL_HPP_INCLUDED__ */ jzmq-3.1.0/src/main/java/000077500000000000000000000000001236001602100151175ustar00rootroot00000000000000jzmq-3.1.0/src/main/java/org/000077500000000000000000000000001236001602100157065ustar00rootroot00000000000000jzmq-3.1.0/src/main/java/org/zeromq/000077500000000000000000000000001236001602100172235ustar00rootroot00000000000000jzmq-3.1.0/src/main/java/org/zeromq/App.java000066400000000000000000000033401236001602100206060ustar00rootroot00000000000000package org.zeromq; import java.util.Collection; /** * Simple App to display version information about jzmq. * */ public class App { public static void main(final String[] args) throws Exception { final Package p = App.class.getPackage(); final String appname = p.getSpecificationTitle(); final String versionMaven = p.getSpecificationVersion(); String[] version = new String[] { "", "" }; if (p.getImplementationVersion() != null) { version = p.getImplementationVersion().split(" ", 2); } String zmqVersion = null; try { final int major = ZMQ.version_major(); final int minor = ZMQ.version_minor(); final int patch = ZMQ.version_patch(); zmqVersion = major + "." + minor + "." + patch; } catch (Throwable x) { zmqVersion = "ERROR! " + x.getMessage(); } final String fmt = "%-7.7s %-15.15s %s%n"; System.out.printf(fmt, "ZeroMQ", "version:", zmqVersion); System.out.printf(fmt, appname, "version:", versionMaven); System.out.printf(fmt, appname, "build time:", version[1]); System.out.printf(fmt, appname, "build commit:", version[0]); System.out.println(); System.out.println("JNI lib location: " + (EmbeddedLibraryTools.LOADED_EMBEDDED_LIBRARY ? "embedded" : "java.library.path")); System.out.println("current platform: " + EmbeddedLibraryTools.getCurrentPlatformIdentifier()); final Collection files = EmbeddedLibraryTools.getEmbeddedLibraryList(); for (final String file : files) { System.out.println("embedded library: " + file); } } } jzmq-3.1.0/src/main/java/org/zeromq/EmbeddedLibraryTools.java000066400000000000000000000107531236001602100241330ustar00rootroot00000000000000package org.zeromq; import java.io.BufferedOutputStream; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.net.URL; import java.util.ArrayList; import java.util.Collection; import java.util.Enumeration; import java.util.List; import java.util.jar.JarEntry; import java.util.jar.JarFile; public class EmbeddedLibraryTools { public static final boolean LOADED_EMBEDDED_LIBRARY; static { LOADED_EMBEDDED_LIBRARY = loadEmbeddedLibrary(); } public static String getCurrentPlatformIdentifier() { String osName = System.getProperty("os.name"); if (osName.toLowerCase().indexOf("windows") > -1) { osName = "Windows"; } return System.getProperty("os.arch") + "/" + osName; } public static Collection getEmbeddedLibraryList() { final Collection result = new ArrayList(); final Collection files = catalogClasspath(); for (final String file : files) { if (file.startsWith("NATIVE")) { result.add(file); } } return result; } private static void catalogArchive(final File jarfile, final Collection files) { try { final JarFile j = new JarFile(jarfile); final Enumeration e = j.entries(); while (e.hasMoreElements()) { final JarEntry entry = e.nextElement(); if (!entry.isDirectory()) { files.add(entry.getName()); } } } catch (IOException x) { System.err.println(x.toString()); } } private static Collection catalogClasspath() { final List files = new ArrayList(); final String[] classpath = System.getProperty("java.class.path", "").split(File.pathSeparator); for (final String path : classpath) { final File tmp = new File(path); if (tmp.isFile() && path.toLowerCase().endsWith(".jar")) { catalogArchive(tmp, files); } else if (tmp.isDirectory()) { final int len = tmp.getPath().length() + 1; catalogFiles(len, tmp, files); } } return files; } private static void catalogFiles(final int prefixlen, final File root, final Collection files) { final File[] ff = root.listFiles(); for (final File f : ff) { if (f.isDirectory()) { catalogFiles(prefixlen, f, files); } else { files.add(f.getPath().substring(prefixlen)); } } } private static boolean loadEmbeddedLibrary() { boolean usingEmbedded = false; // attempt to locate embedded native library within JAR at following location: // /NATIVE/${os.arch}/${os.name}/libjzmq.[so|dylib|dll] String[] allowedExtensions = new String[] { "so", "dylib", "dll" }; StringBuilder url = new StringBuilder(); url.append("/NATIVE/"); url.append(getCurrentPlatformIdentifier()); url.append("/libjzmq."); URL nativeLibraryUrl = null; // loop through extensions, stopping after finding first one for (String ext : allowedExtensions) { nativeLibraryUrl = ZMQ.class.getResource(url.toString() + ext); if (nativeLibraryUrl != null) break; } if (nativeLibraryUrl != null) { // native library found within JAR, extract and load try { final File libfile = File.createTempFile("libjzmq-", ".lib"); libfile.deleteOnExit(); // just in case final InputStream in = nativeLibraryUrl.openStream(); final OutputStream out = new BufferedOutputStream(new FileOutputStream(libfile)); int len = 0; byte[] buffer = new byte[8192]; while ((len = in.read(buffer)) > -1) out.write(buffer, 0, len); out.close(); in.close(); System.load(libfile.getAbsolutePath()); libfile.delete(); usingEmbedded = true; } catch (IOException x) { // mission failed, do nothing } } // nativeLibraryUrl exists return usingEmbedded; } private EmbeddedLibraryTools() { }; } jzmq-3.1.0/src/main/java/org/zeromq/ZAuth.java000066400000000000000000000404311236001602100211230ustar00rootroot00000000000000package org.zeromq; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import org.zeromq.ZMQ.PollItem; import org.zeromq.ZMQ.Poller; import org.zeromq.ZMQ.Socket; import org.zeromq.ZThread.IAttachedRunnable; /** * ZAuth takes over authentication for all incoming connections in its context. * Note that libzmq provides four levels of security: default NULL (which zauth * does not see), and authenticated NULL, PLAIN, and CURVE, which zauth can see. * * Based on zauth.c in * czmq * * @author cbusbey (at) connamara (dot) com */ public class ZAuth { private Socket pipe; //pipe to backend agent private boolean verbose; /** * A small class for working with ZAP requests and replies. */ public static class ZAPRequest { public Socket handler; //socket we're talking to public String version; // Version number, must be "1.0" public String sequence; // Sequence number of request public String domain; // Server socket domain public String address; // Client IP address public String identity; // Server socket idenntity public String mechanism; // Security mechansim public String username; // PLAIN user name public String password; // PLAIN password, in clear text public String clientKey; // CURVE client public key in ASCII public String principal; // GSSAPI principal static ZAPRequest recvRequest(Socket handler) { if (ZMQ.getMajorVersion() == 4) { ZMsg request = ZMsg.recvMsg(handler); ZAPRequest self = new ZAPRequest(); // Store handler socket so we can send a reply easily self.handler = handler; // Get all standard frames off the handler socket self.version = request.popString(); self.sequence = request.popString(); self.domain = request.popString(); self.address = request.popString(); self.identity = request.popString(); self.mechanism = request.popString(); // If the version is wrong, we're linked with a bogus libzmq, so die assert (self.version.equals("1.0")); // Get mechanism-specific frames if (self.mechanism.equals("PLAIN")) { self.username = request.popString(); self.password = request.popString(); } else if (self.mechanism.equals("CURVE")) { // TODO: Handle CURVE authentication } else if (self.mechanism.equals("GSSAPI")) { self.principal = request.popString(); } request.destroy(); return self; } else { return null; } } /** * Send a zap reply to the handler socket * * @param request */ static void reply(ZAPRequest request, String statusCode, String statusText) { if (request == null) { return; } ZMsg msg = new ZMsg(); msg.add("1.0"); msg.add(request.sequence); msg.add(statusCode); msg.add(statusText); msg.add(""); msg.add(""); msg.send(request.handler); } } /** * ZAuthAgent is the backend agent which we talk to over a pipe. This lets * the agent do work asynchronously in the background while our application * does other things. This is invisible to the caller, who sees a classic * API. */ private static class ZAuthAgent implements IAttachedRunnable { private Socket pipe; //pipe back to application api private Socket handler; //ZAP handler socket private boolean verbose; //trace output to stdout private ConcurrentMap whitelist = new ConcurrentHashMap(); //whitelisted addresses private ConcurrentMap blacklist = new ConcurrentHashMap(); //blacklisted addresses private ConcurrentMap passwords = new ConcurrentHashMap(); // PLAIN passwords, if loaded private boolean terminated; //did api ask us to quit? private File passwords_file; private long passwords_modified; final private ZAuth auth; //our parent auth, used for authorization callbacks private ZAuthAgent(ZAuth auth) { this.auth = auth; } /** * handle a message from the front end api * * @return */ private boolean controlMessage() { ZMsg msg = ZMsg.recvMsg(pipe); String command = msg.popString(); if (command == null) { return false; //interrupted } if (command.equals("ALLOW")) { String address = msg.popString(); whitelist.put(address, "OK"); } else if (command.equals("DENY")) { String address = msg.popString(); blacklist.put(address, "OK"); } else if (command.equals("PLAIN")) { // For now we don't do anything with domains String domain = msg.popString(); // Get password file and load into HashMap // If the file doesn't exist we'll get an empty map String filename = msg.popString(); this.passwords_file = new File(filename); this.loadPasswords(true); ZMsg reply = new ZMsg(); reply.add("OK"); reply.send(pipe); reply.destroy(); } else if (command.equals("GSSAPI")) { //for now, we don't do anything with domains String domain = msg.popString(); } else if (command.equals("VERBOSE")) { String verboseStr = msg.popString(); this.verbose = verboseStr.equals("true"); } else if (command.equals("TERMINATE")) { this.terminated = true; ZMsg reply = new ZMsg(); reply.add("OK"); reply.send(pipe); reply.destroy(); } msg.destroy(); return true; } private boolean authenticate() { ZAPRequest request = ZAPRequest.recvRequest(handler); if (request == null) { return false; } //is the address explicitly whitelisted or blacklisted? boolean allowed = false; boolean denied = false; if (!whitelist.isEmpty()) { if (whitelist.containsKey(request.address)) { allowed = true; if (verbose) { System.out.printf("I: PASSED (whitelist) address = %s\n", request.address); } } else { denied = true; if (verbose) { System.out.printf("I: DENIED (not in whitelist) address = %s\n", request.address); } } } else if (!blacklist.isEmpty()) { if (blacklist.containsKey(request.address)) { denied = true; if (verbose) { System.out.printf("I: DENIED (blacklist) address = %s\n", request.address); } } else { allowed = true; if (verbose) { System.out.printf("I: PASSED (not in blacklist) address = %s\n", request.address); } } } //mechanism specific check if (!denied) { if (request.mechanism.equals("NULL") && !allowed) { // For NULL, we allow if the address wasn't blacklisted if (verbose) { System.out.printf("I: ALLOWED (NULL)\n"); } allowed = true; } else if (request.mechanism.equals("PLAIN")) { // For PLAIN, even a whitelisted address must authenticate allowed = authenticatePlain(request); } else if (request.mechanism.equals("CURVE")) { // For CURVE, even a whitelisted address must authenticate // TODO: Handle CURVE authentication } else if (request.mechanism.equals("GSSAPI")) { // At this point, the request is authenticated, send to //zauth callback for complete authorization allowed = auth.authenticateGSS(request); } else { System.out.printf("Skipping unknown mechanism%n"); } } if (allowed) { ZAPRequest.reply(request, "200", "OK"); } else { ZAPRequest.reply(request, "400", "NO ACCESS"); } return true; } private boolean authenticatePlain(ZAPRequest request) { // Refresh the passwords map if the file changed this.loadPasswords(false); String password = this.passwords.get(request.username); if (password != null && password.equals(request.password)) { if (this.verbose) { System.out.printf("ZAUTH I: ALLOWED (PLAIN) username=%s password=%s\n", request.username, request.password); } return true; } else { if (this.verbose) { System.out.printf("ZAUTH I: DENIED (PLAIN) username=%s password=%s\n", request.username, request.password); } return false; } } @Override public void run(Object[] args, ZContext ctx, Socket pipe) { this.pipe = pipe; //create ZAP handler and get ready for requests handler = ctx.createSocket(ZMQ.REP); try { handler.bind("inproc://zeromq.zap.01"); } catch (ZMQException e) { pipe.send("ERROR"); return; } pipe.send("OK"); PollItem[] pollItems = {new PollItem(pipe, Poller.POLLIN), new PollItem(handler, Poller.POLLIN)}; while (!terminated && !Thread.currentThread().isInterrupted()) { int rc = ZMQ.poll(pollItems, -1); if (rc == -1) { break; //interrupt } if (pollItems[0].isReadable()) { if (!controlMessage()) { break; } } if (pollItems[1].isReadable()) { if (!authenticate()) { break; } } } } private void loadPasswords(boolean initial) { if (!initial) { long lastModified = this.passwords_file.lastModified(); long age = System.currentTimeMillis() - lastModified; if (lastModified > this.passwords_modified && age > 1000) { // File has been modified and is stable, clear hashmap this.passwords.clear(); } else { return; } } this.passwords_modified = this.passwords_file.lastModified(); try { BufferedReader br = new BufferedReader(new FileReader(this.passwords_file)); String line; while ((line = br.readLine()) != null) { // Skip lines starting with "#" or that do not look like name=value data int equals = line.indexOf('='); if (line.charAt(0) == '#' || equals == -1 || equals == line.length() - 1) { continue; } this.passwords.put(line.substring(0, equals), line.substring(equals + 1, line.length())); } br.close(); } catch (Exception ex) { // Ignore the exception, just don't read the file } } } /** * Install authentication for the specified context. Note that until you add * policies, all incoming NULL connections are allowed (classic ZeroMQ * behaviour), and all PLAIN and CURVE connections are denied. */ public ZAuth(ZContext ctx) { pipe = ZThread.fork(ctx, new ZAuthAgent(this)); ZMsg msg = ZMsg.recvMsg(pipe); String response = msg.popString(); msg.destroy(); } /** * Enable verbose tracing of commands and activity * * @param verbose */ public void setVerbose(boolean verbose) { this.verbose = verbose; //agent should also be verbose ZMsg msg = new ZMsg(); msg.add("VERBOSE"); msg.add(String.format("%b", verbose)); msg.send(pipe); msg.destroy(); } /** * Allow (whitelist) a single IP address. For NULL, all clients from this * address will be accepted. For PLAIN and CURVE, they will be allowed to * continue with authentication. You can call this method multiple times to * whitelist multiple IP addresses. If you whitelist a single address, any * non-whitelisted addresses are treated as blacklisted. * */ public void allow(String address) { assert (address != null); ZMsg msg = new ZMsg(); msg.add("ALLOW"); msg.add(address); msg.send(pipe); msg.destroy(); } /** * Deny (blacklist) a single IP address. For all security mechanisms, this * rejects the connection without any further authentication. Use either a * whitelist, or a blacklist, not not both. If you define both a whitelist * and a blacklist, only the whitelist takes effect. */ public void deny(String address) { assert (address != null); ZMsg msg = new ZMsg(); msg.add("DENY"); msg.add(address); msg.send(pipe); msg.destroy(); } /** * Configure PLAIN authentication for a given domain. PLAIN authentication * uses a plain-text password file. To cover all domains, use "*". You can * modify the password file at any time; it is reloaded automatically. * * @param domain * @param filename */ public void configurePlain(String domain, String filename) { assert (domain != null); assert (filename != null); ZMsg msg = new ZMsg(); msg.add("PLAIN"); msg.add(domain); msg.add(filename); msg.send(pipe); msg.destroy(); } /** * Destructor. */ public void destroy() { ZMsg request = new ZMsg(); request.add("TERMINATE"); request.send(pipe); request.destroy(); ZMsg reply = ZMsg.recvMsg(pipe); reply.destroy(); } /*Configure GSSAPI authentication for a given domain. GSSAPI authentication uses an underlying mechanism (usually Kerberos) to establish a secure context and perform mutual authentication. To cover all domains, use "*". */ public void configureGSSAPI(String domain) { assert (domain != null); ZMsg msg = new ZMsg(); msg.add("GSSAPI"); msg.add(domain); msg.send(pipe); msg.destroy(); } /* * Callback for authorizing an authenticated GSS connection. Returns true * if the connection is authorized, false otherwise. Default implementation * authorizes all authenticated connections. */ protected boolean authenticateGSS(ZAPRequest request) { if (verbose) { System.out.printf("I: ALLOWED (GSSAPI allow any client) principal = %s identity = %s%n", request.principal, request.identity); } return true; } } jzmq-3.1.0/src/main/java/org/zeromq/ZContext.java000066400000000000000000000113511236001602100216450ustar00rootroot00000000000000package org.zeromq; import java.io.Closeable; import java.util.List; import java.util.ListIterator; import java.util.concurrent.CopyOnWriteArrayList; import org.zeromq.ZMQ.Context; import org.zeromq.ZMQ.Socket; /** * ZContext provides a high-level ZeroMQ context management class * * The ZContext class wraps java org.zeromq.Context objects, which in turn wrap native 0MQ contexts. It manages open * sockets in the context and automatically closes these before terminating the context. It provides a simple way to set * the linger timeout on sockets, and configure contexts for number of I/O threads. Sets-up signal (interrupt) handling * for the process. * * @see czmq version * * @author rsmith (at) rsbatechnology (dot) co (dot) uk */ public class ZContext implements Closeable { /** * Reference to underlying Context object */ private ZMQ.Context context; /** * List of sockets managed by this ZContext */ private List sockets; /** * Number of io threads allocated to this context, default 1 */ private int ioThreads; /** * Linger timeout, default 0 */ private int linger; /** * Indicates if context object is owned by main thread (useful for multi-threaded applications) */ private boolean main; /** * Class Constructor */ public ZContext() { context = null; // Don't create Context until create 1st 0MQ socket sockets = new CopyOnWriteArrayList(); ioThreads = 1; linger = 0; main = true; } /** * Destructor. Call this to gracefully terminate context and close any managed 0MQ sockets */ public void destroy() { ListIterator itr = sockets.listIterator(); while (itr.hasNext()) { destroySocket(itr.next()); } sockets.clear(); // Only terminate context if we are on the main thread if (isMain() && context != null) context.term(); } /** * Creates a new managed socket within this ZContext instance. Use this to get automatic management of the socket at * shutdown * * @param type socket type (see ZMQ static class members) * @return Newly created Socket object */ public Socket createSocket(int type) { if (context == null) context = ZMQ.context(ioThreads); // Create and register socket Socket socket = context.socket(type); sockets.add(socket); return socket; } /** * Destroys managed socket within this context and remove from sockets list * * @param s org.zeromq.Socket object to destroy */ public void destroySocket(Socket s) { if (s == null) return; if (sockets.contains(s)) { try { s.setLinger(linger); } catch (ZMQException e) { if (e.getErrorCode() != ZMQ.ETERM()) { throw e; } } s.close(); sockets.remove(s); } } /** * Creates new shadow context. Shares same underlying org.zeromq.Context instance but has own list of managed * sockets, io thread count etc. * * @param ctx Original ZContext to create shadow of * @return New ZContext */ public static ZContext shadow(ZContext ctx) { ZContext shadow = new ZContext(); shadow.setContext(ctx.getContext()); shadow.setMain(false); return shadow; } /** * @return the ioThreads */ public int getIoThreads() { return ioThreads; } /** * @param ioThreads the ioThreads to set */ public void setIoThreads(int ioThreads) { this.ioThreads = ioThreads; } /** * @return the linger */ public int getLinger() { return linger; } /** * @param linger the linger to set */ public void setLinger(int linger) { this.linger = linger; } /** * @return the main */ public boolean isMain() { return main; } /** * @param main the main to set */ public void setMain(boolean main) { this.main = main; } /** * @return the context */ public Context getContext() { return context; } /** * @param ctx sets the underlying org.zeromq.Context associated with this ZContext wrapper object */ public void setContext(Context ctx) { this.context = ctx; } /** * @return the sockets */ public List getSockets() { return sockets; } @Override public void close() { destroy(); } } jzmq-3.1.0/src/main/java/org/zeromq/ZDispatcher.java000066400000000000000000000141701236001602100223110ustar00rootroot00000000000000package org.zeromq; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.ConcurrentMap; import java.util.concurrent.CountDownLatch; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.LinkedBlockingQueue; import java.util.concurrent.atomic.AtomicBoolean; /** * Dispatcher for ZeroMQ Sockets. * * Warning: * The Dispatcher uses a busy spin loop when waiting on events. * This is ideal for low latency applications but not in all situations. * It has the side effect of consuming 100% of a CPU when waiting for events. * * With this dispatcher, you can register ONE handler per socket * and get a Sender for sending ZMsg. */ public class ZDispatcher { private ConcurrentMap dispatchers = new ConcurrentHashMap(); private final ExecutorService dispatcherExecutor; public ZDispatcher() { this.dispatcherExecutor = Executors.newCachedThreadPool(); } public ZDispatcher(ExecutorService dispatcherExecutor) { this.dispatcherExecutor = dispatcherExecutor; } public void registerHandler(ZMQ.Socket socket, ZMessageHandler messageHandler, ZSender sender) { registerHandler(socket, messageHandler, sender, Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors())); } public void registerHandler(ZMQ.Socket socket, ZMessageHandler messageHandler, ZSender sender, ExecutorService threadpool) { SocketDispatcher socketDispatcher = new SocketDispatcher(socket, messageHandler, sender, threadpool); if (dispatchers.putIfAbsent(socket, socketDispatcher) != null) { throw new IllegalArgumentException("This socket already have a message handler"); } socketDispatcher.start(); dispatcherExecutor.execute(socketDispatcher); } public void unregisterHandler(ZMQ.Socket socket) { SocketDispatcher removedDispatcher = dispatchers.remove(socket); if (removedDispatcher == null) { throw new IllegalArgumentException("This socket doesn't have a message handler"); } removedDispatcher.shutdown(); } public void shutdown() { dispatcherExecutor.shutdown(); for (SocketDispatcher socketDispatcher : dispatchers.values()) { socketDispatcher.shutdown(); } dispatchers.clear(); } public interface ZMessageHandler { public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg); } public final static class ZSender { private final BlockingQueue out = new LinkedBlockingQueue(); public final boolean send(ZMsg msg) { return out.add(msg); } } private static final class SocketDispatcher implements Runnable { private volatile boolean active = false; private final CountDownLatch shutdownLatch = new CountDownLatch(1); private final ZMQ.Socket socket; private final ZMessageHandler handler; private final ZSender sender; private final ExecutorService threadpool; private final BlockingQueue in = new LinkedBlockingQueue(); private static final int BUFFER_SIZE = 1024; private static final ThreadLocal messages = new ThreadLocal() { @Override protected ZMessageBuffer initialValue() { return new ZMessageBuffer(); } }; private final AtomicBoolean busy = new AtomicBoolean(false); public SocketDispatcher(ZMQ.Socket socket, ZMessageHandler handler, ZSender sender, ExecutorService handleThreadpool) { this.socket = socket; this.handler = handler; this.sender = sender; this.threadpool = handleThreadpool; } public void run() { while (active) { doReceive(); doHandle(); doSend(); } threadpool.shutdown(); shutdownLatch.countDown(); } public void start() { this.active = true; } public void shutdown() { try { this.active = false; this.shutdownLatch.await(); } catch (InterruptedException e) { } } private void doReceive() { ZMsg msg; int remainingBuffer = BUFFER_SIZE; while (active && remainingBuffer-- > 0 && (msg = ZMsg.recvMsg(socket, ZMQ.DONTWAIT)) != null && msg.size() > 0 && msg.getFirst().hasData()) { in.add(msg); } } private void doHandle() { if (!in.isEmpty() && busy.compareAndSet(false, true)) { threadpool.submit(new Runnable() { @Override public void run() { ZMessageBuffer messages = SocketDispatcher.this.messages.get(); messages.drainFrom(in); busy.set(false); for (int i = 0; i <= messages.lastValidIndex; i++) { if (active) { handler.handleMessage(sender, messages.buffer[i]); } } } }); } } private void doSend() { ZMsg msg; int remainingBuffer = BUFFER_SIZE; while (active && remainingBuffer-- > 0 && (msg = sender.out.poll()) != null) { msg.send(socket); } } private static class ZMessageBuffer { private final ZMsg[] buffer = new ZMsg[BUFFER_SIZE]; private int lastValidIndex; private void drainFrom(BlockingQueue in) { int lastIndex = lastValidIndex = -1; ZMsg msg; while (++lastIndex < buffer.length && (msg = in.poll()) != null) { buffer[lastIndex] = msg; lastValidIndex = lastIndex; } } } } } jzmq-3.1.0/src/main/java/org/zeromq/ZFrame.java000066400000000000000000000245521236001602100212620ustar00rootroot00000000000000package org.zeromq; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.Arrays; import org.zeromq.ZMQ.Socket; /** * ZFrame * * The ZFrame class provides methods to send and receive single message frames across 0MQ sockets. A 'frame' corresponds * to one underlying zmq_msg_t in the libzmq code. When you read a frame from a socket, the more() method indicates if * the frame is part of an unfinished multipart message. The send() method normally destroys the frame, but with the * ZFRAME_REUSE flag, you can send the same frame many times. Frames are binary, and this class has no special support * for text data. * * Based on zframe.c in czmq * * @author rsmith (at) rsbatechnology (dot) co (dot) uk * * */ public class ZFrame { public static final int MORE = ZMQ.SNDMORE; public static final int REUSE = 128; // no effect at java public static final int DONTWAIT = ZMQ.DONTWAIT; private boolean more; private byte[] data; /** * Class Constructor Creates an empty frame. (Useful when reading frames from a 0MQ Socket) */ protected ZFrame() { // Empty constructor } /** * Class Constructor Copies message data into ZFrame object * * @param data Data to copy into ZFrame object */ public ZFrame(byte[] data) { if (data != null) { this.data = (byte[]) data.clone(); } } /** * Class Constructor Copies String into frame data * * @param data */ public ZFrame(String data) { if (data != null) { this.data = data.getBytes(); } } /** * Destructor. */ public void destroy() { if (hasData()) data = null; } /** * @return the data */ public byte[] getData() { return data; } /** * @return More flag, true if last read had MORE message parts to come */ public boolean hasMore() { return more; } /** * Returns byte size of frame, if set, else 0 * * @return Number of bytes in frame data, else 0 */ public int size() { if (hasData()) return data.length; else return 0; } /** * Convenience method to ascertain if this frame contains some message data * * @return True if frame contains data */ public boolean hasData() { return data != null; } /** * Method to call org.zeromq.Socket send() method. * * @param socket 0MQ socket to send on * @param flags Valid send() method flags, defined in org.zeromq.ZMQ class * @return True if success, else False */ public boolean send(Socket socket, int flags) { if (socket == null) { throw new IllegalArgumentException("socket parameter must be set"); } if (!hasData()) { throw new IllegalAccessError("Cannot send frame without data"); } // Note the jzmq Socket.cpp JNI class does a memcpy of the byte data before calling // the 0MQ send function, so don't have to clone the message data again here. return socket.send(data, flags); } /** * Sends frame to socket if it contains any data. Frame contents are kept after the send. * * @param socket 0MQ socket to send frame * @param flags Valid send() method flags, defined in org.zeromq.ZMQ class * @return True if success, else False */ public boolean sendAndKeep(Socket socket, int flags) { return send(socket, flags); } /** * Sends frame to socket if it contains any data. Frame contents are kept after the send. Uses default behaviour of * Socket.send() method, with no flags set * * @param socket 0MQ socket to send frame * @return True if success, else False */ public boolean sendAndKeep(Socket socket) { return sendAndKeep(socket, 0); } /** * Sends frame to socket if it contains data. Use this method to send a frame and destroy the data after. * * @param socket 0MQ socket to send frame * @param flags Valid send() method flags, defined in org.zeromq.ZMQ class * @return True if success, else False */ public boolean sendAndDestroy(Socket socket, int flags) { boolean ret = send(socket, flags); if (ret) destroy(); return ret; } /** * Sends frame to socket if it contains data. Use this method to send an isolated frame and destroy the data after. * Uses default behaviour of Socket.send() method, with no flags set * * @param socket 0MQ socket to send frame * @return True if success, else False */ public boolean sendAndDestroy(Socket socket) { return sendAndDestroy(socket, 0); } /** * Creates a new frame that duplicates an existing frame * * @return Duplicate of frame; message contents copied into new byte array */ public ZFrame duplicate() { return new ZFrame(this.data.clone()); } /** * Returns true if both frames have byte - for byte identical data * * @param other The other ZFrame to compare * @return True if both ZFrames have same byte-identical data, else false */ public boolean hasSameData(ZFrame other) { if (other == null) return false; if (size() == other.size()) { if (hasData() && other.hasData()) { for (int i = 0; i < size(); i++) { if (this.data[i] != other.data[i]) return false; } return true; } } return false; } /** * Sets new contents for frame * * @param data New byte array contents for frame */ public void reset(byte[] data) { this.data = data; } /** * Sets new contents for frame * * @param data String contents for frame */ public void reset(String data) { reset(data.getBytes()); } /** * Returns frame data as a printable hex string * * @return */ public String strhex() { String hexChar = "0123456789ABCDEF"; StringBuilder b = new StringBuilder(); for (int nbr = 0; nbr < data.length; nbr++) { int b1 = data[nbr] >>> 4 & 0xf; int b2 = data[nbr] & 0xf; b.append(hexChar.charAt(b1)); b.append(hexChar.charAt(b2)); } return b.toString(); } /** * String equals. Uses String compareTo for the comparison (lexigraphical) * * @param str String to compare with frame data * @return True if frame body data matches given string */ public boolean streq(String str) { if (!hasData()) return false; return new String(this.data).compareTo(str) == 0; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ZFrame zFrame = (ZFrame) o; if (!Arrays.equals(data, zFrame.data)) return false; return true; } @Override public int hashCode() { return data != null ? Arrays.hashCode(data) : 0; } /** * Returns a human - readable representation of frame's data * * @return A text string or hex-encoded string if data contains any non-printable ASCII characters */ public String toString() { if (!hasData()) return null; // Dump message as text or hex-encoded string boolean isText = true; for (int i = 0; i < data.length; i++) { if (data[i] < 32 || data[i] > 127) isText = false; } if (isText) return new String(data); else return strhex(); } /** * Internal method to call recv on the socket. Does not trap any ZMQExceptions but expects caling routine to handle * them. * * @param socket 0MQ socket to read from * @return Byte array */ private byte[] recv(Socket socket, int flags) { if (socket == null) throw new IllegalArgumentException("socket parameter must not be null"); data = socket.recv(flags); more = socket.hasReceiveMore(); return data; } /** * Receives single frame from socket, returns the received frame object, or null if the recv was interrupted. Does a * blocking recv, if you want to not block then use recvFrame(socket, ZMQ.DONTWAIT); * * @param socket Socket to read from * @return received frame, else null */ public static ZFrame recvFrame(Socket socket) { ZFrame f = new ZFrame(); f.recv(socket, 0); return f; } /** * Receive a new frame off the socket, Returns newly-allocated frame, or null if there was no input waiting, or if * the read was interrupted. * * @param socket Socket to read from * @param flags Pass flags to 0MQ socket.recv call * @return received frame, else null */ public static ZFrame recvFrame(Socket socket, int flags) { ZFrame f = new ZFrame(); f.recv(socket, flags); return f; } public void print(String prefix) { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); if (prefix != null) pw.printf("%s", prefix); byte[] data = getData(); int size = size(); boolean is_bin = false; int char_nbr; for (char_nbr = 0; char_nbr < size; char_nbr++) if (data[char_nbr] < 9 || data[char_nbr] > 127) is_bin = true; pw.printf("[%03d] ", size); int max_size = is_bin ? 35 : 70; String elipsis = ""; if (size > max_size) { size = max_size; elipsis = "..."; } for (char_nbr = 0; char_nbr < size; char_nbr++) { if (is_bin) pw.printf("%02X", data[char_nbr]); else pw.printf("%c", data[char_nbr]); } pw.printf("%s\n", elipsis); pw.flush(); pw.close(); try { sw.close(); } catch (IOException e) { } System.out.print(sw.toString()); } } jzmq-3.1.0/src/main/java/org/zeromq/ZLoop.java000066400000000000000000000271731236001602100211430ustar00rootroot00000000000000/* Copyright (c) 1991-2011 iMatix Corporation Copyright other contributors as noted in the AUTHORS file. This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ package org.zeromq; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.zeromq.ZMQ.PollItem; import org.zeromq.ZMQ.Poller; /** * The ZLoop class provides an event-driven reactor pattern. The reactor handles zmq.PollItem items (pollers or writers, * sockets or fds), and once-off or repeated timers. Its resolution is 1 msec. It uses a tickless timer to reduce CPU * interrupts in inactive processes. */ public class ZLoop { public static interface IZLoopHandler { public int handle(ZLoop loop, PollItem item, Object arg); } private class SPoller { PollItem item; IZLoopHandler handler; Object arg; int errors; // If too many errors, kill poller protected SPoller(PollItem item, IZLoopHandler handler, Object arg) { this.item = item; this.handler = handler; this.arg = arg; errors = 0; } } ; private class STimer { int delay; int times; IZLoopHandler handler; Object arg; long when; // Clock time when alarm goes off public STimer(int delay, int times, IZLoopHandler handler, Object arg) { this.delay = delay; this.times = times; this.handler = handler; this.arg = arg; this.when = -1; } } private final List pollers; // List of poll items private final List timers; // List of timers private int pollSize; // Size of poll set private Poller pollset; // zmq_poll set private SPoller[] pollact; // Pollers for this poll set private boolean dirty; // True if pollset needs rebuilding private boolean verbose; // True if verbose tracing wanted private final List zombies; // List of timers to kill private final List newTimers; // List of timers to add public ZLoop() { pollers = new ArrayList(); timers = new ArrayList(); zombies = new ArrayList(); newTimers = new ArrayList(); } public void destroy() { // do nothing } // We hold an array of pollers that matches the pollset, so we can // register/cancel pollers orthogonally to executing the pollset // activity on pollers. Returns 0 on success, -1 on failure. private void rebuild() { pollact = null; pollSize = pollers.size(); pollset = new Poller(pollSize); pollact = new SPoller[pollSize]; int itemNbr = 0; for (SPoller poller : pollers) { pollset.register(poller.item); pollact[itemNbr] = poller; itemNbr++; } dirty = false; } private long ticklessTimer() { // Calculate tickless timer, up to 1 hour long tickless = System.currentTimeMillis() + 1000 * 3600; for (STimer timer : timers) { if (timer.when == -1) timer.when = timer.delay + System.currentTimeMillis(); if (tickless > timer.when) tickless = timer.when; } long timeout = tickless - System.currentTimeMillis(); if (timeout < 0) timeout = 0; if (verbose) System.out.printf("I: zloop: polling for %d msec\n", timeout); return timeout; } // -------------------------------------------------------------------------- // Register pollitem with the reactor. When the pollitem is ready, will call // the handler, passing the arg. Returns 0 if OK, -1 if there was an error. // If you register the pollitem more than once, each instance will invoke its // corresponding handler. public int addPoller(PollItem item_, IZLoopHandler handler, Object arg) { PollItem item = item_; if (item.getRawSocket() == null && item.getSocket() == null) return -1; SPoller poller = new SPoller(item_, handler, arg); pollers.add(poller); dirty = true; if (verbose) System.out.printf("I: zloop: register %s poller (%s, %s)\n", item.getSocket() != null ? item.getSocket() .getType() : "RAW", item.getSocket(), item.getRawSocket()); return 0; } // -------------------------------------------------------------------------- // Cancel a pollitem from the reactor, specified by socket or FD. If both // are specified, uses only socket. If multiple poll items exist for same // socket/FD, cancels ALL of them. public void removePoller(PollItem item_) { PollItem item = item_; Iterator it = pollers.iterator(); while (it.hasNext()) { SPoller p = it.next(); if (item.equals(p.item)) { it.remove(); dirty = true; } } if (verbose) System.out.printf("I: zloop: cancel %s poller (%s, %s)", item.getSocket() != null ? item.getSocket() .getType() : "RAW", item.getSocket(), item.getRawSocket()); } // -------------------------------------------------------------------------- // Register a timer that expires after some delay and repeats some number of // times. At each expiry, will call the handler, passing the arg. To // run a timer forever, use 0 times. Returns 0 if OK, -1 if there was an // error. public int addTimer(int delay, int times, IZLoopHandler handler, Object arg) { STimer timer = new STimer(delay, times, handler, arg); // We cannot touch self->timers because we may be executing that // from inside the poll loop. So, we hold the new timer on the newTimers // list, and process that list when we're done executing timers. newTimers.add(timer); if (verbose) System.out.printf("I: zloop: register timer delay=%d times=%d\n", delay, times); return 0; } // -------------------------------------------------------------------------- // Cancel all timers for a specific argument (as provided in zloop_timer) // Returns 0 on success. public int removeTimer(Object arg) { assert (arg != null); // We cannot touch self->timers because we may be executing that // from inside the poll loop. So, we hold the arg on the zombie // list, and process that list when we're done executing timers. zombies.add(arg); if (verbose) System.out.printf("I: zloop: cancel timer\n"); return 0; } // -------------------------------------------------------------------------- // Set verbose tracing of reactor on/off public void verbose(boolean verbose) { this.verbose = verbose; } // -------------------------------------------------------------------------- // Start the reactor. Takes control of the thread and returns when the 0MQ // context is terminated or the process is interrupted, or any event handler // returns -1. Event handlers may register new sockets and timers, and // cancel sockets. Returns 0 if interrupted, -1 if cancelled by a // handler, positive on internal error public int start() { int rc = 0; timers.addAll(newTimers); newTimers.clear(); // Recalculate all timers now for (STimer timer : timers) { timer.when = timer.delay + System.currentTimeMillis(); } // Main reactor loop while (!Thread.currentThread().isInterrupted()) { if (dirty) { // If s_rebuild_pollset() fails, break out of the loop and // return its error rebuild(); } long wait = ticklessTimer(); rc = pollset.poll(wait); if (rc == -1) { if (verbose) System.out.printf("I: zloop: interrupted (%d)\n", rc); rc = 0; break; // Context has been shut down } // Handle any timers that have now expired Iterator it = timers.iterator(); while (it.hasNext()) { STimer timer = it.next(); if (System.currentTimeMillis() >= timer.when && timer.when != -1) { if (verbose) System.out.println("I: zloop: call timer handler"); rc = timer.handler.handle(this, null, timer.arg); if (rc == -1) break; // Timer handler signalled break if (timer.times != 0 && --timer.times == 0) { it.remove(); } else timer.when = timer.delay + System.currentTimeMillis(); } } if (rc == -1) break; // Some timer signalled break from the reactor loop // Handle any pollers that are ready for (int itemNbr = 0; itemNbr < pollSize; itemNbr++) { SPoller poller = pollact[itemNbr]; if (pollset.getItem(itemNbr).isError()) { if (verbose) System.out.printf("I: zloop: can't poll %s socket (%s, %s)", poller.item.getSocket() != null ? poller.item.getSocket().getType() : "RAW", poller.item.getSocket(), poller.item.getRawSocket()); // Give handler one chance to handle error, then kill // poller because it'll disrupt the reactor otherwise. if (poller.errors++ > 0) { removePoller(poller.item); } } else poller.errors = 0; // A non-error happened if (pollset.getItem(itemNbr).readyOps() > 0) { if (verbose) System.out.printf("I: zloop: call %s socket handler (%s, %s)\n", poller.item.getSocket() != null ? poller.item.getSocket().getType() : "RAW", poller.item.getSocket(), poller.item.getRawSocket()); rc = poller.handler.handle(this, poller.item, poller.arg); if (rc == -1) break; // Poller handler signalled break } } // Now handle any timer zombies // This is going to be slow if we have many zombies for (Object arg : zombies) { it = timers.iterator(); while (it.hasNext()) { STimer timer = it.next(); if (timer.arg == arg) { it.remove(); } } } // Now handle any new timers added inside the loop timers.addAll(newTimers); newTimers.clear(); if (rc == -1) break; } return rc; } } jzmq-3.1.0/src/main/java/org/zeromq/ZMQ.java000066400000000000000000002331261236001602100205440ustar00rootroot00000000000000/* Copyright (c) 2007-2010 iMatix Corporation This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program. If not, see . */ package org.zeromq; import java.io.Closeable; import java.nio.ByteBuffer; import java.nio.charset.Charset; import java.nio.channels.SelectableChannel; import java.util.LinkedList; import java.util.Random; import java.util.concurrent.atomic.AtomicBoolean; /** * ZeroMQ JNI Bindings. * * @author Gonzalo Diethelm * */ public class ZMQ { static { // if no embedded native library, revert to loading from java.library.path if (!EmbeddedLibraryTools.LOADED_EMBEDDED_LIBRARY) System.loadLibrary("jzmq"); } // Values for flags in Socket's send and recv functions. /** * Socket flag to indicate a nonblocking send or recv mode. */ public static final int NOBLOCK = 1; public static final int DONTWAIT = 1; /** * Socket flag to indicate that more message parts are coming. */ public static final int SNDMORE = 2; // Socket types, used when creating a Socket. /** * Flag to specify a exclusive pair of items. */ public static final int PAIR = 0; /** * Flag to specify a PUB socket, receiving side must be a SUB or XSUB. */ public static final int PUB = 1; /** * Flag to specify the receiving part of the PUB or XPUB socket. */ public static final int SUB = 2; /** * Flag to specify a REQ socket, receiving side must be a REP. */ public static final int REQ = 3; /** * Flag to specify the receiving part of a REQ socket. */ public static final int REP = 4; /** * Flag to specify a DEALER socket (aka XREQ). DEALER is really a combined ventilator / sink that does * load-balancing on output and fair-queuing on input with no other semantics. It is the only socket type that lets * you shuffle messages out to N nodes and shuffle the replies back, in a raw bidirectional asynch pattern. */ public static final int DEALER = 5; /** * Old alias for DEALER flag. Flag to specify a XREQ socket, receiving side must be a XREP. * * @deprecated As of release 3.0 of zeromq, replaced by {@link #DEALER} */ public static final int XREQ = DEALER; /** * Flag to specify ROUTER socket (aka XREP). ROUTER is the socket that creates and consumes request-reply routing * envelopes. It is the only socket type that lets you route messages to specific connections if you know their * identities. */ public static final int ROUTER = 6; /** * Old alias for ROUTER flag. Flag to specify the receiving part of a XREQ socket. * * @deprecated As of release 3.0 of zeromq, replaced by {@link #ROUTER} */ public static final int XREP = ROUTER; /** * Flag to specify the receiving part of a PUSH socket. */ public static final int PULL = 7; /** * Flag to specify a PUSH socket, receiving side must be a PULL. */ public static final int PUSH = 8; /** * Flag to specify a XPUB socket, receiving side must be a SUB or XSUB. Subscriptions can be received as a message. * Subscriptions start with a '1' byte. Unsubscriptions start with a '0' byte. */ public static final int XPUB = 9; /** * Flag to specify the receiving part of the PUB or XPUB socket. Allows */ public static final int XSUB = 10; /** * Flag to specify a STREAMER device. */ public static final int STREAMER = 1; /** * Flag to specify a FORWARDER device. */ public static final int FORWARDER = 2; /** * Flag to specify a QUEUE device. */ public static final int QUEUE = 3; /** * @see ZMQ#PULL */ @Deprecated public static final int UPSTREAM = PULL; /** * @see ZMQ#PUSH */ @Deprecated public static final int DOWNSTREAM = PUSH; /** * EVENT_CONNECTED: connection established. * The EVENT_CONNECTED event triggers when a connection has been * established to a remote peer. This can happen either synchronous * or asynchronous. Value is the FD of the newly connected socket. */ public static final int EVENT_CONNECTED = 1; /** * EVENT_CONNECT_DELAYED: synchronous connect failed, it's being polled. * The EVENT_CONNECT_DELAYED event triggers when an immediate connection * attempt is delayed and its completion is being polled for. Value has * no meaning. */ public static final int EVENT_CONNECT_DELAYED = 2; /** * EVENT_CONNECT_RETRIED: asynchronous connect / reconnection attempt. * The EVENT_CONNECT_RETRIED event triggers when a connection attempt is * being handled by reconnect timer. The reconnect interval's recomputed * for each attempt. Value is the reconnect interval. */ public static final int EVENT_CONNECT_RETRIED = 4; /** * EVENT_LISTENING: socket bound to an address, ready to accept connections. * The EVENT_LISTENING event triggers when a socket's successfully bound to * a an interface. Value is the FD of the newly bound socket. */ public static final int EVENT_LISTENING = 8; /** * EVENT_BIND_FAILED: socket could not bind to an address. * The EVENT_BIND_FAILED event triggers when a socket could not bind to a * given interface. Value is the errno generated by the bind call. */ public static final int EVENT_BIND_FAILED = 16; /** * EVENT_ACCEPTED: connection accepted to bound interface. * The EVENT_ACCEPTED event triggers when a connection from a remote peer * has been established with a socket's listen address. Value is the FD of * the accepted socket. */ public static final int EVENT_ACCEPTED = 32; /** * EVENT_ACCEPT_FAILED: could not accept client connection. * The EVENT_ACCEPT_FAILED event triggers when a connection attempt to a * socket's bound address fails. Value is the errno generated by accept. */ public static final int EVENT_ACCEPT_FAILED = 64; /** * EVENT_CLOSED: connection closed. * The EVENT_CLOSED event triggers when a connection's underlying * descriptor has been closed. Value is the former FD of the for the * closed socket. FD has been closed already! */ public static final int EVENT_CLOSED = 128; /** * EVENT_CLOSE_FAILED: connection couldn't be closed. * The EVENT_CLOSE_FAILED event triggers when a descriptor could not be * released back to the OS. Implementation note: ONLY FOR IPC SOCKETS. * Value is the errno generated by unlink. */ public static final int EVENT_CLOSE_FAILED = 256; /** * EVENT_DISCONNECTED: broken session. * The EVENT_DISCONNECTED event triggers when the stream engine (tcp and * ipc specific) detects a corrupted / broken session. Value is the FD of * the socket. */ public static final int EVENT_DISCONNECTED = 512; /** * EVENT_MONITOR_STOPPED: monitor has been stopped. * The EVENT_MONITOR_STOPPED event triggers when the monitor for a socket is * stopped. */ public static final int EVENT_MONITOR_STOPPED = 1024; /** * EVENT_ALL: all events known by the java binding. * The EVENT_ALL constant can be used to set up a monitor for all events known * by the java binding. One could add more flags */ public static final int EVENT_ALL = EVENT_CONNECTED | EVENT_CONNECT_DELAYED | EVENT_CONNECT_RETRIED | EVENT_LISTENING | EVENT_BIND_FAILED | EVENT_ACCEPTED | EVENT_ACCEPT_FAILED | EVENT_CLOSED | EVENT_CLOSE_FAILED | EVENT_DISCONNECTED | EVENT_MONITOR_STOPPED; /** * @return Major version number of the ZMQ library. */ public static int getMajorVersion() { return version_major(); } /** * @return Major version number of the ZMQ library. */ public static int getMinorVersion() { return version_minor(); } /** * @return Major version number of the ZMQ library. */ public static int getPatchVersion() { return version_patch(); } /** * @return Full version number of the ZMQ library used for comparing versions. */ public static int getFullVersion() { return version_full(); } /** * @param major Version major component. * @param minor Version minor component. * @param patch Version patch component. * * @return Comparible single int version number. */ public static int makeVersion(final int major, final int minor, final int patch) { return make_version(major, minor, patch); } /** * @return String version number in the form major.minor.patch. */ public static String getVersionString() { return String.format("%d.%d.%d", version_major(), version_minor(), version_patch()); } /** * Starts the built-in 0MQ proxy in the current application thread. The proxy connects a frontend socket to a * backend socket. Conceptually, data flows from frontend to backend. Depending on the socket types, replies may * flow in the opposite direction. The direction is conceptual only; the proxy is fully symmetric and there is no * technical difference between frontend and backend. * * Before calling ZMQ.proxy() you must set any socket options, and connect or bind both frontend and backend * sockets. The two conventional proxy models are: * * ZMQ.proxy() runs in the current thread and returns only if/when the current context is closed. * * @param frontend ZMQ.Socket * @param backend ZMQ.Socket * @param capture If the capture socket is not NULL, the proxy shall send all messages, received on both frontend * and backend, to the capture socket. The capture socket should be a ZMQ_PUB, ZMQ_DEALER, ZMQ_PUSH, or * ZMQ_PAIR socket. * @since 3.2.2 */ public static void proxy(Socket frontend, Socket backend, Socket capture) { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) throw new UnsupportedOperationException(); run_proxy(frontend, backend, capture); } /** * Poll on polling items until timeout * * @param items polling items * @param timeout timeout in millisecond * @return number of events */ public static int poll(PollItem[] items, long timeout) { return poll(items, items.length, timeout); } /** * Poll on polling items until timeout * * @param items polling items * @param count active item count * @param timeout timeout in millisecond * @return number of events */ public static int poll(PollItem[] items, int count, long timeout) { return Poller.run_poll(items, count, timeout); } protected static native int version_full(); protected static native int version_major(); protected static native int version_minor(); protected static native int version_patch(); protected static native int make_version(int major, int minor, int patch); protected static native long ENOTSUP(); protected static native long EPROTONOSUPPORT(); protected static native long ENOBUFS(); protected static native long ENETDOWN(); protected static native long EADDRINUSE(); protected static native long EADDRNOTAVAIL(); protected static native long ECONNREFUSED(); protected static native long EINPROGRESS(); protected static native long EHOSTUNREACH(); protected static native long EMTHREAD(); protected static native long EFSM(); protected static native long ENOCOMPATPROTO(); protected static native long ETERM(); protected static native long ENOTSOCK(); private static native void run_proxy(Socket frontend, Socket backend, Socket capture); /** * Inner class: Error. */ public enum Error { ENOTSUP(ENOTSUP()), EPROTONOSUPPORT(EPROTONOSUPPORT()), ENOBUFS(ENOBUFS()), ENETDOWN(ENETDOWN()), EADDRINUSE(EADDRINUSE()), EADDRNOTAVAIL(EADDRNOTAVAIL()), ECONNREFUSED(ECONNREFUSED()), EINPROGRESS(EINPROGRESS()), EHOSTUNREACH(EHOSTUNREACH()), EMTHREAD(EMTHREAD()), EFSM(EFSM()), ENOCOMPATPROTO(ENOCOMPATPROTO()), ETERM(ETERM()), ENOTSOCK(ENOTSOCK()); private final long code; Error(long code) { this.code = code; } public long getCode() { return code; } public static Error findByCode(int code) { for (Error e : Error.class.getEnumConstants()) { if (e.getCode() == code) { return e; } } throw new IllegalArgumentException("Unknown " + Error.class.getName() + " enum code:" + code); } } /** * Create a new Context. * * @param ioThreads Number of threads to use, usually 1 is sufficient for most use cases. * @return the Context */ public static Context context(int ioThreads) { return new Context(ioThreads); } /** * Inner class: Context. */ public static class Context implements Closeable { private final AtomicBoolean closed = new AtomicBoolean(false); /** * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ Context has been disposed * of. */ public void term() { if(closed.compareAndSet(false, true)) { destroy(); } } /** * Create a new Socket within this context. * * @param type the socket type. * @return the newly created Socket. */ public Socket socket(int type) { return new Socket(this, type); } /** * Create a new Poller within this context, with a default size. * * @return the newly created Poller. * @deprecated use Poller constructor */ public Poller poller() { return new Poller(this); } /** * Create a new Poller within this context, with a specified initial size. * * @param size the poller initial size. * @return the newly created Poller. * @deprecated use Poller constructor */ public Poller poller(int size) { return new Poller(this, size); } /** * Class constructor. * * @param ioThreads size of the threads pool to handle I/O operations. */ protected Context(int ioThreads) { construct(ioThreads); } /** Initialize the JNI interface */ protected native void construct(int ioThreads); /** Free all resources used by JNI interface. */ protected native void destroy(); /** * Get the underlying context handle. This is private because it is only accessed from JNI, where Java access * controls are ignored. * * @return the internal 0MQ context handle. */ private long getContextHandle() { return this.contextHandle; } /** Opaque data used by JNI driver. */ private long contextHandle; public void close() { term(); } /** * Sets the maximum number of sockets allowed on the context */ public native boolean setMaxSockets(int maxSockets); /** * The maximum number of sockets allowed on the context */ public native int getMaxSockets(); } /** * Inner class: Socket. */ public static class Socket implements Closeable { private static native void nativeInit(); static { if (!EmbeddedLibraryTools.LOADED_EMBEDDED_LIBRARY) System.loadLibrary("jzmq"); nativeInit(); } private final AtomicBoolean closed = new AtomicBoolean(false); /** * This is an explicit "destructor". It can be called to ensure the corresponding 0MQ Socket has been disposed * of. */ public void close() { if(closed.compareAndSet(false, true)) { destroy(); } } /** * The 'ZMQ_TYPE option shall retrieve the socket type for the specified 'socket'. The socket type is specified * at socket creation time and cannot be modified afterwards. * * @return the socket type. * @since 2.1.0 */ public int getType() { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0)) return -1; return (int) getLongSockopt(TYPE); } /** * @see #setLinger(long) * * @return the linger period. * @since 2.1.0 */ public long getLinger() { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0)) return -1; return getLongSockopt(LINGER); } /** * @see #setReconnectIVL(long) * * @return the reconnectIVL. * @since 3.0.0 */ public long getReconnectIVL() { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10)) return -1; return getLongSockopt(RECONNECT_IVL); } /** * @see #setBacklog(long) * * @return the backlog. * @since 3.0.0 */ public long getBacklog() { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return -1; return getLongSockopt(BACKLOG); } /** * @see #setReconnectIVLMax(long) * * @return the reconnectIVLMax. * @since 3.0.0 */ public long getReconnectIVLMax() { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10)) return -1; return getLongSockopt(RECONNECT_IVL_MAX); } /** * @see #setMaxMsgSize(long) * * @return the maxMsgSize. * @since 3.0.0 */ public long getMaxMsgSize() { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return -1; return getLongSockopt(MAXMSGSIZE); } /** * @see #setSndHWM(long) * * @return the SndHWM. * @since 3.0.0 */ public long getSndHWM() { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return -1; return getLongSockopt(SNDHWM); } /** * @see #setRcvHWM(long) * * @return the recvHWM period. * @since 3.0.0 */ public long getRcvHWM() { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return -1; return getLongSockopt(RCVHWM); } /** * @see #setHWM(long) * * @return the High Water Mark. */ public long getHWM() { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) return -1; return getLongSockopt(HWM); } /** * @see #setSwap(long) * * @return the number of messages to swap at most. */ public long getSwap() { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) return -1; return getLongSockopt(SWAP); } /** * @see #setAffinity(long) * * @return the affinity. */ public long getAffinity() { return getLongSockopt(AFFINITY); } /** * @see #setTCPKeepAlive(long) * * @return the keep alive setting. */ public long getTCPKeepAliveSetting() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 0)) return -1; return getLongSockopt(KEEPALIVE); } /** * @see #setTCPKeepAliveIdle(long) * * @return the keep alive idle value. */ public long getTCPKeepAliveIdle() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 0)) return -1; return getLongSockopt(KEEPALIVEIDLE); } /** * @see #setTCPKeepAliveInterval(long) * * @return the keep alive interval. */ public long getTCPKeepAliveInterval() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 0)) return -1; return getLongSockopt(KEEPALIVEINTVL); } /** * @see #setTCPKeepAliveCount(long) * * @return the keep alive count. */ public long getTCPKeepAliveCount() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 0)) return -1; return getLongSockopt(KEEPALIVECNT); } /** * @see #setIdentity(byte[]) * * @return the Identitiy. */ public byte[] getIdentity() { return getBytesSockopt(IDENTITY); } /** * @see #setRate(long) * * @return the Rate. */ public long getRate() { return getLongSockopt(RATE); } /** * @see #setRecoveryInterval(long) * * @return the RecoveryIntervall. */ public long getRecoveryInterval() { return getLongSockopt(RECOVERY_IVL); } /** * @see #setMulticastLoop(boolean) * * @return the Multicast Loop. */ public boolean hasMulticastLoop() { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return false; return getLongSockopt(MCAST_LOOP) != 0; } /** * Sets the time-to-live field in every multicast packet sent from this socket. The default is 1 which means * that the multicast packets don't leave the local network. * * @param mcast_hops */ public void setMulticastHops(long mcast_hops) { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return; setLongSockopt(MULTICAST_HOPS, mcast_hops); } /** * @see #setMulticastHops(long) * * @return the Multicast Hops. */ public long getMulticastHops() { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return 1; return getLongSockopt(MULTICAST_HOPS); } /** * Sets the timeout for receive operation on the socket. If the value is 0, recv will return immediately, with a * EAGAIN error if there is no message to receive. If the value is -1, it will block until a message is * available. For all other values, it will wait for a message for that amount of time before returning with an * EAGAIN error. * * @param timeout Timeout for receive operation in milliseconds. Default -1 (infinite) */ public void setReceiveTimeOut(int timeout) { if (ZMQ.version_full() < ZMQ.make_version(2, 2, 0)) return; setLongSockopt(RCVTIMEO, timeout); } /** * @see #setReceiveTimeOut(int) * * @return the Receive Timeout in milliseconds */ public int getReceiveTimeOut() { if (ZMQ.version_full() < ZMQ.make_version(2, 2, 0)) return -1; return (int) getLongSockopt(RCVTIMEO); } /** * Sets the timeout for send operation on the socket. If the value is 0, send will return immediately, with a * EAGAIN error if the message cannot be sent. If the value is -1, it will block until the message is sent. For * all other values, it will try to send the message for that amount of time before returning with an EAGAIN * error. * * @param timeout Timeout for send operation in milliseconds. Default -1 (infinite) */ public void setSendTimeOut(int timeout) { if (ZMQ.version_full() < ZMQ.make_version(2, 2, 0)) return; setLongSockopt(SNDTIMEO, timeout); } /** * @see #setSendTimeOut(int) * * @return the Send Timeout. in milliseconds */ public int getSendTimeOut() { if (ZMQ.version_full() < ZMQ.make_version(2, 2, 0)) return -1; return (int) getLongSockopt(SNDTIMEO); } /** * @see #setSendBufferSize(long) * * @return the kernel send buffer size. */ public long getSendBufferSize() { return getLongSockopt(SNDBUF); } /** * @see #setReceiveBufferSize(long) * * @return the kernel receive buffer size. */ public long getReceiveBufferSize() { return getLongSockopt(RCVBUF); } /** * @see #setIPv4Only(boolean) * * @return the IPv4 only socket. */ public boolean getIPv4Only() { return getLongSockopt(IPV4ONLY) == 1; } /** * @see #setPlainServer(boolean) * * @return if the socket is setup for PLAIN security */ public boolean getPlainServer() { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { return getLongSockopt(PLAIN_SERVER) == 1; } return false; } /** * @see #setPlainUsername(byte[]) * * @return null terminated byte array in server charset */ public byte[] getPlainUsername() { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { return getBytesSockopt(PLAIN_USERNAME); } return null; } /** * @see #setPlainPassword(byte[]) * * @return null terminated byte array in server charset */ public byte[] getPlainPassword() { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { return getBytesSockopt(PLAIN_PASSWORD); } return null; } /** * The 'ZMQ_RCVMORE' option shall return a boolean value indicating if the multi-part message currently being * read from the specified 'socket' has more message parts to follow. If there are no message parts to follow or * if the message currently being read is not a multi-part message a value of zero shall be returned. Otherwise, * a value of 1 shall be returned. * * @return true if there are more messages to receive. */ public boolean hasReceiveMore() { return getLongSockopt(RCVMORE) != 0; } /** * The 'ZMQ_FD' option shall retrieve file descriptor associated with the 0MQ socket. The descriptor can be used * to integrate 0MQ socket into an existing event loop. It should never be used for anything else than polling * -- such as reading or writing. The descriptor signals edge-triggered IN event when something has happened * within the 0MQ socket. It does not necessarily mean that the messages can be read or written. Check * ZMQ_EVENTS option to find out whether the 0MQ socket is readable or writeable. * * @return the underlying file descriptor. * @since 2.1.0 */ public long getFD() { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0)) return -1; return getLongSockopt(FD); } /** * The 'ZMQ_EVENTS' option shall retrieve event flags for the specified socket. If a message can be read from * the socket ZMQ_POLLIN flag is set. If message can be written to the socket ZMQ_POLLOUT flag is set. * * @return the mask of outstanding events. * @since 2.1.0 */ public long getEvents() { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0)) return -1; return getLongSockopt(EVENTS); } /** * The 'ZMQ_LINGER' option shall retrieve the period for pending outbound messages to linger in memory after * closing the socket. Value of -1 means infinite. Pending messages will be kept until they are fully * transferred to the peer. Value of 0 means that all the pending messages are dropped immediately when socket * is closed. Positive value means number of milliseconds to keep trying to send the pending messages before * discarding them. * * @param linger the linger period. * @since 2.1.0 */ public void setLinger(long linger) { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 0)) return; setLongSockopt(LINGER, linger); } /** * @since 3.0.0 */ public void setReconnectIVL(long reconnectIVL) { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10)) return; setLongSockopt(RECONNECT_IVL, reconnectIVL); } /** * @since 3.0.0 */ public void setBacklog(long backlog) { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return; setLongSockopt(BACKLOG, backlog); } /** * @since 3.0.0 */ public void setReconnectIVLMax(long reconnectIVLMax) { if (ZMQ.version_full() < ZMQ.make_version(2, 1, 10)) return; setLongSockopt(RECONNECT_IVL_MAX, reconnectIVLMax); } /** * @since 3.0.0 */ public void setMaxMsgSize(long maxMsgSize) { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return; setLongSockopt(MAXMSGSIZE, maxMsgSize); } /** * @since 3.0.0 */ public void setSndHWM(long sndHWM) { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return; setLongSockopt(SNDHWM, sndHWM); } /** * @since 3.0.0 */ public void setRcvHWM(long rcvHWM) { if (ZMQ.version_full() < ZMQ.make_version(3, 0, 0)) return; setLongSockopt(RCVHWM, rcvHWM); } /** * The 'ZMQ_HWM' option shall set the high water mark for the specified 'socket'. The high water mark is a hard * limit on the maximum number of outstanding messages 0MQ shall queue in memory for any single peer that the * specified 'socket' is communicating with. * * If this limit has been reached the socket shall enter an exceptional state and depending on the socket type, * 0MQ shall take appropriate action such as blocking or dropping sent messages. Refer to the individual socket * descriptions in the man page of zmq_socket[3] for details on the exact action taken for each socket type. * * @param hwm the number of messages to queue. */ public void setHWM(long hwm) { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) return; setLongSockopt(HWM, hwm); } /** * Get the Swap. The 'ZMQ_SWAP' option shall set the disk offload (swap) size for the specified 'socket'. A * socket which has 'ZMQ_SWAP' set to a non-zero value may exceed its high water mark; in this case outstanding * messages shall be offloaded to storage on disk rather than held in memory. * * @param swap The value of 'ZMQ_SWAP' defines the maximum size of the swap space in bytes. */ public void setSwap(long swap) { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) return; setLongSockopt(SWAP, swap); } /** * Get the Affinity. The 'ZMQ_AFFINITY' option shall set the I/O thread affinity for newly created connections * on the specified 'socket'. * * Affinity determines which threads from the 0MQ I/O thread pool associated with the socket's _context_ shall * handle newly created connections. A value of zero specifies no affinity, meaning that work shall be * distributed fairly among all 0MQ I/O threads in the thread pool. For non-zero values, the lowest bit * corresponds to thread 1, second lowest bit to thread 2 and so on. For example, a value of 3 specifies that * subsequent connections on 'socket' shall be handled exclusively by I/O threads 1 and 2. * * See also in the man page of zmq_init[3] for details on allocating the number of I/O threads for a specific * _context_. * * @param affinity the affinity. */ public void setAffinity(long affinity) { setLongSockopt(AFFINITY, affinity); } /** * Override SO_KEEPALIVE socket option (where supported by OS) to enable keep-alive packets for a socket * connection. Possible values are -1, 0, 1. The default value -1 will skip all overrides and do the OS default. * * @param optVal The value of 'ZMQ_TCP_KEEPALIVE' to turn TCP keepalives on (1) or off (0). */ public void setTCPKeepAlive(long optVal) { if (ZMQ.version_full() >= ZMQ.make_version(3, 2, 0)) setLongSockopt(KEEPALIVE, optVal); } /** * Override TCP_KEEPCNT socket option (where supported by OS). The default value -1 will skip all overrides and * do the OS default. * * @param optVal The value of 'ZMQ_TCP_KEEPALIVE_CNT' defines the number of keepalives before death. */ public void setTCPKeepAliveCount(long optVal) { if (ZMQ.version_full() >= ZMQ.make_version(3, 2, 0)) setLongSockopt(KEEPALIVECNT, optVal); } /** * Override TCP_KEEPINTVL socket option (where supported by OS). The default value -1 will skip all overrides * and do the OS default. * * @param optVal The value of 'ZMQ_TCP_KEEPALIVE_INTVL' defines the interval between keepalives. Unit is OS * dependant. */ public void setTCPKeepAliveInterval(long optVal) { if (ZMQ.version_full() >= ZMQ.make_version(3, 2, 0)) setLongSockopt(KEEPALIVEINTVL, optVal); } /** * Override TCP_KEEPCNT (or TCP_KEEPALIVE on some OS) socket option (where supported by OS). The default value * -1 will skip all overrides and do the OS default. * * @param optVal The value of 'ZMQ_TCP_KEEPALIVE_IDLE' defines the interval between the last data packet sent * over the socket and the first keepalive probe. Unit is OS dependant. */ public void setTCPKeepAliveIdle(long optVal) { if (ZMQ.version_full() >= ZMQ.make_version(3, 2, 0)) setLongSockopt(KEEPALIVEIDLE, optVal); } /** * The 'ZMQ_IDENTITY' option shall set the identity of the specified 'socket'. Socket identity determines if * existing 0MQ infastructure (_message queues_, _forwarding devices_) shall be identified with a specific * application and persist across multiple runs of the application. * * If the socket has no identity, each run of an application is completely separate from other runs. However, * with identity set the socket shall re-use any existing 0MQ infrastructure configured by the previous run(s). * Thus the application may receive messages that were sent in the meantime, _message queue_ limits shall be * shared with previous run(s) and so on. * * Identity should be at least one byte and at most 255 bytes long. Identities starting with binary zero are * reserved for use by 0MQ infrastructure. * * @param identity */ public void setIdentity(byte[] identity) { setBytesSockopt(IDENTITY, identity); } /** * The 'ZMQ_SUBSCRIBE' option shall establish a new message filter on a 'ZMQ_SUB' socket. Newly created * 'ZMQ_SUB' sockets shall filter out all incoming messages, therefore you should call this option to establish * an initial message filter. * * An empty 'option_value' of length zero shall subscribe to all incoming messages. A non-empty 'option_value' * shall subscribe to all messages beginning with the specified prefix. Mutiple filters may be attached to a * single 'ZMQ_SUB' socket, in which case a message shall be accepted if it matches at least one filter. * * @param topic */ public void subscribe(byte[] topic) { setBytesSockopt(SUBSCRIBE, topic); } /** * The 'ZMQ_UNSUBSCRIBE' option shall remove an existing message filter on a 'ZMQ_SUB' socket. The filter * specified must match an existing filter previously established with the 'ZMQ_SUBSCRIBE' option. If the socket * has several instances of the same filter attached the 'ZMQ_UNSUBSCRIBE' option shall remove only one * instance, leaving the rest in place and functional. * * @param topic */ public void unsubscribe(byte[] topic) { setBytesSockopt(UNSUBSCRIBE, topic); } /** * The 'ZMQ_RATE' option shall set the maximum send or receive data rate for multicast transports such as in the * man page of zmq_pgm[7] using the specified 'socket'. * * @param rate */ public void setRate(long rate) { setLongSockopt(RATE, rate); } /** * The 'ZMQ_RECOVERY_IVL' option shall set the recovery interval for multicast transports using the specified * 'socket'. The recovery interval determines the maximum time in seconds (before version 3.0.0) or milliseconds * (version 3.0.0 and after) that a receiver can be absent from a multicast group before unrecoverable data loss * will occur. * * CAUTION: Exercise care when setting large recovery intervals as the data needed for recovery will be held in * memory. For example, a 1 minute recovery interval at a data rate of 1Gbps requires a 7GB in-memory buffer. * {Purpose of this Method} * * @param recovery_ivl */ public void setRecoveryInterval(long recovery_ivl) { setLongSockopt(RECOVERY_IVL, recovery_ivl); } /** * The 'ZMQ_MCAST_LOOP' option shall control whether data sent via multicast transports using the specified * 'socket' can also be received by the sending host via loopback. A value of zero disables the loopback * functionality, while the default value of 1 enables the loopback functionality. Leaving multicast loopback * enabled when it is not required can have a negative impact on performance. Where possible, disable * 'ZMQ_MCAST_LOOP' in production environments. * * @param mcast_loop */ public void setMulticastLoop(boolean mcast_loop) { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) return; setLongSockopt(MCAST_LOOP, mcast_loop ? 1 : 0); } /** * The 'ZMQ_SNDBUF' option shall set the underlying kernel transmit buffer size for the 'socket' to the * specified size in bytes. A value of zero means leave the OS default unchanged. For details please refer to * your operating system documentation for the 'SO_SNDBUF' socket option. * * @param sndbuf */ public void setSendBufferSize(long sndbuf) { setLongSockopt(SNDBUF, sndbuf); } /** * The 'ZMQ_RCVBUF' option shall set the underlying kernel receive buffer size for the 'socket' to the specified * size in bytes. A value of zero means leave the OS default unchanged. For details refer to your operating * system documentation for the 'SO_RCVBUF' socket option. * * @param rcvbuf */ public void setReceiveBufferSize(long rcvbuf) { setLongSockopt(RCVBUF, rcvbuf); } /** * The 'ZMQ_IPV4ONLY' option shall set the underlying native socket type. An IPv6 socket lets applications * connect to and accept connections from both IPv4 and IPv6 hosts. * * @param v4only A value of true will use IPv4 sockets, while the value of false will use IPv6 sockets */ public void setIPv4Only(boolean v4only) { setLongSockopt(IPV4ONLY, v4only ? 1L : 0L); } /** * Sets the ROUTER socket behavior when an unroutable message is encountered. * * @param mandatory A value of false is the default and discards the message silently when it cannot be routed. * A value of true returns an EHOSTUNREACH error code if the message cannot be routed. */ public void setRouterMandatory(boolean mandatory) { setLongSockopt(ROUTER_MANDATORY, mandatory ? 1L : 0L); } /** * Sets the XPUB socket behavior on new subscriptions and unsubscriptions. * * @param verbose A value of false is the default and passes only new subscription messages to upstream. * A value of true passes all subscription messages upstream. * @since 3.2.2 */ public void setXpubVerbose(boolean verbose) { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) return; setLongSockopt(XPUB_VERBOSE, verbose ? 1L : 0L); } /** * Sets if the socket is for a server using the PLAIN security mechanism. * @see PLAIN RFC * @param plain whether or not to use PLAIN security * @since 4.0.0 */ public void setPlainServer(boolean plain) { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { setLongSockopt(PLAIN_SERVER, plain ? 1L : 0L); } } /** * Sets the username used for the PLAIN security mechanism. * @see PLAIN RFC * @param username null terminated string in server charset * @since 4.0.0 */ public void setPlainUsername(byte[] username) { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { setBytesSockopt(PLAIN_USERNAME, username); } } /** * Sets the password used for the PLAIN security mechanism. * @see PLAIN RFC * @param password null terminated string in server charset * @since 4.0.0 */ public void setPlainPassword(byte[] password) { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { setBytesSockopt(PLAIN_PASSWORD, password); } } /** * Sets the domain for ZAP (ZMQ RFC 27) authentication. * @param domain For NULL security (the default on all tcp:// connections), * ZAP authentication only happens if you set a non-empty domain. For PLAIN and CURVE security, * ZAP requests are always made, if there is a ZAP handler present. * See http://rfc.zeromq.org/spec:27 for more details. */ public void setZAPDomain(byte[] domain) { if(ZMQ.version_full() >= ZMQ.make_version(4, 1, 0)) { setBytesSockopt(ZAP_DOMAIN, domain); } } public void setGSSAPIServer(boolean isServer) { if(ZMQ.version_full() >= ZMQ.makeVersion(4, 1, 0)) { setLongSockopt(GSSAPI_SERVER, isServer ? 1L : 0L); } } public void setGSSAPIPrincipal(byte[] principal) { if(ZMQ.version_full() >= ZMQ.make_version(4, 1, 0)) { setBytesSockopt(GSSAPI_PRINCIPAL, principal); } } public void setGSSAPIServicePrincipal(byte[] principal) { if(ZMQ.version_full() >= ZMQ.make_version(4, 1, 0)) { setBytesSockopt(GSSAPI_SERVICE_PRINCIPAL, principal); } } public void setGSSAPIPlainText(boolean isPlaintext) { if(ZMQ.version_full() >= ZMQ.makeVersion(4, 1, 0)) { setLongSockopt(GSSAPI_PLAINTEXT, isPlaintext ? 1L : 0L); } } /** * Sets whether socket should keep only last received/to be sent message in its inbound/outbound queue. * * @param conflate A value of false is the default which means socket preserves all messages with respect * to the RECVHWM and SENDHWM options. A value of true means only last message is kept ignoring * the RECVHWM and SENDHWM options. * @since 4.0.0 */ public void setConflate(boolean conflate) { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { setLongSockopt(CONFLATE, conflate ? 1L : 0L); } } /** * Indicate whether socket should keep only last received/to be sent message in its inbound/outbound queue. * * @return true if should keep only last received/to be sent message in its inbound/outbound queue. * @since 4.0.0 */ public boolean getConflate() { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { return getLongSockopt(CONFLATE) != 0L; } else { return false; } } /** * Indicate whether socket should only queue messages to completed connections. * * @return true if should only queue messages to completed connections. * @since 3.2.0 */ public boolean getImmediate() { if (ZMQ.version_full() >= ZMQ.make_version(3, 2, 0)) { return getLongSockopt(IMMEDIATE) != 0L; } else { return false; } } /** * Sets whether socket should only queue messages to completed connections. * * @param immediate A value of false is the default which means socket will not queue messages to * to incomplete connections. This will cause the socket to block if there are no other connections, * but will prevent queues from filling on pipes awaiting connection. * @since 3.2.0 */ public void setImmediate(boolean immediate) { if (ZMQ.version_full() >= ZMQ.make_version(3, 2, 0)) { setLongSockopt(IMMEDIATE, immediate ? 1L : 0L); } } public void setReqRelaxed(boolean isRelaxed) { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { setLongSockopt(REQ_RELAXED, isRelaxed ? 1L : 0L); } } public void setReqCorrelate(boolean isCorrelate) { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { setLongSockopt(REQ_CORRELATE, isCorrelate ? 1L : 0L); } } /** * Sets whether the socket should automatically send an empty message * when a new connection is made or accepted. This may be set on * REQ, DEALER, or ROUTER sockets connected to a ROUTER socket. * The application must filter such empty messages. * * @param isProbeRouter if {@code true}, the socket will automatically * send an empty message when a new connection is made or * accepted; if {@code false}, no such message will be sent * @since 4.0.0 */ public void setProbeRouter(boolean isProbeRouter) { if (ZMQ.version_full() >= ZMQ.make_version(4, 0, 0)) { setLongSockopt(PROBE_ROUTER, isProbeRouter ? 1L : 0L); } } /** * Bind to network interface. Start listening for new connections. * * @param addr the endpoint to bind to. */ public native void bind(String addr); /** * Bind to network interface to a random port. Start listening for new connections. * * @param addr the endpoint to bind to. */ public int bindToRandomPort(String addr) { return bindToRandomPort(addr, 2000, 20000, 100); } /** * Bind to network interface to a random port. Start listening for new connections. * * @param addr the endpoint to bind to. * @param min_port The minimum port in the range of ports to try. */ public int bindToRandomPort(String addr, int min_port) { return bindToRandomPort(addr, min_port, 20000, 100); } /** * Bind to network interface to a random port. Start listening for new connections. * * @param addr the endpoint to bind to. * @param min_port The minimum port in the range of ports to try. * @param max_port The maximum port in the range of ports to try. */ public int bindToRandomPort(String addr, int min_port, int max_port) { return bindToRandomPort(addr, min_port, max_port, 100); } /** * Bind to network interface to a random port. Start listening for new connections. * * @param addr the endpoint to bind to. * @param min_port The minimum port in the range of ports to try. * @param max_port The maximum port in the range of ports to try. * @param max_tries The number of attempt to bind. */ public int bindToRandomPort(String addr, int min_port, int max_port, int max_tries) { int port; Random rand = new Random(); for (int i = 0; i < max_tries; i++) { port = rand.nextInt(max_port - min_port + 1) + min_port; try { bind(String.format("%s:%s", addr, port)); return port; } catch (ZMQException e) { if (e.getErrorCode() != ZMQ.EADDRINUSE()) { throw e; } continue; } } throw new ZMQException("Could not bind socket to random port.", (int) ZMQ.EADDRINUSE()); } /** * Unbind from network interface. Stop listening for connections. * * @param addr the endpoint to unbind from. */ public native void unbind(String addr); /** * Connect to remote application. * * @param addr the endpoint to connect to. */ public native void connect(String addr); /** * Disconnect from a remote application. * * @param addr the endpoint to disconnect from. */ public native void disconnect(String addr); /** * Start a monitoring socket where events can be received. * * @param addr the endpoint to receive events from. (must be inproc transport) * @param events the events of interest. * @return true if monitor socket setup is successful * @throws ZMQException */ public native boolean monitor(String addr, int events) throws ZMQException; /** * Send a message. * * @param msg the message to send, as an array of bytes. * @param offset the offset of the message to send. * @param flags the flags to apply to the send operation. * @return true if send was successful, false otherwise. */ public boolean send(byte[] msg, int offset, int flags) { return send(msg, offset, msg.length, flags); } /** * * @param msg * @param offset * @param len * @param flags * @return */ public native boolean send(byte[] msg, int offset, int len, int flags); /** * Perform a zero copy send. The buffer must be allocated using ByteBuffer.allocateDirect * * @param buffer * @param len * @param flags * @return */ public native boolean sendZeroCopy(ByteBuffer buffer, int len, int flags); /** * Send a message. * * @param msg the message to send, as an array of bytes. * @param flags the flags to apply to the send operation. * @return true if send was successful, false otherwise. */ public boolean send(byte[] msg, int flags) { return send(msg, 0, msg.length, flags); } /** * Send a String. * * @param msg the message to send, as a String. * @return true if send was successful, false otherwise. */ public boolean send(String msg) { byte[] b = msg.getBytes(); return send(b, 0, b.length, 0); } /** * Send a String. * * @param msg the message to send, as a String. * @return true if send was successful, false otherwise. */ public boolean sendMore(String msg) { byte[] b = msg.getBytes(); return send(b, 0, b.length, SNDMORE); } /** * Send a String. * * @param msg the message to send, as a String. * @param flags the flags to apply to the send operation. * @return true if send was successful, false otherwise. */ public boolean send(String msg, int flags) { byte[] b = msg.getBytes(); return send(b, 0, b.length, flags); } /** * Send a message * * @param bb ByteBuffer payload * @param flags the flags to apply to the send operation * @return the number of bytes sent */ public native int sendByteBuffer(ByteBuffer bb, int flags); /** * Receive a message. * * @param flags the flags to apply to the receive operation. * @return the message received, as an array of bytes; null on error. */ public native byte[] recv(int flags); /** * Receive a message in to a specified buffer. * * @param buffer byte[] to copy zmq message payload in to. * @param offset offset in buffer to write data * @param len max bytes to write to buffer. If len is smaller than the incoming message size, the message will * be truncated. * @param flags the flags to apply to the receive operation. * @return the number of bytes read, -1 on error */ public native int recv(byte[] buffer, int offset, int len, int flags); /** * Zero copy recv * * @param buffer * @param len * @param flags * @return bytes read, -1 on error */ public native int recvZeroCopy(ByteBuffer buffer, int len, int flags); /** * Receive a message. * * @return the message received, as an array of bytes; null on error. */ public final byte[] recv() { return recv(0); } /** * Receive a message as a String with the default Charset. * * @deprecated use {@link #recvStr(Charset)} instead. * @return the message received, as a String; null on error. */ @Deprecated public String recvStr() { return recvStr(0); } /** * Receive a message as a String with a given Charset. * * @param charset the charset of the resulting string. * @return the message received, as a String; null on error. */ public String recvStr(Charset charset) { return recvStr(0, charset); } /** * Receive a message as a String with the default charset. * * @deprecated use {@link #recvStr(int, Charset)} instead. * @param flags the flags to apply to the receive operation. * @return the message received, as a String; null on error. */ @Deprecated public String recvStr(int flags) { return recvStr(flags, Charset.defaultCharset()); } /** * Receive a message as a String. * * @param flags the flags to apply to the receive operation. * @param charset the charset of the resulting string. * @return the message received, as a String; null on error. */ public String recvStr(int flags, Charset charset) { byte[] data = recv(flags); if (data == null) { return null; } else { return new String(data, charset); } } /** * Receive a message * * @param buffer * @param flags * @return bytes read, -1 on error */ public native int recvByteBuffer(ByteBuffer buffer, int flags); /** * Class constructor. * * @param context a 0MQ context previously created. * @param type the socket type. */ protected Socket(Context context, int type) { // We keep a local handle to context so that // garbage collection won't be too greedy on it. this.context = context; construct(context, type); } /** Initialize the JNI interface */ protected native void construct(Context ctx, int type); /** Free all resources used by JNI interface. */ protected native void destroy(); /** * Get the socket option value, as a long. * * @param option ID of the option to set. * @return The socket option value (as a long). */ protected native long getLongSockopt(int option); /** * Get the socket option value, as a byte array. * * @param option ID of the option to set. * @return The socket option value (as a byte array). */ protected native byte[] getBytesSockopt(int option); /** * Set the socket option value, given as a long. * * @param option ID of the option to set. * @param optval value (as a long) to set the option to. */ protected native void setLongSockopt(int option, long optval); /** * Set the socket option value, given as a byte array. * * @param option ID of the option to set. * @param optval value (as a byte array) to set the option to. */ protected native void setBytesSockopt(int option, byte[] optval); /** * Get the underlying socket handle. This is private because it is only accessed from JNI, where Java access * controls are ignored. * * @return the internal 0MQ socket handle. */ private long getSocketHandle() { return this.socketHandle; } /** Opaque data used by JNI driver. */ private long socketHandle; private final Context context; // private Constants use the appropriate setter instead. private static final int HWM = 1; // public static final int LWM = 2; // No longer supported private static final int SWAP = 3; private static final int AFFINITY = 4; private static final int IDENTITY = 5; private static final int SUBSCRIBE = 6; private static final int UNSUBSCRIBE = 7; private static final int RATE = 8; private static final int RECOVERY_IVL = 9; private static final int MCAST_LOOP = 10; private static final int SNDBUF = 11; private static final int RCVBUF = 12; private static final int RCVMORE = 13; private static final int FD = 14; private static final int EVENTS = 15; private static final int TYPE = 16; private static final int LINGER = 17; private static final int RECONNECT_IVL = 18; private static final int BACKLOG = 19; private static final int RECONNECT_IVL_MAX = 21; private static final int MAXMSGSIZE = 22; private static final int SNDHWM = 23; private static final int RCVHWM = 24; private static final int MULTICAST_HOPS = 25; private static final int RCVTIMEO = 27; private static final int SNDTIMEO = 28; private static final int IPV4ONLY = 31; private static final int ROUTER_MANDATORY = 33; private static final int KEEPALIVE = 34; private static final int KEEPALIVECNT = 35; private static final int KEEPALIVEIDLE = 36; private static final int KEEPALIVEINTVL = 37; private static final int IMMEDIATE = 39; private static final int XPUB_VERBOSE = 40; private static final int PLAIN_SERVER = 44; private static final int PLAIN_USERNAME = 45; private static final int PLAIN_PASSWORD = 46; private static final int PROBE_ROUTER = 51; private static final int REQ_CORRELATE = 52; private static final int REQ_RELAXED = 53; private static final int CONFLATE = 54; private static final int ZAP_DOMAIN = 55; private static final int GSSAPI_SERVER = 62; private static final int GSSAPI_PRINCIPAL = 63; private static final int GSSAPI_SERVICE_PRINCIPAL = 64; private static final int GSSAPI_PLAINTEXT = 65; } public static class PollItem { private Socket socket; private SelectableChannel channel; private int events; private int revents; public PollItem(Socket socket, int events) { this.socket = socket; this.events = events; this.revents = 0; } public PollItem(SelectableChannel channel, int events) { this.channel = channel; this.events = events; this.revents = 0; } public SelectableChannel getRawSocket() { return channel; } public Socket getSocket() { return socket; } public boolean isError() { return (revents & Poller.POLLERR) > 0; } public int readyOps() { return revents; } public boolean isReadable() { return (revents & Poller.POLLIN) > 0; } public boolean isWritable() { return (revents & Poller.POLLOUT) > 0; } @Override public boolean equals(Object obj) { if (!(obj instanceof PollItem)) return false; PollItem target = (PollItem) obj; if (socket != null && socket == target.socket) return true; if (channel != null && channel == target.channel) return true; return false; } } /** * Inner class: Poller. */ public static class Poller { /** * These values can be ORed to specify what we want to poll for. */ public static final int POLLIN = 1; public static final int POLLOUT = 2; public static final int POLLERR = 4; /** * Register a Socket for polling on all events. * * @param socket the Socket we are registering. * @return the index identifying this Socket in the poll set. */ public int register(Socket socket) { return register(socket, POLLIN | POLLOUT | POLLERR); } /** * Register a Channel for polling on all events. * * @param channel the Channel we are registering. * @return the index identifying this Channel in the poll set. */ public int register(SelectableChannel channel) { return register(channel, POLLIN | POLLOUT | POLLERR); } /** * Register a Socket for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param socket the Socket we are registering. * @param events a mask composed by XORing POLLIN, POLLOUT and POLLERR. * @return the index identifying this Socket in the poll set. */ public int register(Socket socket, int events) { return registerInternal(new PollItem(socket, events)); } /** * Register a Channel for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param channel the Channel we are registering. * @param events a mask composed by XORing POLLIN, POLLOUT and POLLERR. * @return the index identifying this Channel in the poll set. */ public int register(SelectableChannel channel, int events) { return registerInternal(new PollItem(channel, events)); } /** * Register a Channel for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param item the PollItem we are registering. * @return the index identifying this Channel in the poll set. */ public int register(PollItem item) { return registerInternal(item); } /** * Register a Socket for polling on the specified events. * * Automatically grow the internal representation if needed. * * @param item the PollItem we are registering. * @return the index identifying this Socket in the poll set. */ private int registerInternal(PollItem item) { int pos = -1; if (!this.freeSlots.isEmpty()) { // If there are free slots in our array, remove one // from the free list and use it. pos = this.freeSlots.remove(); } else { if (this.next >= this.size) { // It is necessary to grow the arrays. // Compute new size for internal arrays. int nsize = this.size + SIZE_INCREMENT; // Create new internal arrays. PollItem[] ns = new PollItem[nsize]; short[] ne = new short[nsize]; short[] nr = new short[nsize]; // Copy contents of current arrays into new arrays. for (int i = 0; i < this.next; ++i) { ns[i] = this.items[i]; } // Swap internal arrays and size to new values. this.size = nsize; this.items = ns; } pos = this.next++; } this.items[pos] = item; this.used++; return pos; } /** * Unregister a Socket for polling on the specified events. * * @param socket the Socket to be unregistered */ public void unregister(Socket socket) { unregisterInternal(socket); } /** * Unregister a Channel for polling on the specified events. * * @param channel the Channel to be unregistered */ public void unregister(SelectableChannel channel) { unregisterInternal(channel); } /** * Unregister a Socket for polling on the specified events. * * @param socket the Socket to be unregistered */ private void unregisterInternal(Object socket) { for (int i = 0; i < this.next; ++i) { PollItem item = this.items[i]; if (item == null) { continue; } if (item.socket == socket || item.channel == socket) { this.items[i] = null; this.freeSlots.add(i); --this.used; break; } } } /** * Get the socket associated with an index. * * @param index the desired index. * @return the Socket associated with that index (or null). */ public Socket getSocket(int index) { if (index < 0 || index >= this.next) return null; return this.items[index].socket; } /** * Get the PollItem associated with an index. * * @param index the desired index. * @return the PollItem associated with that index (or null). */ public PollItem getItem(int index) { if (index < 0 || index >= this.next) return null; return this.items[index]; } /** * Get the current poll timeout. * * @return the current poll timeout in microseconds. * @deprecated Timeout handling has been moved to the poll() methods. */ public long getTimeout() { return this.timeout; } /** * Set the poll timeout. * * @param timeout the desired poll timeout in microseconds. * @deprecated Timeout handling has been moved to the poll() methods. */ public void setTimeout(long timeout) { if (timeout < -1) return; this.timeout = timeout; } /** * Get the current poll set size. * * @return the current poll set size. */ public int getSize() { return this.size; } /** * Get the index for the next position in the poll set size. * * @return the index for the next position in the poll set size. */ public int getNext() { return this.next; } /** * Issue a poll call. If the poller's internal timeout value has been set, use that value as timeout; otherwise, * block indefinitely. * * @return how many objects where signalled by poll (). */ public long poll() { long tout = -1; if (this.timeout > -1) { tout = this.timeout; } return poll(tout); } /** * Issue a poll call, using the specified timeout value. *

* Since ZeroMQ 3.0, the timeout parameter is in milliseconds, * but prior to this the unit was microseconds. * * @param tout the timeout, as per zmq_poll if -1, it will block * indefinitely until an event happens; if 0, it will * return immediately; otherwise, it will wait for at most * that many milliseconds/microseconds (see above). * * @see 2.1 docs * @see 3.0 docs * * @return how many objects where signalled by poll () */ public int poll(long tout) { if (tout < -1) { return 0; } if (this.size <= 0 || this.next <= 0) { return 0; } return run_poll(this.items, this.used, tout); } /** * Check whether the specified element in the poll set was signalled for input. * * @param index * * @return true if the element was signalled. */ public boolean pollin(int index) { return poll_mask(index, POLLIN); } /** * Check whether the specified element in the poll set was signalled for output. * * @param index * * @return true if the element was signalled. */ public boolean pollout(int index) { return poll_mask(index, POLLOUT); } /** * Check whether the specified element in the poll set was signalled for error. * * @param index * * @return true if the element was signalled. */ public boolean pollerr(int index) { return poll_mask(index, POLLERR); } /** * Constructor * * @param size the number of Sockets this poller will contain. */ public Poller(int size) { this(null, size); } /** * Class constructor. * * @param context a 0MQ context previously created. */ protected Poller(Context context) { this(context, SIZE_DEFAULT); } /** * Class constructor. * * @param context a 0MQ context previously created. * @param size the number of Sockets this poller will contain. */ protected Poller(Context context, int size) { this.context = context; this.size = size; this.next = 0; this.items = new PollItem[this.size]; freeSlots = new LinkedList(); } /** * Issue a poll call on the specified 0MQ items. *

* Since ZeroMQ 3.0, the timeout parameter is in milliseconds, but prior to this the unit was * microseconds. * * @param items an array of PollItem to poll. * @param timeout the maximum timeout in milliseconds/microseconds (see above). * @return how many objects where signalled by poll. * @see 2.1 docs * @see 3.0 docs */ protected native static int run_poll(PollItem[] items, int count, long timeout); /** * Check whether a specific mask was signalled by latest poll call. * * @param index the index indicating the socket. * @param mask a combination of POLLIN, POLLOUT and POLLERR. * @return true if specific socket was signalled as specified. */ private boolean poll_mask(int index, int mask) { if (mask <= 0 || index < 0 || index >= this.next || this.items[index] == null) { return false; } return (this.items[index].revents & mask) > 0; } private Context context = null; private long timeout = -2; // mark as uninitialized private int size = 0; private int next = 0; private int used = 0; private PollItem[] items = null; // When socket is removed from polling, store free slots here private LinkedList freeSlots = null; private static final int SIZE_DEFAULT = 32; private static final int SIZE_INCREMENT = 16; } /** * Inner class: Event. * Monitor socket event class */ public static class Event { private static native void nativeInit(); static { nativeInit(); } private final int event; private final Object value; private final String address; private Event(int event, int value, String address) { this(event, Integer.valueOf(value), address != null ? address : ""); } public Event(int event, Object value, String address) { this.event = event; this.value = value; this.address = address; } public int getEvent() { return event; } public Object getValue() { return value; } /** * Get the address. * For libzmq versions 3.2.x the address will be an empty string. * @return */ public String getAddress() { return address; } private static native Event recv(long socket, int flags) throws ZMQException; /** * Receive an event from a monitor socket. * For libzmq versions 3.2.x the address will be an empty string. * @param socket the socket * @param flags the flags to apply to the receive operation. * @return the received event or null if no message was received. * @throws ZMQException */ public static Event recv(Socket socket, int flags) throws ZMQException { return Event.recv(socket.socketHandle, flags); } /** * Receive an event from a monitor socket. * Does a blocking recv. * For libzmq versions 3.2.x the address will be an empty string. * @param socket the socket * @return the received event. * @throws ZMQException */ public static Event recv(Socket socket) throws ZMQException { return Event.recv(socket, 0); } } } jzmq-3.1.0/src/main/java/org/zeromq/ZMQException.java000066400000000000000000000012001236001602100224050ustar00rootroot00000000000000package org.zeromq; /** * ZeroMQ runtime exception. * * @author Alois Belaska <alois.belaska@gmail.com> */ public class ZMQException extends RuntimeException { private static final long serialVersionUID = -978820750094924644L; private int errorCode = 0; public ZMQException(String message, int errorCode) { super(message); this.errorCode = errorCode; } /** * @return error code */ public int getErrorCode() { return errorCode; } @Override public String toString() { return super.toString() + "(0x" + Integer.toHexString(errorCode) + ")"; } } jzmq-3.1.0/src/main/java/org/zeromq/ZMQForwarder.java000066400000000000000000000031371236001602100224150ustar00rootroot00000000000000package org.zeromq; import org.zeromq.ZMQ.Context; import org.zeromq.ZMQ.Socket; /** * ZeroMQ Forwarder Device implementation. * * @author Alois Belaska <alois.belaska@gmail.com> */ public class ZMQForwarder implements Runnable { private final ZMQ.Poller poller; private final ZMQ.Socket inSocket; private final ZMQ.Socket outSocket; /** * Class constructor. * * @param context a 0MQ context previously created. * @param inSocket input socket * @param outSocket output socket */ public ZMQForwarder(Context context, Socket inSocket, Socket outSocket) { this.inSocket = inSocket; this.outSocket = outSocket; this.poller = context.poller(1); this.poller.register(inSocket, ZMQ.Poller.POLLIN); } /** * Forwarding messages. */ @Override public void run() { byte[] msg = null; boolean more = true; while (!Thread.currentThread().isInterrupted()) { try { // wait while there are requests to process if (poller.poll(250000) < 1) { continue; } msg = inSocket.recv(0); more = inSocket.hasReceiveMore(); if (msg != null) { outSocket.send(msg, more ? ZMQ.SNDMORE : 0); } } catch (ZMQException e) { // context destroyed, exit if (ZMQ.Error.ETERM.getCode() == e.getErrorCode()) { break; } throw e; } } } } jzmq-3.1.0/src/main/java/org/zeromq/ZMQQueue.java000066400000000000000000000051201236001602100215400ustar00rootroot00000000000000package org.zeromq; import java.io.Closeable; import java.io.IOException; import org.zeromq.ZMQ.Context; import org.zeromq.ZMQ.Socket; /** * ZeroMQ Queue Device implementation. * * @author Alois Belaska <alois.belaska@gmail.com> */ public class ZMQQueue implements Runnable, Closeable { private final ZMQ.Poller poller; private final ZMQ.Socket inSocket; private final ZMQ.Socket outSocket; /** * Class constructor. * * @param context a 0MQ context previously created. * @param inSocket input socket * @param outSocket output socket */ public ZMQQueue(Context context, Socket inSocket, Socket outSocket) { this.inSocket = inSocket; this.outSocket = outSocket; this.poller = context.poller(2); this.poller.register(inSocket, ZMQ.Poller.POLLIN); this.poller.register(outSocket, ZMQ.Poller.POLLIN); } /** * Queuing of requests and replies. */ @Override public void run() { byte[] msg = null; boolean more = true; while (!Thread.currentThread().isInterrupted()) { try { // wait while there are either requests or replies to process if (poller.poll(-1) < 0) { break; } // process a request if (poller.pollin(0)) { more = true; while (more) { msg = inSocket.recv(0); more = inSocket.hasReceiveMore(); if (msg != null) { outSocket.send(msg, more ? ZMQ.SNDMORE : 0); } } } // process a reply if (poller.pollin(1)) { more = true; while (more) { msg = outSocket.recv(0); more = outSocket.hasReceiveMore(); if (msg != null) { inSocket.send(msg, more ? ZMQ.SNDMORE : 0); } } } } catch (ZMQException e) { // context destroyed, exit if (ZMQ.Error.ETERM.getCode() == e.getErrorCode()) { break; } throw e; } } } /** * Unregisters input and output sockets. */ @Override public void close() throws IOException { poller.unregister(this.inSocket); poller.unregister(this.outSocket); } } jzmq-3.1.0/src/main/java/org/zeromq/ZMQStreamer.java000066400000000000000000000010511236001602100222350ustar00rootroot00000000000000package org.zeromq; import org.zeromq.ZMQ.Context; import org.zeromq.ZMQ.Socket; /** * ZeroMQ Streamer Device implementation. * * @author Alois Belaska <alois.belaska@gmail.com> */ public class ZMQStreamer extends ZMQForwarder { /** * Class constructor. * * @param context a 0MQ context previously created. * @param inSocket input socket * @param outSocket output socket */ public ZMQStreamer(Context context, Socket inSocket, Socket outSocket) { super(context, inSocket, outSocket); } } jzmq-3.1.0/src/main/java/org/zeromq/ZMsg.java000066400000000000000000000365241236001602100207600ustar00rootroot00000000000000package org.zeromq; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import java.io.PrintWriter; import java.io.StringWriter; import java.util.ArrayDeque; import java.util.Collection; import java.util.Deque; import java.util.Iterator; import java.util.NoSuchElementException; import org.zeromq.ZMQ.Socket; /** * The ZMsg class provides methods to send and receive multipart messages across 0MQ sockets. This class provides a * list-like container interface, with methods to work with the overall container. ZMsg messages are composed of zero or * more ZFrame objects. * *

 * // Send a simple single-frame string message on a ZMQSocket "output" socket object
 * ZMsg.newStringMsg("Hello").send(output);
 * 
 * // Add several frames into one message
 * ZMsg msg = new ZMsg();
 * for (int i = 0; i < 10; i++) {
 *     msg.addString("Frame" + i);
 * }
 * msg.send(output);
 * 
 * // Receive message from ZMQSocket "input" socket object and iterate over frames
 * ZMsg receivedMessage = ZMsg.recvMsg(input);
 * for (ZFrame f : receivedMessage) {
 *     // Do something with frame f (of type ZFrame)
 * }
 * 
* * Based on zmsg.c in czmq * */ public class ZMsg implements Iterable, Deque { /** * Hold internal list of ZFrame objects */ private ArrayDeque frames; /** * Class Constructor */ public ZMsg() { frames = new ArrayDeque(); } /** * Destructor. Explicitly destroys all ZFrames contains in the ZMsg */ public void destroy() { if (frames == null) return; for (ZFrame f : frames) { f.destroy(); } frames.clear(); } /** * Return total number of bytes contained in all ZFrames in this ZMsg * * @return */ public long contentSize() { long size = 0; for (ZFrame f : frames) { size += f.size(); } return size; } /** * Add a String as a new ZFrame to the end of list * * @param str String to add to list */ public void addString(String str) { if (frames == null) frames = new ArrayDeque(); frames.add(new ZFrame(str)); } /** * Creates copy of this ZMsg. Also duplicates all frame content. * * @return The duplicated ZMsg object, else null if this ZMsg contains an empty frame set */ public ZMsg duplicate() { if (frames != null) { ZMsg msg = new ZMsg(); for (ZFrame f : frames) msg.add(f.duplicate()); return msg; } else return null; } /** * Push frame plus empty frame to front of message, before 1st frame. Message takes ownership of frame, will destroy * it when message is sent. * * @param frame */ public void wrap(ZFrame frame) { if (frame != null) { push(new ZFrame("")); push(frame); } } /** * Pop frame off front of message, caller now owns frame. If next frame is empty, pops and destroys that empty frame * (e.g. useful when unwrapping ROUTER socket envelopes) * * @return Unwrapped frame */ public ZFrame unwrap() { if (size() == 0) return null; ZFrame f = pop(); ZFrame empty = getFirst(); if (empty.hasData() && empty.size() == 0) { empty = pop(); empty.destroy(); } return f; } /** * Send message to 0MQ socket. * * @param socket 0MQ socket to send ZMsg on. */ public void send(Socket socket) { send(socket, false); } /** * Send message to 0MQ socket, destroys contents after sending if destroy param is set to true. If the message has * no frames, sends nothing but still destroy()s the ZMsg object * * @param socket 0MQ socket to send ZMsg on. */ public void send(Socket socket, boolean destroy) { if (socket == null) throw new IllegalArgumentException("socket is null"); if (frames.size() == 0) return; Iterator i = frames.iterator(); while (i.hasNext()) { ZFrame f = i.next(); f.sendAndKeep(socket, (i.hasNext()) ? ZMQ.SNDMORE : 0); } if (destroy) { destroy(); } } /** * Receives message from socket, returns ZMsg object or null if the recv was interrupted. Does a blocking recv, if * you want not to block then use the ZLoop class or ZMQ.Poller to check for socket input before receiving or * recvMsg with flag ZMQ.DONTWAIT. * * @param socket * @return */ public static ZMsg recvMsg(Socket socket) { return recvMsg(socket, 0); } /** * Receives message from socket, returns ZMsg object or null if the recv was interrupted. Does a blocking recv, if * you want not to block then use the ZLoop class or ZMQ.Poller to check for socket input before receiving. * * @param socket * @param flag see ZMQ constants * @return */ public static ZMsg recvMsg(Socket socket, int flag) { if (socket == null) throw new IllegalArgumentException("socket is null"); ZMsg msg = new ZMsg(); while (true) { ZFrame f = ZFrame.recvFrame(socket, flag); if (f == null) { // If receive failed or was interrupted msg.destroy(); break; } msg.add(f); if (!f.hasMore()) break; } return msg; } /** * Save message to an open data output stream. * * Data saved as: 4 bytes: number of frames For every frame: 4 bytes: byte size of frame data + n bytes: frame byte * data * * @param msg ZMsg to save * @param file DataOutputStream * @return True if saved OK, else false */ public static boolean save(ZMsg msg, DataOutputStream file) { if (msg == null) return false; try { // Write number of frames file.writeInt(msg.size()); if (msg.size() > 0) { for (ZFrame f : msg) { // Write byte size of frame file.writeInt(f.size()); // Write frame byte data file.write(f.getData()); } } return true; } catch (IOException e) { return false; } } /** * Load / append a ZMsg from an open DataInputStream * * @param file DataInputStream connected to file * @return ZMsg object */ public static ZMsg load(DataInputStream file) { if (file == null) return null; ZMsg rcvMsg = new ZMsg(); try { int msgSize = file.readInt(); if (msgSize > 0) { int msgNbr = 0; while (++msgNbr <= msgSize) { int frameSize = file.readInt(); byte[] data = new byte[frameSize]; file.read(data); rcvMsg.add(new ZFrame(data)); } } return rcvMsg; } catch (IOException e) { return null; } } /** * Create a new ZMsg from one or more Strings * * @param strings Strings to add as frames. * @return ZMsg object */ public static ZMsg newStringMsg(String... strings) { ZMsg msg = new ZMsg(); for (String data : strings) { msg.addString(data); } return msg; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; ZMsg zMsg = (ZMsg) o; if (frames == null || zMsg.frames == null) return false; // based on AbstractList Iterator e1 = frames.iterator(); Iterator e2 = zMsg.frames.iterator(); while (e1.hasNext() && e2.hasNext()) { ZFrame o1 = e1.next(); ZFrame o2 = e2.next(); if (!(o1 == null ? o2 == null : o1.equals(o2))) return false; } return !(e1.hasNext() || e2.hasNext()); } @Override public int hashCode() { if (frames == null || frames.size() == 0) return 0; int result = 1; for (ZFrame frame : frames) result = 31 * result + (frame == null ? 0 : frame.hashCode()); return result; } /** * Dump the message in human readable format. This should only be used for debugging and tracing, inefficient in * handling large messages. **/ public void dump(Appendable out) { try { StringWriter sw = new StringWriter(); PrintWriter pw = new PrintWriter(sw); pw.printf("--------------------------------------\n"); for (ZFrame frame : frames) { pw.printf("[%03d] %s\n", frame.getData().length, frame.toString()); } out.append(sw.getBuffer()); sw.close(); } catch (IOException e) { throw new RuntimeException("Message dump exception " + super.toString(), e); } } /** * Convert the message to a string, for use in debugging. */ public String toString() { StringBuilder sb = new StringBuilder(); dump(sb); return sb.toString(); } // ********* Convenience Deque methods for common data types *** // public void addFirst(String stringValue) { addFirst(new ZFrame(stringValue)); } public void addFirst(byte[] data) { addFirst(new ZFrame(data)); } public void addLast(String stringValue) { addLast(new ZFrame(stringValue)); } public void addLast(byte[] data) { addLast(new ZFrame(data)); } // ********* Convenience Queue methods for common data types *** // public void push(String str) { push(new ZFrame(str)); } public void push(byte[] data) { push(new ZFrame(data)); } public boolean add(String stringValue) { return add(new ZFrame(stringValue)); } public boolean add(byte[] data) { return add(new ZFrame(data)); } // ********* Implement Iterable Interface *************** // @Override public Iterator iterator() { // TODO Auto-generated method stub return frames.iterator(); } // ********* Implement Deque Interface ****************** // @Override public boolean addAll(Collection arg0) { return frames.addAll(arg0); } @Override public void clear() { frames.clear(); } @Override public boolean containsAll(Collection arg0) { return frames.containsAll(arg0); } @Override public boolean isEmpty() { return frames.isEmpty(); } @Override public boolean removeAll(Collection arg0) { return frames.removeAll(arg0); } @Override public boolean retainAll(Collection arg0) { return frames.retainAll(arg0); } @Override public Object[] toArray() { return frames.toArray(); } @Override public T[] toArray(T[] arg0) { return frames.toArray(arg0); } @Override public boolean add(ZFrame e) { if (frames == null) frames = new ArrayDeque(); return frames.add(e); } @Override public void addFirst(ZFrame e) { if (frames == null) frames = new ArrayDeque(); frames.addFirst(e); } @Override public void addLast(ZFrame e) { if (frames == null) frames = new ArrayDeque(); frames.addLast(e); } @Override public boolean contains(Object o) { return frames.contains(o); } @Override public Iterator descendingIterator() { return frames.descendingIterator(); } @Override public ZFrame element() { return frames.element(); } @Override public ZFrame getFirst() { try { return frames.getFirst(); } catch (NoSuchElementException e) { return null; } } @Override public ZFrame getLast() { try { return frames.getLast(); } catch (NoSuchElementException e) { return null; } } @Override public boolean offer(ZFrame e) { if (frames == null) frames = new ArrayDeque(); return frames.offer(e); } @Override public boolean offerFirst(ZFrame e) { if (frames == null) frames = new ArrayDeque(); return frames.offerFirst(e); } @Override public boolean offerLast(ZFrame e) { if (frames == null) frames = new ArrayDeque(); return frames.offerLast(e); } @Override public ZFrame peek() { return frames.peek(); } @Override public ZFrame peekFirst() { try { return frames.peekFirst(); } catch (NoSuchElementException e) { return null; } } @Override public ZFrame peekLast() { try { return frames.peekLast(); } catch (NoSuchElementException e) { return null; } } @Override public ZFrame poll() { return frames.poll(); } @Override public ZFrame pollFirst() { return frames.pollFirst(); } @Override public ZFrame pollLast() { return frames.pollLast(); } @Override public ZFrame pop() { if (frames == null) frames = new ArrayDeque(); try { return frames.pop(); } catch (NoSuchElementException e) { return null; } } /** * Pop a ZFrame and return the toString() representation of it. * * @return toString version of pop'ed frame, or null if no frame exists. */ public String popString() { ZFrame frame = pop(); if (frame == null) return null; return frame.toString(); } @Override public void push(ZFrame e) { if (frames == null) frames = new ArrayDeque(); frames.push(e); } @Override public ZFrame remove() { return frames.remove(); } @Override public boolean remove(Object o) { return frames.remove(o); } @Override public ZFrame removeFirst() { try { return frames.removeFirst(); } catch (NoSuchElementException e) { return null; } } @Override public boolean removeFirstOccurrence(Object o) { return frames.removeFirstOccurrence(o); } @Override public ZFrame removeLast() { try { return frames.removeLast(); } catch (NoSuchElementException e) { return null; } } @Override public boolean removeLastOccurrence(Object o) { return frames.removeLastOccurrence(o); } @Override public int size() { return frames.size(); } } jzmq-3.1.0/src/main/java/org/zeromq/ZThread.java000066400000000000000000000057251236001602100214400ustar00rootroot00000000000000package org.zeromq; import org.zeromq.ZMQ.Socket; public class ZThread { public static interface IAttachedRunnable { public void run(Object[] args, ZContext ctx, Socket pipe); } public static interface IDetachedRunnable { public void run(Object[] args); } private static class ShimThread extends Thread { private ZContext ctx; private IAttachedRunnable attachedRunnable; private IDetachedRunnable detachedRunnable; private Object[] args; private Socket pipe; protected ShimThread(ZContext ctx, IAttachedRunnable runnable, Object[] args, Socket pipe) { assert (ctx != null); assert (pipe != null); assert (runnable != null); this.ctx = ctx; this.attachedRunnable = runnable; this.args = args; this.pipe = pipe; } public ShimThread(IDetachedRunnable runnable, Object[] args) { assert (runnable != null); this.detachedRunnable = runnable; this.args = args; } @Override public void run() { if (attachedRunnable != null) { try { attachedRunnable.run(args, ctx, pipe); } catch (ZMQException e) { if (e.getErrorCode() != ZMQ.ETERM()) { throw e; } } ctx.destroy(); } else detachedRunnable.run(args); } } // -------------------------------------------------------------------------- // Create a detached thread. A detached thread operates autonomously // and is used to simulate a separate process. It gets no ctx, and no // pipe. public static void start(IDetachedRunnable runnable, Object... args) { // Prepare child thread Thread shim = new ShimThread(runnable, args); shim.start(); } // -------------------------------------------------------------------------- // Create an attached thread. An attached thread gets a ctx and a PAIR // pipe back to its parent. It must monitor its pipe, and exit if the // pipe becomes unreadable. Returns pipe, or null if there was an error. public static Socket fork(ZContext ctx, IAttachedRunnable runnable, Object... args) { Socket pipe = ctx.createSocket(ZMQ.PAIR); if (pipe != null) { pipe.bind(String.format("inproc://zctx-pipe-%d", pipe.hashCode())); } else { return null; } // Connect child pipe to our pipe ZContext ccontext = ZContext.shadow(ctx); Socket cpipe = ccontext.createSocket(ZMQ.PAIR); if (cpipe == null) return null; cpipe.connect(String.format("inproc://zctx-pipe-%d", pipe.hashCode())); // Prepare child thread Thread shim = new ShimThread(ccontext, runnable, args, cpipe); shim.start(); return pipe; } } jzmq-3.1.0/src/main/perf/000077500000000000000000000000001236001602100151325ustar00rootroot00000000000000jzmq-3.1.0/src/main/perf/Makefile.am000066400000000000000000000006371236001602100171740ustar00rootroot00000000000000jarfile = zmq-perf.jar jardir = $(datadir)/perf JZMQ_PERF_JAVA_FILES = \ local_lat.java \ local_thr.java \ remote_lat.java \ remote_thr.java JZMQ_PERF_CLASS_FILES = *.class $(jarfile): $(JAVAC) -classpath $(top_builddir)/src/main/java -d . $(JZMQ_PERF_JAVA_FILES) $(JAR) cf $(JARFLAGS) $@ $(JZMQ_PERF_CLASS_FILES) jar_DATA = $(jarfile) CLEANFILES = \ -rf org \ $(JZMQ_PERF_CLASS_FILES) \ $(jarfile) jzmq-3.1.0/src/main/perf/local_lat.java000066400000000000000000000032731236001602100177340ustar00rootroot00000000000000/* Copyright (c) 2007-2010 iMatix Corporation This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program. If not, see . */ import org.zeromq.ZMQ; class local_lat { public static void main (String [] args) { if (args.length != 3) { System.out.println ("usage: local_lat " + " "); return; } String bindTo = args [0]; int messageSize = Integer.parseInt (args [1]); int roundtripCount = Integer.parseInt (args [2]); ZMQ.Context ctx = ZMQ.context (1); ZMQ.Socket s = ctx.socket (ZMQ.REP); // Add your socket options here. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. s.bind (bindTo); for (int i = 0; i != roundtripCount; i++) { byte [] data = s.recv (0); assert (data.length == messageSize); s.send (data, 0); } try { Thread.sleep (1000); } catch (InterruptedException e) { e.printStackTrace (); } } } jzmq-3.1.0/src/main/perf/local_lat.sh000077500000000000000000000001041236001602100174160ustar00rootroot00000000000000#!/bin/sh java -classpath "../src/zmq.jar:zmq-perf.jar" local_lat $@jzmq-3.1.0/src/main/perf/local_thr.java000066400000000000000000000043041236001602100177450ustar00rootroot00000000000000/* Copyright (c) 2007-2010 iMatix Corporation This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program. If not, see . */ import org.zeromq.ZMQ; class local_thr { public static void main (String [] args) { if (args.length != 3) { System.out.println ("usage: local_thr " + " "); return; } String bindTo = args [0]; long messageSize = Integer.parseInt (args [1]); long messageCount = Integer.parseInt (args [2]); ZMQ.Context ctx = ZMQ.context (1); ZMQ.Socket s = ctx.socket (ZMQ.PULL); // Add your socket options here. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. s.bind (bindTo); byte [] data = s.recv (0); assert (data.length == messageSize); long start = System.currentTimeMillis (); for (int i = 1; i != messageCount; i ++) { data = s.recv (0); assert (data.length == messageSize); } long end = System.currentTimeMillis (); long elapsed = (end - start) * 1000; if (elapsed == 0) elapsed = 1; long throughput = messageCount * 1000000 / elapsed; double megabits = (double) (throughput * messageSize * 8) / 1000000; System.out.println ("message size: " + messageSize + " [B]"); System.out.println ("message count: " + messageCount); System.out.println ("mean throughput: " + throughput + "[msg/s]"); System.out.println ("mean throughput: " + megabits + "[Mb/s]"); } } jzmq-3.1.0/src/main/perf/local_thr.sh000077500000000000000000000001041236001602100174330ustar00rootroot00000000000000#!/bin/sh java -classpath "../src/zmq.jar:zmq-perf.jar" local_thr $@jzmq-3.1.0/src/main/perf/remote_lat.java000066400000000000000000000040011236001602100201230ustar00rootroot00000000000000/* Copyright (c) 2007-2010 iMatix Corporation This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program. If not, see . */ import org.zeromq.ZMQ; class remote_lat { public static void main (String [] args) { if (args.length != 3) { System.out.println ("usage: remote_lat " + " "); return; } String connectTo = args [0]; int messageSize = Integer.parseInt (args [1]); int roundtripCount = Integer.parseInt (args [2]); ZMQ.Context ctx = ZMQ.context (1); ZMQ.Socket s = ctx.socket (ZMQ.REQ); // Add your socket options here. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. s.connect (connectTo); long start = System.currentTimeMillis (); byte data [] = new byte [messageSize]; for (int i = 0; i != roundtripCount; i ++) { s.send (data, 0); data = s.recv (0); assert (data.length == messageSize); } long end = System.currentTimeMillis (); long elapsed = (end - start) * 1000; double latency = (double) elapsed / roundtripCount / 2; System.out.println ("message size: " + messageSize + " [B]"); System.out.println ("roundtrip count: " + roundtripCount); System.out.println ("mean latency: " + latency + " [us]"); } } jzmq-3.1.0/src/main/perf/remote_lat.sh000077500000000000000000000001051236001602100176200ustar00rootroot00000000000000#!/bin/sh java -classpath "../src/zmq.jar:zmq-perf.jar" remote_lat $@jzmq-3.1.0/src/main/perf/remote_thr.java000066400000000000000000000030541236001602100201470ustar00rootroot00000000000000/* Copyright (c) 2007-2010 iMatix Corporation This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the Lesser GNU General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the Lesser GNU General Public License for more details. You should have received a copy of the Lesser GNU General Public License along with this program. If not, see . */ import org.zeromq.ZMQ; class remote_thr { public static void main (String [] args) { if (args.length != 3) { System.out.println ("usage: remote_thr " + " "); return; } // Parse the command line arguments. String connectTo = args [0]; int messageSize = Integer.parseInt (args [1]); int messageCount = Integer.parseInt (args [2]); ZMQ.Context ctx = ZMQ.context (1); ZMQ.Socket s = ctx.socket (ZMQ.PUSH); // Add your socket options here. // For example ZMQ_RATE, ZMQ_RECOVERY_IVL and ZMQ_MCAST_LOOP for PGM. s.connect (connectTo); byte msg [] = new byte [messageSize]; for (int i = 0; i != messageCount; i++) s.send (msg, 0); } } jzmq-3.1.0/src/main/perf/remote_thr.sh000077500000000000000000000001051236001602100176350ustar00rootroot00000000000000#!/bin/sh java -classpath "../src/zmq.jar:zmq-perf.jar" remote_thr $@jzmq-3.1.0/src/test/000077500000000000000000000000001236001602100142315ustar00rootroot00000000000000jzmq-3.1.0/src/test/java/000077500000000000000000000000001236001602100151525ustar00rootroot00000000000000jzmq-3.1.0/src/test/java/org/000077500000000000000000000000001236001602100157415ustar00rootroot00000000000000jzmq-3.1.0/src/test/java/org/zeromq/000077500000000000000000000000001236001602100172565ustar00rootroot00000000000000jzmq-3.1.0/src/test/java/org/zeromq/ZContextTest.java000066400000000000000000000050271236001602100225430ustar00rootroot00000000000000package org.zeromq; import org.junit.Test; import org.zeromq.ZMQ.Socket; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * Tests high-level ZContext class * * @author richardsmith * */ public class ZContextTest { @Test public void testConstruction() { ZContext ctx = new ZContext(); assertTrue(ctx != null); assertEquals(1, ctx.getIoThreads()); assertEquals(0, ctx.getLinger()); assertTrue(ctx.isMain()); } @Test public void testDestruction() { ZContext ctx = new ZContext(); ctx.destroy(); assertTrue(ctx.getSockets().isEmpty()); // Ensure context is not destroyed if not in main thread ZContext ctx1 = new ZContext(); ctx1.setMain(false); @SuppressWarnings("unused") Socket s = ctx1.createSocket(ZMQ.PAIR); ctx1.destroy(); assertTrue(ctx1.getSockets().isEmpty()); assertTrue(ctx1.getContext() != null); } @Test public void testAddingSockets() throws ZMQException { // Tests "internal" newSocket method, should not be used outside jzmq itself. ZContext ctx = new ZContext(); try { Socket s = ctx.createSocket(ZMQ.PUB); assertTrue(s != null); assertTrue(s.getType() == ZMQ.PUB); Socket s1 = ctx.createSocket(ZMQ.REQ); assertTrue(s1 != null); assertEquals(2, ctx.getSockets().size()); } finally { ctx.destroy(); } } @Test public void testRemovingSockets() throws ZMQException { ZContext ctx = new ZContext(); try { Socket s = ctx.createSocket(ZMQ.PUB); assertTrue(s != null); assertEquals(1, ctx.getSockets().size()); ctx.destroySocket(s); assertEquals(0, ctx.getSockets().size()); } finally { ctx.destroy(); } } @Test public void testShadow() { ZContext ctx = new ZContext(); Socket s = ctx.createSocket(ZMQ.PUB); assertTrue(s != null); assertEquals(1, ctx.getSockets().size()); ZContext shadowCtx = ZContext.shadow(ctx); shadowCtx.setMain(false); assertEquals(0, shadowCtx.getSockets().size()); @SuppressWarnings("unused") Socket s1 = shadowCtx.createSocket(ZMQ.SUB); assertEquals(1, shadowCtx.getSockets().size()); assertEquals(1, ctx.getSockets().size()); shadowCtx.destroy(); ctx.destroy(); } } jzmq-3.1.0/src/test/java/org/zeromq/ZDispatcherTest.java000066400000000000000000000175151236001602100232120ustar00rootroot00000000000000package org.zeromq; import org.junit.Test; import java.text.MessageFormat; import java.util.UUID; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CountDownLatch; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; import java.util.concurrent.atomic.AtomicBoolean; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; import static junit.framework.Assert.assertEquals; import static junit.framework.Assert.assertFalse; /** */ public class ZDispatcherTest { @Test public void singleMessage() throws InterruptedException { final CountDownLatch latch = new CountDownLatch(1); ZContext ctx = new ZContext(); ZMQ.Socket logger = ctx.createSocket(ZMQ.PAIR); logger.bind("inproc://zmsg.test"); ZMQ.Socket out = ctx.createSocket(ZMQ.PAIR); out.connect("inproc://zmsg.test"); final String mesgTxt = "Hello"; ZDispatcher dispatcher = new ZDispatcher(); ZDispatcher.ZSender outSender = new ZDispatcher.ZSender(); dispatcher.registerHandler(out, new ZDispatcher.ZMessageHandler() { @Override public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg) { } }, outSender); dispatcher.registerHandler(logger, new ZDispatcher.ZMessageHandler() { @Override public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg) { assertEquals(mesgTxt, msg.poll().toString()); latch.countDown(); } }, new ZDispatcher.ZSender()); ZMsg msg = new ZMsg(); ZFrame frame = new ZFrame(mesgTxt); msg.addFirst(frame); outSender.send(msg); latch.await(1, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); dispatcher.shutdown(); ctx.destroy(); } @Test public void testMessagesDispatchedToDifferentHandlersAreExecutedConcurrently() throws InterruptedException, BrokenBarrierException, TimeoutException { final AtomicBoolean threadingIssueDetected = new AtomicBoolean(false); final Lock guardLock1 = new ReentrantLock(); final Lock guardLock2 = new ReentrantLock(); final CyclicBarrier handlersBarrier = new CyclicBarrier(3); ZContext ctx = new ZContext(); ZMQ.Socket socketOne = ctx.createSocket(ZMQ.PAIR); socketOne.bind("inproc://zmsg.test"); ZMQ.Socket socketTwo = ctx.createSocket(ZMQ.PAIR); socketTwo.connect("inproc://zmsg.test"); ZDispatcher dispatcher = new ZDispatcher(); ZDispatcher.ZSender senderOne = new ZDispatcher.ZSender(); dispatcher.registerHandler(socketOne, new ZDispatcher.ZMessageHandler() { @Override public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg) { try { if (guardLock1.tryLock()) { handlersBarrier.await(1, TimeUnit.SECONDS); } else { threadingIssueDetected.set(true); } } catch (Exception ex) { threadingIssueDetected.set(true); } finally { guardLock1.unlock(); } } }, senderOne); ZDispatcher.ZSender senderTwo = new ZDispatcher.ZSender(); dispatcher.registerHandler(socketTwo, new ZDispatcher.ZMessageHandler() { @Override public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg) { try { if (guardLock2.tryLock()) { handlersBarrier.await(1, TimeUnit.SECONDS); } else { threadingIssueDetected.set(true); } } catch (Exception ex) { threadingIssueDetected.set(true); } finally { guardLock2.unlock(); } } }, senderTwo); ZMsg msg = new ZMsg(); ZFrame frame = new ZFrame("Hello"); msg.addFirst(frame); senderOne.send(msg.duplicate()); senderOne.send(msg.duplicate()); senderTwo.send(msg.duplicate()); senderTwo.send(msg.duplicate()); handlersBarrier.await(1, TimeUnit.SECONDS); handlersBarrier.await(1, TimeUnit.SECONDS); assertFalse(threadingIssueDetected.get()); dispatcher.shutdown(); ctx.destroy(); } @Test public void testNoMessageAreSentAfterShutdown() throws InterruptedException, BrokenBarrierException, TimeoutException { final AtomicBoolean shutdownIssueDetected = new AtomicBoolean(false); final CountDownLatch latch = new CountDownLatch(1); ZContext ctx = new ZContext(); ZMQ.Socket socketOne = ctx.createSocket(ZMQ.PAIR); socketOne.bind("inproc://zmsg.test"); ZMQ.Socket socketTwo = ctx.createSocket(ZMQ.PAIR); socketTwo.connect("inproc://zmsg.test"); final ZDispatcher dispatcher = new ZDispatcher(); final CyclicBarrier handlersBarrier = new CyclicBarrier(2, new Runnable() { @Override public void run() { if (latch.getCount() == 0) { dispatcher.shutdown(); } } }); ZDispatcher.ZSender senderOne = new ZDispatcher.ZSender(); dispatcher.registerHandler(socketOne, new ZDispatcher.ZMessageHandler() { @Override public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg) { latch.countDown(); try { handlersBarrier.await(1, TimeUnit.SECONDS); } catch (Exception e) { } } }, senderOne); ZDispatcher.ZSender senderTwo = new ZDispatcher.ZSender(); dispatcher.registerHandler(socketTwo, new ZDispatcher.ZMessageHandler() { @Override public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg) { sender.send(msg); shutdownIssueDetected.set(true); } }, senderTwo); ZMsg msg = new ZMsg(); msg.add(new ZFrame("Hello")); senderTwo.send(msg); handlersBarrier.await(1, TimeUnit.SECONDS); senderOne.send(msg); senderOne.send(msg); latch.await(1, TimeUnit.SECONDS); assertEquals(0, latch.getCount()); assertFalse(shutdownIssueDetected.get()); dispatcher.shutdown(); ctx.destroy(); } @Test public void dispatcherPerformanceTest() throws InterruptedException { final int nMessages = 1000000; final CountDownLatch latch = new CountDownLatch(nMessages); ZContext ctx = new ZContext(); ZDispatcher dispatcher = new ZDispatcher(); ZMQ.Socket in = ctx.createSocket(ZMQ.ROUTER); in.bind("inproc://zmsg.test"); ZMQ.Socket out = ctx.createSocket(ZMQ.DEALER); out.connect("inproc://zmsg.test"); dispatcher.registerHandler(in, new ZDispatcher.ZMessageHandler() { @Override public void handleMessage(ZDispatcher.ZSender sender, ZMsg msg) { latch.countDown(); } }, new ZDispatcher.ZSender()); long start = System.currentTimeMillis(); for (int i = 0; i < nMessages; i++) { ZMsg msg = new ZMsg(); msg.addLast(UUID.randomUUID().toString()); msg.send(out); } System.out.println(MessageFormat.format("performanceTest message sent:{0}", nMessages)); latch.await(); System.out.println(MessageFormat.format("performanceTest throughput:{0} messages/seconds", nMessages / ((System.currentTimeMillis() - start) / 1000))); dispatcher.shutdown(); ctx.destroy(); } }jzmq-3.1.0/src/test/java/org/zeromq/ZFrameTest.java000066400000000000000000000075251236001602100221560ustar00rootroot00000000000000package org.zeromq; import org.junit.Test; import org.zeromq.ZMQ.Socket; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; /** * Tests ZFrame class * * @author Richard Smith * */ public class ZFrameTest { @Test public void testZFrameCreation() { ZFrame f = new ZFrame("Hello".getBytes()); assertTrue(f != null); assertTrue(f.hasData()); assertEquals(5, f.size()); f = new ZFrame(); assertFalse(f.hasData()); assertEquals(0, f.size()); } @Test public void testZFrameEquals() { ZFrame f = new ZFrame("Hello".getBytes()); ZFrame clone = f.duplicate(); assertEquals(f, clone); } @Test public void testSending() { ZContext ctx = new ZContext(); Socket output = ctx.createSocket(ZMQ.PAIR); output.bind("inproc://zframe.test"); Socket input = ctx.createSocket(ZMQ.PAIR); input.connect("inproc://zframe.test"); // Send five different frames, test ZFRAME_MORE for (int i = 0; i < 5; i++) { ZFrame f = new ZFrame("Hello".getBytes()); f.sendAndDestroy(output, ZMQ.SNDMORE); assertEquals(0, f.size()); } // Send same frame five times ZFrame f = new ZFrame("Hello".getBytes()); for (int i = 0; i < 5; i++) { f.sendAndKeep(output, ZMQ.SNDMORE); } assertEquals(5, f.size()); ctx.destroy(); } @Test public void testCopyingAndDuplicating() { ZContext ctx = new ZContext(); Socket output = ctx.createSocket(ZMQ.PAIR); output.bind("inproc://zframe.test"); Socket input = ctx.createSocket(ZMQ.PAIR); input.connect("inproc://zframe.test"); ZFrame f = new ZFrame("Hello".getBytes()); ZFrame copy = f.duplicate(); assertTrue(copy.hasSameData(f)); f.destroy(); assertFalse(copy.hasSameData(f)); assertEquals(5, copy.size()); copy.destroy(); assertFalse(copy.hasSameData(f)); ctx.destroy(); } @Test public void testReceiving() { ZContext ctx = new ZContext(); Socket output = ctx.createSocket(ZMQ.PAIR); output.bind("inproc://zframe.test"); Socket input = ctx.createSocket(ZMQ.PAIR); input.connect("inproc://zframe.test"); // Send same frame five times ZFrame f = new ZFrame("Hello".getBytes()); for (int i = 0; i < 5; i++) { f.sendAndKeep(output, ZMQ.SNDMORE); } // Send END frame f = new ZFrame("NOT".getBytes()); f.reset("END".getBytes()); assertEquals("454E44", f.strhex()); f.sendAndDestroy(output); // Read and count until we receive END int frame_nbr = 0; while (true) { f = ZFrame.recvFrame(input); frame_nbr++; if (f.streq("END")) { f.destroy(); break; } } assertEquals(6, frame_nbr); f = ZFrame.recvFrame(input, ZMQ.DONTWAIT); assertTrue(!f.hasData()); ctx.destroy(); } @Test public void testStringFrames() { ZContext ctx = new ZContext(); Socket output = ctx.createSocket(ZMQ.PAIR); output.bind("inproc://zframe.test"); Socket input = ctx.createSocket(ZMQ.PAIR); input.connect("inproc://zframe.test"); ZFrame f1 = new ZFrame("Hello"); assertEquals(5, f1.getData().length); f1.sendAndKeep(output); ZFrame f2 = ZFrame.recvFrame(input); assertTrue(f2.hasData()); assertEquals(5, f2.getData().length); assertTrue(f2.streq("Hello")); assertEquals(f2.toString(), "Hello"); assertTrue(f2.hasSameData(f1)); ctx.destroy(); } } jzmq-3.1.0/src/test/java/org/zeromq/ZLoopTest.java000066400000000000000000000172071236001602100220330ustar00rootroot00000000000000/* Copyright other contributors as noted in the AUTHORS file. This file is part of 0MQ. 0MQ is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 3 of the License, or (at your option) any later version. 0MQ is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this program. If not, see . */ package org.zeromq; import org.junit.After; import org.junit.Assert; import org.zeromq.ZMQ.Poller; import org.zeromq.ZMQ.Socket; import org.zeromq.ZMQ.PollItem; import org.junit.Test; import org.junit.Before; public class ZLoopTest { private String received; private ZContext ctx; private Socket input; private Socket output; @Before public void setUp() { ctx = new ZContext(); assert (ctx != null); output = ctx.createSocket(ZMQ.PAIR); assert (output != null); output.bind("inproc://zloop.test"); input = ctx.createSocket(ZMQ.PAIR); assert (input != null); input.connect("inproc://zloop.test"); received = "FAILED"; } @After public void tearDown() { ctx.destroy(); } @Test public void testZLoop() { int rc = 0; ZLoop loop = new ZLoop(); assert (loop != null); ZLoop.IZLoopHandler timerEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { ((Socket) arg).send("PING", 0); return 0; } }; ZLoop.IZLoopHandler socketEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { received = ((Socket) arg).recvStr(0); // Just end the reactor return -1; } }; // After 10 msecs, send a ping message to output loop.addTimer(10, 1, timerEvent, input); // When we get the ping message, end the reactor PollItem pollInput = new PollItem(output, Poller.POLLIN); rc = loop.addPoller(pollInput, socketEvent, output); Assert.assertEquals(0, rc); loop.start(); loop.removePoller(pollInput); Assert.assertEquals("PING", received); } @Test public void testZLoopAddTimerFromTimer() { int rc = 0; ZLoop loop = new ZLoop(); assert (loop != null); ZLoop.IZLoopHandler timerEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { final long now = System.currentTimeMillis(); ZLoop.IZLoopHandler timerEvent2 = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { final long now2 = System.currentTimeMillis(); assert (now2 >= now + 10); ((Socket) arg).send("PING", 0); return 0; } }; loop.addTimer(10, 1, timerEvent2, arg); return 0; } }; ZLoop.IZLoopHandler socketEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { received = ((Socket) arg).recvStr(0); // Just end the reactor return -1; } }; // After 10 msecs, fire a timer that registers // another timer that sends the ping message loop.addTimer(10, 1, timerEvent, input); // When we get the ping message, end the reactor PollItem pollInput = new PollItem(output, Poller.POLLIN); rc = loop.addPoller(pollInput, socketEvent, output); Assert.assertEquals(0, rc); loop.start(); loop.removePoller(pollInput); Assert.assertEquals("PING", received); } @Test(timeout = 1000) public void testZLoopAddTimerFromSocketHandler() { int rc = 0; ZLoop loop = new ZLoop(); assert (loop != null); ZLoop.IZLoopHandler timerEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { ((Socket) arg).send("PING", 0); return 0; } }; ZLoop.IZLoopHandler socketEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { final long now = System.currentTimeMillis(); ZLoop.IZLoopHandler timerEvent2 = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { final long now2 = System.currentTimeMillis(); Assert.assertTrue(now2 >= now + 10); received = ((Socket) arg).recvStr(0); // Just end the reactor return -1; } }; // After 10 msec fire a timer that ends the reactor loop.addTimer(10, 1, timerEvent2, arg); return 0; } }; // Fire a timer that sends the ping message loop.addTimer(0, 1, timerEvent, input); // When we get the ping message, end the reactor PollItem pollInput = new PollItem(output, Poller.POLLIN); rc = loop.addPoller(pollInput, socketEvent, output); Assert.assertEquals(0, rc); loop.start(); loop.removePoller(pollInput); Assert.assertEquals("PING", received); } @Test(timeout = 1000) public void testZLoopEndReactorFromTimer() { int rc = 0; ZLoop loop = new ZLoop(); assert (loop != null); ZLoop.IZLoopHandler timerEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { ((Socket) arg).send("PING", 0); return 0; } }; ZLoop.IZLoopHandler socketEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { // After 10 msecs, fire an event that ends the reactor ZLoop.IZLoopHandler shutdownEvent = new ZLoop.IZLoopHandler() { @Override public int handle(ZLoop loop, PollItem item, Object arg) { received = ((Socket) arg).recvStr(0); // Just end the reactor return -1; } }; loop.addTimer(10, 1, shutdownEvent, arg); return 0; } }; // Fire event that sends a ping message to output loop.addTimer(0, 1, timerEvent, input); // When we get the ping message, end the reactor PollItem pollInput = new PollItem(output, Poller.POLLIN); rc = loop.addPoller(pollInput, socketEvent, output); Assert.assertEquals(0, rc); loop.start(); loop.removePoller(pollInput); Assert.assertEquals("PING", received); } } jzmq-3.1.0/src/test/java/org/zeromq/ZMQForwarderTest.java000066400000000000000000000020231236001602100233010ustar00rootroot00000000000000package org.zeromq; import static org.junit.Assert.assertArrayEquals; import org.junit.Test; public class ZMQForwarderTest { @Test public void testQueue() throws InterruptedException { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket clients = context.socket(ZMQ.PAIR); clients.bind("inproc://fw_clients"); ZMQ.Socket client = context.socket(ZMQ.PAIR); client.connect("inproc://fw_clients"); ZMQ.Socket workers = context.socket(ZMQ.PAIR); workers.bind("inproc://fw_workers"); ZMQ.Socket worker = context.socket(ZMQ.PAIR); worker.connect("inproc://fw_workers"); Thread t = new Thread(new ZMQForwarder(context, clients, workers)); t.start(); for (int i = 0; i < 10; i++) { byte[] req = ("request" + i).getBytes(); client.send(req, 0); // worker receives request byte[] reqTmp = worker.recv(0); assertArrayEquals(req, reqTmp); } t.interrupt(); } } jzmq-3.1.0/src/test/java/org/zeromq/ZMQQueueTest.java000066400000000000000000000021221236001602100224320ustar00rootroot00000000000000package org.zeromq; import static org.junit.Assert.assertArrayEquals; import org.junit.Test; public class ZMQQueueTest { @Test public void testQueue() throws InterruptedException { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket clients = context.socket(ZMQ.XREP); clients.bind("inproc://gate_clients"); ZMQ.Socket workers = context.socket(ZMQ.XREQ); workers.bind("inproc://gate_workers"); ZMQ.Socket client = context.socket(ZMQ.REQ); client.connect("inproc://gate_clients"); ZMQ.Socket worker = context.socket(ZMQ.REP); worker.connect("inproc://gate_workers"); Thread t = new Thread(new ZMQQueue(context, clients, workers)); t.start(); for (int i = 0; i < 10; i++) { byte[] req = ("request" + i).getBytes(); byte[] rsp = ("response" + i).getBytes(); client.send(req, 0); // worker receives request byte[] reqTmp = worker.recv(0); assertArrayEquals(req, reqTmp); // worker sends response worker.send(rsp, 0); // client receives response byte[] rspTmp = client.recv(0); assertArrayEquals(rsp, rspTmp); } t.interrupt(); } } jzmq-3.1.0/src/test/java/org/zeromq/ZMQTest.java000066400000000000000000000633441236001602100214420ustar00rootroot00000000000000package org.zeromq; import java.nio.ByteBuffer; import java.nio.ByteOrder; import java.nio.charset.CharacterCodingException; import static org.junit.Assert.assertArrayEquals; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; import org.junit.Test; import org.zeromq.ZMQ.Context; import org.zeromq.ZMQ.Event; import org.zeromq.ZMQ.Poller; import org.zeromq.ZMQ.Socket; /** * @author Cliff Evans */ public class ZMQTest { /** * Test method for {@link org.zeromq.ZMQ#makeVersion(int, int, int)}. */ @Test public void testMakeVersion() { assertEquals(ZMQ.getFullVersion(), ZMQ.makeVersion(ZMQ.getMajorVersion(), ZMQ.getMinorVersion(), ZMQ.getPatchVersion())); } /** * Test method for {@link org.zeromq.ZMQ#getVersionString()}. */ @Test public void testGetVersion() { assertEquals(ZMQ.getMajorVersion() + "." + ZMQ.getMinorVersion() + "." + ZMQ.getPatchVersion(), ZMQ.getVersionString()); } /** * Test method for {@link org.zeromq.ZMQ.Socket#bindToRandomPort(String)}. */ @Test public void testBindToRandomPort() { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket sock = context.socket(ZMQ.DEALER); // Check that bindToRandomport generate valid port number for (int i = 0; i < 100; i++) { sock.bindToRandomPort("tcp://127.0.0.1"); } sock.close(); sock = context.socket(ZMQ.DEALER); // Check that exception different of EADDRINUSE is not catched // Invalid protocol try { sock.bindToRandomPort("noprotocol://127.0.0.1"); } catch (ZMQException e) { assertEquals(e.getErrorCode(), ZMQ.EPROTONOSUPPORT()); } } @Test public void testReqRep() { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket in = context.socket(ZMQ.REQ); in.bind("inproc://reqrep"); ZMQ.Socket out = context.socket(ZMQ.REP); out.connect("inproc://reqrep"); for (int i = 0; i < 10; i++) { byte[] req = ("request" + i).getBytes(); byte[] rep = ("reply" + i).getBytes(); assertTrue(in.send(req, 0)); byte[] reqTmp = out.recv(0); assertArrayEquals(req, reqTmp); assertTrue(out.send(rep, 0)); byte[] repTmp = in.recv(0); assertArrayEquals(rep, repTmp); } } @Test public void testXPUBSUB() { if (ZMQ.getFullVersion() < ZMQ.make_version(3, 0, 0)) { // Can only test XPUB on ZMQ >= of 3.0 return; } ZMQ.Context context = ZMQ.context(1); ZMQ.Socket pub = context.socket(ZMQ.XPUB); pub.bind("inproc://xpub"); ZMQ.Socket sub = context.socket(ZMQ.SUB); sub.connect("inproc://xpub"); ZMQ.Socket xsub = context.socket(ZMQ.XSUB); xsub.connect("inproc://xpub"); sub.subscribe("".getBytes()); byte[] subcr = pub.recv(0); assertArrayEquals(new byte[] { 1 }, subcr); sub.unsubscribe("".getBytes()); subcr = pub.recv(0); assertArrayEquals(new byte[] { 0 }, subcr); byte[] subscription = "subs".getBytes(); // Append subscription byte[] expected = new byte[subscription.length + 1]; expected[0] = 1; System.arraycopy(subscription, 0, expected, 1, subscription.length); sub.subscribe(subscription); subcr = pub.recv(0); assertArrayEquals(expected, subcr); // Verify xsub subscription xsub.send(expected, 0); subcr = pub.recv(1); assertNull(subcr); for (int i = 0; i < 10; i++) { byte[] data = ("subscrip" + i).getBytes(); assertTrue(pub.send(data, 0)); // Verify SUB byte[] tmp = sub.recv(0); assertArrayEquals(data, tmp); // Verify XSUB tmp = xsub.recv(0); assertArrayEquals(data, tmp); } } @Test public void testSetXpubVerbose() { if (ZMQ.getFullVersion() < ZMQ.make_version(3, 2, 2)) { // Can only test ZMQ_XPUB_VERBOSE on ZMQ >= of 3.2.2 return; } ZMQ.Context context = ZMQ.context(1); byte[] topic = "topic".getBytes(); byte[] subscription = new byte[topic.length + 1]; subscription[0] = 1; System.arraycopy(topic, 0, subscription, 1, topic.length); ZMQ.Socket xpubVerbose = context.socket(ZMQ.XPUB); xpubVerbose.setXpubVerbose(true); xpubVerbose.bind("inproc://xpub_verbose"); ZMQ.Socket xpubDefault = context.socket(ZMQ.XPUB); xpubDefault.bind("inproc://xpub_default"); ZMQ.Socket[] xsubs = new ZMQ.Socket[3]; for (int i = 0; i < xsubs.length; i++) { xsubs[i] = context.socket(ZMQ.XSUB); xsubs[i].connect("inproc://xpub_verbose"); xsubs[i].connect("inproc://xpub_default"); } for (int i = 0; i < xsubs.length; i++) { xsubs[i].send(subscription, 0); assertArrayEquals(subscription, xpubVerbose.recv(0)); if (i == 0) { assertArrayEquals(subscription, xpubDefault.recv(0)); } else { assertNull(xpubDefault.recv(ZMQ.DONTWAIT)); } } for (int i = 0; i < xsubs.length; i++) { xsubs[i].close(); } xpubVerbose.close(); xpubDefault.close(); context.term(); } /** * Test method for various set/get options. */ @Test public void testSetOption() { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket sock = context.socket(ZMQ.REQ); if (ZMQ.getFullVersion() >= ZMQ.makeVersion(3, 2, 0)) { sock.setIPv4Only(false); assertEquals(false, sock.getIPv4Only()); sock.setIPv4Only(true); assertEquals(true, sock.getIPv4Only()); } sock.close(); context.term(); } static class Client extends Thread { private Socket s = null; private String name = null; public Client(Context ctx, String name_) { s = ctx.socket(ZMQ.REQ); name = name_; s.setIdentity(name.getBytes()); } @Override public void run() { s.connect("tcp://127.0.0.1:6660"); s.send("hello", 0); String msg = s.recvStr(0); s.send("world", 0); msg = s.recvStr(0); s.close(); } } static class Dealer extends Thread { private Socket s = null; private String name = null; public Dealer(Context ctx, String name_) { s = ctx.socket(ZMQ.DEALER); name = name_; s.setIdentity(name.getBytes()); } @Override public void run() { s.connect("tcp://127.0.0.1:6661"); int count = 0; while (count < 2) { String msg = s.recvStr(0); if (msg == null) { throw new RuntimeException(); } String identity = msg; msg = s.recvStr(0); if (msg == null) { throw new RuntimeException(); } msg = s.recvStr(0); if (msg == null) { throw new RuntimeException(); } s.send(identity, ZMQ.SNDMORE); s.send("", ZMQ.SNDMORE); String response = "OK " + msg; s.send(response, 0); count++; } s.close(); } } static class Main extends Thread { Context ctx; Main(Context ctx_) { ctx = ctx_; } @Override public void run() { Socket frontend = ctx.socket(ZMQ.ROUTER); assertNotNull(frontend); frontend.bind("tcp://127.0.0.1:6660"); Socket backend = ctx.socket(ZMQ.DEALER); assertNotNull(backend); backend.bind("tcp://127.0.0.1:6661"); ZMQ.proxy(frontend, backend, null); frontend.close(); backend.close(); } } @Test public void testProxy() throws Exception { if (ZMQ.getFullVersion() < ZMQ.make_version(3, 2, 2)) { // Can only test zmq_proxy on ZMQ >= of 3.2.2 return; } Context ctx = ZMQ.context(1); assert (ctx != null); Main mt = new Main(ctx); mt.start(); new Dealer(ctx, "AA").start(); new Dealer(ctx, "BB").start(); Thread.sleep(1000); Thread c1 = new Client(ctx, "X"); c1.start(); Thread c2 = new Client(ctx, "Y"); c2.start(); c1.join(); c2.join(); ctx.term(); } /** * Test method for Router Mandatory */ @Test public void testRouterMandatory() { if (ZMQ.getFullVersion() < ZMQ.makeVersion(3, 2, 0)) return; ZMQ.Context context = ZMQ.context(1); ZMQ.Socket sock = context.socket(ZMQ.ROUTER); boolean ret = sock.sendMore("UNREACHABLE"); assertEquals(true, ret); sock.send("END"); sock.setRouterMandatory(true); try { sock.sendMore("UNREACHABLE"); assertFalse(true); } catch (ZMQException e) { assertEquals(ZMQ.EHOSTUNREACH(), e.getErrorCode()); } sock.close(); context.term(); } @Test public void testSendMoreRequestReplyOverTcp() { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket reply = null; ZMQ.Socket socket = null; try { reply = context.socket(ZMQ.REP); reply.bind("tcp://*:12345"); socket = context.socket(ZMQ.REQ); socket.connect("tcp://localhost:12345"); socket.send("test1", ZMQ.SNDMORE); socket.send("test2"); assertEquals("test1", reply.recvStr()); assertTrue(reply.hasReceiveMore()); assertEquals("test2", reply.recvStr()); } finally { try { socket.close(); } catch (Exception ignore){} try { reply.close(); } catch (Exception ignore){} try { context.term(); } catch (Exception ignore) {} } } @Test public void testWritingToClosedSocket() { ZMQ.Context context = ZMQ.context(1); ZMQ.Socket sock = null; try { sock = context.socket(ZMQ.REQ); sock.connect("ipc:///tmp/hai"); sock.close(); sock.send("PING".getBytes(), 0); } catch (ZMQException e) { assertEquals(ZMQ.ENOTSOCK(), e.getErrorCode()); } finally { try { sock.close(); } catch (Exception ignore) { } try { context.term(); } catch (Exception ignore) { } } } @Test public void testZeroCopyRecv() { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) { ZMQ.Context context = ZMQ.context(1); ByteBuffer response = ByteBuffer.allocateDirect(1024).order(ByteOrder.nativeOrder()); ZMQ.Socket push = null; ZMQ.Socket pull = null; try { push = context.socket(ZMQ.PUSH); pull = context.socket(ZMQ.PULL); pull.bind("tcp://*:45324"); push.connect("tcp://localhost:45324"); push.send("PING"); int rc = pull.recvZeroCopy(response, 16, 0); response.flip(); byte[] b = new byte[rc]; response.get(b); assertEquals("PING", new String(b)); } finally { try { push.close(); } catch (Exception ignore) { } try { pull.close(); } catch (Exception ignore) { } try { context.term(); } catch (Exception ignore) { } } } } @Test public void testZeroCopySend() throws InterruptedException { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) { ZMQ.Context context = ZMQ.context(1); ByteBuffer bb = ByteBuffer.allocateDirect(1024).order(ByteOrder.nativeOrder()); ZMQ.Socket push = null; ZMQ.Socket pull = null; try { push = context.socket(ZMQ.PUSH); pull = context.socket(ZMQ.PULL); pull.bind("tcp://*:45324"); push.connect("tcp://localhost:45324"); bb.put("PING".getBytes()); push.sendZeroCopy(bb, bb.position(), 0); assertEquals("PING", new String(pull.recv())); } finally { try { push.close(); } catch (Exception ignore) { } try { pull.close(); } catch (Exception ignore) { } try { context.term(); } catch (Exception ignore) { } } } } @Test public void testByteBufferSend() throws InterruptedException { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) { ZMQ.Context context = ZMQ.context(1); ByteBuffer bb = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder()); ZMQ.Socket push = null; ZMQ.Socket pull = null; try { push = context.socket(ZMQ.PUSH); pull = context.socket(ZMQ.PULL); pull.bind("ipc:///tmp/sendbb"); push.connect("ipc:///tmp/sendbb"); bb.put("PING".getBytes()); bb.flip(); push.sendByteBuffer(bb, 0); String actual = new String(pull.recv()); System.out.println(actual); assertEquals("PING", actual); } finally { try { push.close(); } catch (Exception ignore) { } try { pull.close(); } catch (Exception ignore) { } try { context.term(); } catch (Exception ignore) { } } } } @Test public void testByteBufferRecv() throws InterruptedException, CharacterCodingException { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) { ZMQ.Context context = ZMQ.context(1); ByteBuffer bb = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder()); ZMQ.Socket push = null; ZMQ.Socket pull = null; try { push = context.socket(ZMQ.PUSH); pull = context.socket(ZMQ.PULL); pull.bind("ipc:///tmp/recvbb"); push.connect("ipc:///tmp/recvbb"); push.send("PING".getBytes(), 0); pull.recvByteBuffer(bb, 0); bb.flip(); byte[] b = new byte[4]; bb.get(b); assertEquals("PING", new String(b)); } finally { try { push.close(); } catch (Exception ignore) { } try { pull.close(); } catch (Exception ignore) { } try { context.term(); } catch (Exception ignore) { } } } } @Test public void testByteBufferRecvTooLarge() throws InterruptedException, CharacterCodingException { if (ZMQ.version_full() >= ZMQ.make_version(3, 0, 0)) { ZMQ.Context context = ZMQ.context(1); ByteBuffer bb = ByteBuffer.allocateDirect(5).order(ByteOrder.nativeOrder()); ZMQ.Socket push = null; ZMQ.Socket pull = null; try { push = context.socket(ZMQ.PUSH); pull = context.socket(ZMQ.PULL); pull.bind("tcp://*:6787"); push.connect("tcp://127.0.0.1:6787"); push.send("helloworld".getBytes(), 0); int size = pull.recvByteBuffer(bb, 0); bb.flip(); byte[] b = new byte[size]; bb.get(b); assertEquals("hello", new String(b)); } finally { try { push.close(); } catch (Exception ignore) { } try { pull.close(); } catch (Exception ignore) { } try { context.term(); } catch (Exception ignore) { } } } } @Test public void testPollerUnregister() { Context context = ZMQ.context(1); Socket socketOne = context.socket(ZMQ.SUB); Socket socketTwo = context.socket(ZMQ.REP); Poller poller = new ZMQ.Poller(2); poller.register(socketOne, ZMQ.Poller.POLLIN); poller.register(socketTwo, ZMQ.Poller.POLLIN); socketOne.setLinger(0); socketOne.close(); socketTwo.setLinger(0); socketTwo.close(); poller.unregister(socketOne); poller.unregister(socketTwo); context.term(); } @Test public void testEventConnected() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); Event event; Socket helper = context.socket(ZMQ.REQ); int port = helper.bindToRandomPort("tcp://127.0.0.1"); Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); monitor.setReceiveTimeOut(100); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CONNECTED)); monitor.connect("inproc://monitor.socket"); socket.connect("tcp://127.0.0.1:" + port); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_CONNECTED, event.getEvent()); helper.close(); socket.close(); monitor.close(); context.term(); } @Test public void testEventConnectDelayed() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); Event event; Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); monitor.setReceiveTimeOut(100); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CONNECT_DELAYED)); monitor.connect("inproc://monitor.socket"); socket.connect("tcp://127.0.0.1:6751"); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_CONNECT_DELAYED, event.getEvent()); socket.close(); monitor.close(); context.term(); } @Test public void testEventConnectRetried() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); Event event; Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); monitor.setReceiveTimeOut(100); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CONNECT_RETRIED)); monitor.connect("inproc://monitor.socket"); socket.connect("tcp://127.0.0.1:6752"); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_CONNECT_RETRIED, event.getEvent()); socket.close(); monitor.close(); context.term(); } @Test public void testEventListening() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); Event event; Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); monitor.setReceiveTimeOut(100); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_LISTENING)); monitor.connect("inproc://monitor.socket"); socket.bindToRandomPort("tcp://127.0.0.1"); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_LISTENING, event.getEvent()); socket.close(); monitor.close(); context.term(); } @Test public void testEventBindFailed() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); ZMQ.Event event; Socket helper = context.socket(ZMQ.REP); int port = helper.bindToRandomPort("tcp://127.0.0.1"); Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); monitor.setReceiveTimeOut(100); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_BIND_FAILED)); monitor.connect("inproc://monitor.socket"); try { socket.bind("tcp://127.0.0.1:" + port); } catch (ZMQException ex) {} event = ZMQ.Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_BIND_FAILED, event.getEvent()); helper.close(); socket.close(); monitor.close(); context.term(); } @Test public void testEventAccepted() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); Event event; Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); Socket helper = context.socket(ZMQ.REQ); monitor.setReceiveTimeOut(100); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_ACCEPTED)); monitor.connect("inproc://monitor.socket"); int port = socket.bindToRandomPort("tcp://127.0.0.1"); helper.connect("tcp://127.0.0.1:" + port); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_ACCEPTED, event.getEvent()); helper.close(); socket.close(); monitor.close(); context.term(); } @Test public void testEventClosed() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); Event event; Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); monitor.setReceiveTimeOut(100); socket.bindToRandomPort("tcp://127.0.0.1"); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_CLOSED)); monitor.connect("inproc://monitor.socket"); socket.close(); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_CLOSED, event.getEvent()); monitor.close(); context.term(); } @Test public void testEventDisconnected() { if (ZMQ.version_full() < ZMQ.make_version(3, 2, 2)) // Monitor added in 3.2.2 return; Context context = ZMQ.context(1); Event event; Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); Socket helper = context.socket(ZMQ.REQ); monitor.setReceiveTimeOut(100); int port = socket.bindToRandomPort("tcp://127.0.0.1"); helper.connect("tcp://127.0.0.1:" + port); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_DISCONNECTED)); monitor.connect("inproc://monitor.socket"); helper.close(); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_DISCONNECTED, event.getEvent()); socket.close(); monitor.close(); context.term(); } @Test public void testEventMonitorStopped() { if (ZMQ.version_full() < ZMQ.make_version(4, 0, 0)) // EVENT_MONITOR_STOPPED added in 4.0.0 return; Context context = ZMQ.context(1); Event event; Socket socket = context.socket(ZMQ.REP); Socket monitor = context.socket(ZMQ.PAIR); monitor.setReceiveTimeOut(100); assertTrue(socket.monitor("inproc://monitor.socket", ZMQ.EVENT_MONITOR_STOPPED)); monitor.connect("inproc://monitor.socket"); socket.monitor(null, 0); event = Event.recv(monitor); assertNotNull("No event was received", event); assertEquals(ZMQ.EVENT_MONITOR_STOPPED, event.getEvent()); socket.close(); monitor.close(); context.term(); } } jzmq-3.1.0/src/test/java/org/zeromq/ZMsgTest.java000066400000000000000000000133571236001602100216520ustar00rootroot00000000000000package org.zeromq; import org.junit.Test; import org.zeromq.ZMQ.Socket; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.util.Iterator; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertTrue; public class ZMsgTest { @Test public void testMessageEquals() { ZMsg msg = new ZMsg(); ZFrame hello = new ZFrame("Hello"); ZFrame world = new ZFrame("World"); msg.add(hello); msg.add(world); assertEquals(msg, msg.duplicate()); ZMsg reverseMsg = new ZMsg(); msg.add(hello); msg.addFirst(world); assertFalse(msg.equals(reverseMsg)); } @Test public void testSingleFrameMessage() { ZContext ctx = new ZContext(); Socket output = ctx.createSocket(ZMQ.PAIR); output.bind("inproc://zmsg.test"); Socket input = ctx.createSocket(ZMQ.PAIR); input.connect("inproc://zmsg.test"); // Test send and receive of a single ZMsg ZMsg msg = new ZMsg(); ZFrame frame = new ZFrame("Hello"); msg.addFirst(frame); assertEquals(1, msg.size()); assertEquals(5, msg.contentSize()); msg.send(output); ZMsg msg2 = ZMsg.recvMsg(input); assertTrue(msg2 != null); assertEquals(1, msg2.size()); assertEquals(5, msg2.contentSize()); msg.destroy(); msg2.destroy(); ctx.destroy(); } @Test public void testMultiPart() { ZContext ctx = new ZContext(); Socket output = ctx.createSocket(ZMQ.PAIR); output.bind("inproc://zmsg.test2"); Socket input = ctx.createSocket(ZMQ.PAIR); input.connect("inproc://zmsg.test2"); ZMsg msg = new ZMsg(); for (int i = 0; i < 10; i++) msg.addString("Frame" + i); ZMsg copy = msg.duplicate(); copy.send(output); msg.send(output); copy = ZMsg.recvMsg(input); assertTrue(copy != null); assertEquals(10, copy.size()); assertEquals(60, copy.contentSize()); copy.destroy(); msg = ZMsg.recvMsg(input); assertTrue(msg != null); assertEquals(10, msg.size()); int count = 0; for (ZFrame f : msg) assertTrue(f.streq("Frame" + count++)); assertEquals(60, msg.contentSize()); msg.destroy(); ctx.destroy(); } @Test public void testMessageFrameManipulation() { ZMsg msg = new ZMsg(); for (int i = 0; i < 10; i++) msg.addString("Frame" + i); // Remove all frames apart from the first and last one for (int i = 0; i < 8; i++) { Iterator iter = msg.iterator(); iter.next(); // Skip first frame ZFrame f = iter.next(); msg.remove(f); f.destroy(); } assertEquals(2, msg.size()); assertEquals(12, msg.contentSize()); assertTrue(msg.getFirst().streq("Frame0")); assertTrue(msg.getLast().streq("Frame9")); ZFrame f = new ZFrame("Address"); msg.push(f); assertEquals(3, msg.size()); assertTrue(msg.getFirst().streq("Address")); msg.addString("Body"); assertEquals(4, msg.size()); ZFrame f0 = msg.pop(); assertTrue(f0.streq("Address")); msg.destroy(); msg = new ZMsg(); f = new ZFrame("Address"); msg.wrap(f); assertEquals(2, msg.size()); msg.addString("Body"); assertEquals(3, msg.size()); f = msg.unwrap(); f.destroy(); assertEquals(1, msg.size()); msg.destroy(); } @Test public void testEmptyMessage() { ZMsg msg = new ZMsg(); assertEquals(0, msg.size()); assertEquals(null, msg.getFirst()); assertEquals(null, msg.getLast()); assertTrue(msg.isEmpty()); assertEquals(null, msg.pop()); assertEquals(null, msg.removeFirst()); assertEquals(false, msg.removeFirstOccurrence(null)); assertEquals(null, msg.removeLast()); msg.destroy(); } @Test public void testLoadSave() { ZMsg msg = new ZMsg(); for (int i = 0; i < 10; i++) msg.addString("Frame" + i); try { // Save msg to a file File f = new File("zmsg.test"); DataOutputStream dos = new DataOutputStream(new FileOutputStream(f)); assertTrue(ZMsg.save(msg, dos)); dos.close(); // Read msg out of the file DataInputStream dis = new DataInputStream(new FileInputStream(f)); ZMsg msg2 = ZMsg.load(dis); dis.close(); f.delete(); assertEquals(10, msg2.size()); assertEquals(60, msg2.contentSize()); } catch (FileNotFoundException e) { e.printStackTrace(); assertTrue(false); } catch (IOException e) { e.printStackTrace(); assertTrue(false); } } @Test public void testNewStringMessage() { // A single string => frame ZMsg msg = ZMsg.newStringMsg("Foo"); assertEquals(1, msg.size()); assertTrue(msg.getFirst().streq("Foo")); // Multiple strings => frames ZMsg msg2 = ZMsg.newStringMsg("Foo", "Bar", "Baz"); assertEquals(3, msg2.size()); assertTrue(msg2.getFirst().streq("Foo")); assertTrue(msg2.getLast().streq("Baz")); // Empty message (Not very useful) ZMsg msg3 = ZMsg.newStringMsg(); assertTrue(msg3.isEmpty()); } } jzmq-3.1.0/src/test/java/org/zeromq/ZThreadTest.java000066400000000000000000000024721236001602100223270ustar00rootroot00000000000000package org.zeromq; import org.zeromq.ZMQ.Socket; import org.junit.Assert; import org.junit.Test; public class ZThreadTest { @Test public void testDetached() { ZThread.IDetachedRunnable detached = new ZThread.IDetachedRunnable() { @Override public void run(Object[] args) { ZContext ctx = new ZContext(); assert (ctx != null); Socket push = ctx.createSocket(ZMQ.PUSH); assert (push != null); ctx.destroy(); } }; ZThread.start(detached); } @Test public void testFork() { ZContext ctx = new ZContext(); ZThread.IAttachedRunnable attached = new ZThread.IAttachedRunnable() { @Override public void run(Object[] args, ZContext ctx, Socket pipe) { // Create a socket to check it'll be automatically deleted ctx.createSocket(ZMQ.PUSH); pipe.recvStr(); pipe.send("pong"); } }; Socket pipe = ZThread.fork(ctx, attached); assert (pipe != null); pipe.send("ping"); String pong = pipe.recvStr(); Assert.assertEquals(pong, "pong"); // Everything should be cleanly closed now ctx.destroy(); } }