Mercurial > hg > orthanc-imagej
changeset 0:1092b2dca366
initial commit
line wrap: on
line diff
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/AUTHORS Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,5 @@ +Orthanc - A Lightweight, RESTful DICOM Server +============================================= + +* Sebastien Jodogne <s.jodogne@gmail.com> + Department of Medical Physics, CHU of Liege, Belgium
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/CMakeLists.txt Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,43 @@ +cmake_minimum_required (VERSION 2.8) + +project(Orthanc_Import) + +find_package(Java REQUIRED) +include(UseJava) + +set(CMAKE_JAVA_COMPILE_FLAGS "-source" "1.6" "-target" "1.6") +set(CMAKE_JAVA_INCLUDE_PATH /usr/share/java/ij.jar) + +# The name of an ImageJ plugin must contain an underscore +# http://imagejdocu.tudor.lu/doku.php?id=howto:plugins:howto_create_an_imagej_plugin_jar_file +add_jar(Orthanc_Import + # Sources of the plugin + ${CMAKE_SOURCE_DIR}/com/orthancserver/DicomDecoder.java + ${CMAKE_SOURCE_DIR}/com/orthancserver/Orthanc.java + ${CMAKE_SOURCE_DIR}/com/orthancserver/OrthancConfigurationDialog.java + ${CMAKE_SOURCE_DIR}/com/orthancserver/OrthancConnection.java + ${CMAKE_SOURCE_DIR}/com/orthancserver/PreviewPanel.java + ${CMAKE_SOURCE_DIR}/com/orthancserver/SelectImageDialog.java + + # Sources of the "json-simple" toolkit + ${CMAKE_SOURCE_DIR}/org/json/simple/ItemList.java + ${CMAKE_SOURCE_DIR}/org/json/simple/JSONArray.java + ${CMAKE_SOURCE_DIR}/org/json/simple/JSONAware.java + ${CMAKE_SOURCE_DIR}/org/json/simple/JSONObject.java + ${CMAKE_SOURCE_DIR}/org/json/simple/JSONStreamAware.java + ${CMAKE_SOURCE_DIR}/org/json/simple/JSONValue.java + ${CMAKE_SOURCE_DIR}/org/json/simple/parser/ContainerFactory.java + ${CMAKE_SOURCE_DIR}/org/json/simple/parser/ContentHandler.java + ${CMAKE_SOURCE_DIR}/org/json/simple/parser/JSONParser.java + ${CMAKE_SOURCE_DIR}/org/json/simple/parser/ParseException.java + ${CMAKE_SOURCE_DIR}/org/json/simple/parser/Yylex.java + ${CMAKE_SOURCE_DIR}/org/json/simple/parser/Yytoken.java + ) + +# Add the "plugins.config" file that is expected by ImageJ in the JAR file +add_custom_command(TARGET Orthanc_Import + POST_BUILD + COMMAND jar uf ${CMAKE_CURRENT_BINARY_DIR}/Orthanc_Import.jar plugins.config + WORKING_DIRECTORY ${CMAKE_SOURCE_DIR} + COMMENT "Packaging the configuration file" VERBATIM + )
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/COPYING Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/> + 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. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + 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 <http://www.gnu.org/licenses/>. + +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: + + <program> Copyright (C) <year> <name of author> + 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 +<http://www.gnu.org/licenses/>. + + 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 +<http://www.gnu.org/philosophy/why-not-lgpl.html>.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/INSTALL Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,36 @@ +Installing pre-compiled binaries +================================ + +Pre-compiled binaries of this plugin are available at: +http://sourceforge.net/projects/orthancserver/files/ImageJ/ + + +Windows Installation +-------------------- + +Download the most recent ".jar" file, then put it into the "plugins" +folder of the ImageJ distribution. By default, this folder is: + +C:\Program Files\ImageJ\plugins\ + + +Linux Installation +------------------ + +Download the most recent ".jar" file, then put it into the following +folder: + +~/.imagej/plugins/ + + +Building from source +==================== + +You will first have to install CMake (http://www.cmake.org/) and, of +course, ImageJ. Here are the commands to build from source under +Linux: + +# mkdir Build +# cd Build +# cmake .. +# make
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/NEWS Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,9 @@ +Pending changes in the mainline +=============================== + + + +Version 1.0.0 (2014/12/08) +========================== + +* Initial release
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/README Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,57 @@ +Orthanc - A Lightweight, RESTful DICOM Server +============================================= + + +General Information +------------------- + +This repository contains an ImageJ plugin that allows to easily access +DICOM images that are stored in some Orthanc server. This plugin might +be useful to medical physicists for QA tasks, as well as for +pedagogical purpose. + +Demonstration: http://youtu.be/wsslVhE-R1Q + +The instructions for building/installing the plugin can be found in +the "INSTALL" file. + + +Licensing +--------- + +Orthanc and this plugin are licensed under the GPLv3 license. + +We also kindly ask scientific works and clinical studies that make +use of Orthanc to cite Orthanc in their associated publications. +Similarly, we ask open-source and closed-source products that make +use of Orthanc to warn us about this use. You can cite our work +using the following BibTeX entry: + +@inproceedings{Jodogne:ISBI2013, + author = {Jodogne, S. and Bernard, C. and Devillers, M. and Lenaerts, E. and Coucke, P.}, + title = {Orthanc -- {A} Lightweight, {REST}ful {DICOM} Server for Healthcare and Medical Research}, + booktitle={Biomedical Imaging ({ISBI}), {IEEE} 10th International Symposium on}, + year={2013}, + pages={190-193}, + ISSN={1945-7928}, + month=apr, + url={http://ieeexplore.ieee.org/xpl/articleDetails.jsp?tp=&arnumber=6556444}, + address={San Francisco, {CA}, {USA}} +} + + +Disclaimer +---------- + +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. + + +Dependencies +------------ + +This plugin depends upon the "json-simple" toolkit +(http://code.google.com/p/json-simple/), that is released under the +Apache License 2.0. The source of this dependency is located in the +"org/" folder.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/com/orthancserver/DicomDecoder.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,427 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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 <http://www.gnu.org/licenses/>. + **/ + + +package com.orthancserver; + +import ij.ImagePlus; +import ij.ImageStack; +import ij.process.ImageProcessor; +import ij.process.ShortProcessor; +import ij.process.ColorProcessor; +import ij.io.FileInfo; +import ij.measure.Calibration; +import org.json.simple.*; +import java.util.List; +import java.util.ArrayList; +import java.util.Collections; +import java.io.IOException; +import javax.swing.SwingWorker; +import java.util.concurrent.ExecutionException; + +import javax.swing.JFrame; +import javax.swing.JProgressBar; +import java.awt.BorderLayout; +import javax.swing.JPanel; +import javax.swing.JButton; +import java.awt.FlowLayout; +import javax.swing.border.EmptyBorder; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + + +public class DicomDecoder +{ + private static class ProgressDialog extends JFrame + { + private JProgressBar bar_ = new JProgressBar(); + private boolean canceled_ = false; + + public ProgressDialog(int count) + { + getContentPane().setLayout(new BorderLayout()); + bar_.setBorder(new EmptyBorder(20, 20, 20, 20)); + getContentPane().add(bar_, BorderLayout.NORTH); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); + getContentPane().add(buttonPane, BorderLayout.SOUTH); + + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + canceled_ = true; + } + }); + buttonPane.add(cancelButton); + + bar_.setMaximum(0); + bar_.setMaximum(count); + + setSize(500, 150); + setTitle("Importing series from Orthanc"); + setLocationRelativeTo(null); // Center dialog on screen + } + + public void SetProgress(int value) + { + bar_.setValue(value); + } + + public boolean IsCanceled() + { + return canceled_; + } + }; + + private static void ExtractCalibration(ImagePlus image, + JSONObject tags) + { + JSONObject rescaleIntercept = (JSONObject) tags.get("0028,1052"); + JSONObject rescaleSlope = (JSONObject) tags.get("0028,1053"); + if (rescaleIntercept != null && + rescaleSlope != null) + { + double[] coeff = { + Float.valueOf((String) rescaleIntercept.get("Value")), + Float.valueOf((String) rescaleSlope.get("Value")) + }; + image.getCalibration().setFunction(Calibration.STRAIGHT_LINE, coeff, "Gray Value"); + } + } + + private static void ExtractPixelSpacing(ImagePlus image, + JSONObject tags) + { + JSONObject pixelSpacing = (JSONObject) tags.get("0028,0030"); + if (pixelSpacing != null) + { + String[] tokens = ((String) pixelSpacing.get("Value")).split("\\\\"); + if (tokens.length == 2) + { + FileInfo fi = image.getFileInfo(); + fi.pixelWidth = Float.valueOf(tokens[0]); + fi.pixelHeight = Float.valueOf(tokens[1]); + fi.unit = "mm"; + + image.setFileInfo(fi); + image.getCalibration().pixelWidth = fi.pixelWidth; + image.getCalibration().pixelHeight = fi.pixelHeight; + image.getCalibration().setUnit(fi.unit); + } + } + } + + private static void ExtractDicomInfo(ImagePlus image, + JSONObject tags) + { + String info = new String(); + + ArrayList<String> tagsIndex = new ArrayList<String>(); + for (Object tag : tags.keySet()) + { + tagsIndex.add((String) tag); + } + + Collections.sort(tagsIndex); + for (String tag : tagsIndex) + { + JSONObject value = (JSONObject) tags.get(tag); + + if (((String) value.get("Type")).equals("String")) + { + info += (tag + " " + (String) value.get("Name") + + ": " + (String) value.get("Value") + "\n"); + } + } + + image.setProperty("Info", info); + } + + private static ImageProcessor DecodeInstance(OrthancConnection c, + String uuid) throws IOException + { + try + { + String uri = "/instances/" + uuid + "/image-uint16"; + ShortProcessor slice = new ShortProcessor(c.ReadImage(uri)); + return slice; + } + catch (IllegalArgumentException e) + { + // Color image + String uri = "/instances/" + uuid + "/preview"; + ColorProcessor slice = new ColorProcessor(c.ReadImage(uri)); + return slice; + } + } + + private static ImageStack AddSlice(ImageStack stack, + OrthancConnection c, + String uuid) throws IOException + { + ImageProcessor slice = DecodeInstance(c, uuid); + + if (stack == null) + { + stack = new ImageStack(slice.getWidth(), slice.getHeight()); + } + + stack.addSlice(slice); + return stack; + } + + + static private class Slice implements Comparable + { + private Float index_; + private String uuid_; + + Slice(float index, + String uuid) + { + index_ = index; + uuid_ = uuid; + } + + @Override + public int compareTo(Object other) + { + return index_.compareTo(((Slice) other).index_); + } + + public String GetUuid() + { + return uuid_; + } + } + + + + private String[] SortSlices(List<Slice> slices) + { + Collections.sort(slices); + + String[] result = new String[slices.size()]; + + for (int i = 0; i < slices.size(); i++) + { + result[i] = slices.get(i).GetUuid(); + } + + return result; + } + + + + private String[] SortSlicesBy3D(OrthancConnection c, + JSONArray instances) throws IOException + { + ArrayList<Slice> slices = new ArrayList<Slice>(); + float normal[] = null; + + float minDistance = Float.POSITIVE_INFINITY; + float maxDistance = Float.NEGATIVE_INFINITY; + + for (int i = 0; i < instances.size(); i++) + { + String uuid = (String) instances.get(i); + JSONObject instance = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags?simplify"); + if (!instance.containsKey("ImageOrientationPatient") || + !instance.containsKey("ImagePositionPatient")) + { + return null; + } + + if (i == 0) + { + String[] tokens = ((String) instance.get("ImageOrientationPatient")).split("\\\\"); + if (tokens.length != 6) + { + return null; + } + + float cosines[] = new float[6]; + for (int j = 0; j < 6; j++) + { + cosines[j] = Float.parseFloat(tokens[j]); + } + + normal = new float[] { + cosines[1] * cosines[5] - cosines[2] * cosines[4], + cosines[2] * cosines[3] - cosines[0] * cosines[5], + cosines[0] * cosines[4] - cosines[1] * cosines[3] + }; + } + + String[] tokens = ((String) instance.get("ImagePositionPatient")).split("\\\\"); + if (tokens.length != 3) + { + return null; + } + + float distance = 0; + for (int j = 0; j < 3; j++) + { + distance += normal[j] * Float.parseFloat(tokens[j]); + } + + minDistance = Math.min(minDistance, distance); + maxDistance = Math.max(minDistance, distance); + slices.add(new Slice(distance, uuid)); + } + + if (maxDistance - minDistance < 0.001) + { + return null; + } + + return SortSlices(slices); + } + + + private String[] SortSlicesByNumber(OrthancConnection c, + JSONArray instances) throws IOException + { + ArrayList<Slice> slices = new ArrayList<Slice>(); + + for (int i = 0; i < instances.size(); i++) + { + String uuid = (String) instances.get(i); + JSONObject instance = (JSONObject) c.ReadJson("/instances/" + uuid); + Long index = (Long) instance.get("IndexInSeries"); + slices.add(new Slice((float) index, uuid)); + } + + return SortSlices(slices); + } + + + + private String[] GetSlices(OrthancConnection c, + JSONArray instances) throws IOException + { + String[] result; + + result = SortSlicesBy3D(c, instances); + if (result != null && result.length == instances.size()) + { + return result; + } + + result = SortSlicesByNumber(c, instances); + if (result != null && result.length == instances.size()) + { + return result; + } + + throw new IOException("Not a 3D image"); + } + + + + + private ImagePlus image_; + + public DicomDecoder(final OrthancConnection c, + boolean isInstance, + String uuid) throws IOException, InterruptedException, ExecutionException + { + ImageStack stack = null; + JSONObject tags = null; + String tagsUri, name; + + if (isInstance) + { + name = "Instance " + uuid; + tags = (JSONObject) c.ReadJson("/instances/" + uuid + "/tags"); + stack = AddSlice(stack, c, uuid); + } + else + { + name = "Series " + uuid; + + JSONObject series = (JSONObject) c.ReadJson("/series/" + uuid); + JSONArray instances = (JSONArray) series.get("Instances"); + + try + { + tags = (JSONObject) c.ReadJson("/series/" + uuid + "/shared-tags"); + } + catch (Exception e) + { + // Fallback for old versions of Orthanc, without "shared-tags" + tags = (JSONObject) c.ReadJson("/instances/" + (String) instances.get(0) + "/tags"); + } + + final String[] slices = GetSlices(c, instances); + final ProgressDialog progress = new ProgressDialog(slices.length); + + try + { + progress.setVisible(true); + SwingWorker<ImageStack, Float> worker = new SwingWorker<ImageStack, Float>() { + @Override + protected ImageStack doInBackground() + { + try + { + ImageStack stack = null; + + for (int i = 0; i < slices.length; i++) + { + if (progress.IsCanceled()) + { + return null; + } + + progress.SetProgress(i); + stack = AddSlice(stack, c, slices[i]); + } + + return stack; + } + catch (IOException e) + { + return null; + } + } + }; + + worker.execute(); + stack = worker.get(); + } + finally + { + progress.setVisible(false); + } + } + + image_ = new ImagePlus(name, stack); + + ExtractCalibration(image_, tags); + ExtractPixelSpacing(image_, tags); + ExtractDicomInfo(image_, tags); + } + + public ImagePlus GetImage() + { + return image_; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/com/orthancserver/GridLayout2.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,167 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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 <http://www.gnu.org/licenses/>. + **/ + + +package com.orthancserver; + +import java.awt.*; + +public class GridLayout2 extends GridLayout +{ + public GridLayout2() { + this(1, 0, 0, 0); + } + + public GridLayout2(int rows, int cols) { + this(rows, cols, 0, 0); + } + + public GridLayout2(int rows, int cols, int hgap, int vgap) { + super(rows, cols, hgap, vgap); + } + + public Dimension preferredLayoutSize(Container parent) { + synchronized (parent.getTreeLock()) { + Insets insets = parent.getInsets(); + int ncomponents = parent.getComponentCount(); + int nrows = getRows(); + int ncols = getColumns(); + if (nrows > 0) { + ncols = (ncomponents + nrows - 1) / nrows; + } + else { + nrows = (ncomponents + ncols - 1) / ncols; + } + int[] w = new int[ncols]; + int[] h = new int[nrows]; + for (int i = 0; i < ncomponents; i ++) { + int r = i / ncols; + int c = i % ncols; + Component comp = parent.getComponent(i); + Dimension d = comp.getPreferredSize(); + if (w[c] < d.width) { + w[c] = d.width; + } + if (h[r] < d.height) { + h[r] = d.height; + } + } + int nw = 0; + for (int j = 0; j < ncols; j ++) { + nw += w[j]; + } + int nh = 0; + for (int i = 0; i < nrows; i ++) { + nh += h[i]; + } + return new Dimension(insets.left + insets.right + nw + (ncols-1)*getHgap(), + insets.top + insets.bottom + nh + (nrows-1)*getVgap()); + } + } + + public Dimension minimumLayoutSize(Container parent) { + synchronized (parent.getTreeLock()) { + Insets insets = parent.getInsets(); + int ncomponents = parent.getComponentCount(); + int nrows = getRows(); + int ncols = getColumns(); + if (nrows > 0) { + ncols = (ncomponents + nrows - 1) / nrows; + } + else { + nrows = (ncomponents + ncols - 1) / ncols; + } + int[] w = new int[ncols]; + int[] h = new int[nrows]; + for (int i = 0; i < ncomponents; i ++) { + int r = i / ncols; + int c = i % ncols; + Component comp = parent.getComponent(i); + Dimension d = comp.getMinimumSize(); + if (w[c] < d.width) { + w[c] = d.width; + } + if (h[r] < d.height) { + h[r] = d.height; + } + } + int nw = 0; + for (int j = 0; j < ncols; j ++) { + nw += w[j]; + } + int nh = 0; + for (int i = 0; i < nrows; i ++) { + nh += h[i]; + } + return new Dimension(insets.left + insets.right + nw + (ncols-1)*getHgap(), + insets.top + insets.bottom + nh + (nrows-1)*getVgap()); + } + } + + public void layoutContainer(Container parent) { + synchronized (parent.getTreeLock()) { + Insets insets = parent.getInsets(); + int ncomponents = parent.getComponentCount(); + int nrows = getRows(); + int ncols = getColumns(); + if (ncomponents == 0) { + return; + } + if (nrows > 0) { + ncols = (ncomponents + nrows - 1) / nrows; + } + else { + nrows = (ncomponents + ncols - 1) / ncols; + } + int hgap = getHgap(); + int vgap = getVgap(); + // scaling factors + Dimension pd = preferredLayoutSize(parent); + double sw = (1.0 * parent.getWidth()) / pd.width; + double sh = (1.0 * parent.getHeight()) / pd.height; + // scale + int[] w = new int[ncols]; + int[] h = new int[nrows]; + for (int i = 0; i < ncomponents; i ++) { + int r = i / ncols; + int c = i % ncols; + Component comp = parent.getComponent(i); + Dimension d = comp.getPreferredSize(); + d.width = (int) (sw * d.width); + d.height = (int) (sh * d.height); + if (w[c] < d.width) { + w[c] = d.width; + } + if (h[r] < d.height) { + h[r] = d.height; + } + } + for (int c = 0, x = insets.left; c < ncols; c ++) { + for (int r = 0, y = insets.top; r < nrows; r ++) { + int i = r * ncols + c; + if (i < ncomponents) { + parent.getComponent(i).setBounds(x, y, w[c], h[r]); + } + y += h[r] + vgap; + } + x += w[c] + hgap; + } + } + } +} \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/com/orthancserver/Orthanc.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,51 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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 <http://www.gnu.org/licenses/>. + **/ + + +package com.orthancserver; + +import ij.plugin.PlugIn; +import ij.Prefs; +import javax.swing.JOptionPane; + +public class Orthanc implements PlugIn +{ + public void run(String arg) + { + SelectImageDialog d = new SelectImageDialog(); + d.Unserialize(Prefs.get("orthanc.servers", "")); + + boolean success = d.ShowModal(); + Prefs.set("orthanc.servers", d.Serialize()); + + if (success) + { + try + { + DicomDecoder decoder = new DicomDecoder(d.GetSelectedConnection(), d.IsInstanceSelected(), d.GetSelectedUuid()); + decoder.GetImage().show(); + } + catch (Exception e) + { + JOptionPane.showMessageDialog(null, "Error while importing this image: " + e.getMessage()); + //e.printStackTrace(System.out); + } + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/com/orthancserver/OrthancConfigurationDialog.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,169 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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 <http://www.gnu.org/licenses/>. + **/ + + +package com.orthancserver; + +import java.awt.BorderLayout; +import java.awt.Canvas; +import java.awt.FlowLayout; +import java.awt.GridLayout; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import java.io.IOException; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JLabel; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JScrollPane; +import javax.swing.JSplitPane; +import javax.swing.JTextField; +import javax.swing.JTree; +import javax.swing.SwingWorker; +import javax.swing.border.EmptyBorder; + +import org.json.simple.JSONObject; + + +public class OrthancConfigurationDialog extends JDialog +{ + private JTextField name_ = new JTextField("Orthanc"); + private JTextField url_ = new JTextField("http://localhost:8042/"); + private JTextField username_ = new JTextField(""); + private JTextField password_ = new JPasswordField(""); + private boolean isSuccess_; + + private OrthancConnection CreateConnection() + { + OrthancConnection orthanc = new OrthancConnection(); + orthanc.SetName(name_.getText()); + orthanc.SetBaseUrl(url_.getText()); + + if (username_.getText().length() != 0) + { + orthanc.SetCredentials(username_.getText(), password_.getText()); + } + + return orthanc; + } + + public OrthancConfigurationDialog() + { + final JPanel contentPanel = new JPanel(); + contentPanel.setBorder(new EmptyBorder(20, 5, 5, 5)); + contentPanel.setLayout(new GridLayout2(0, 2, 20, 5)); + + JLabel label = new JLabel("Name:"); + label.setHorizontalAlignment(JLabel.RIGHT); + contentPanel.add(label); + contentPanel.add(name_); + + label = new JLabel("URL:"); + label.setHorizontalAlignment(JLabel.RIGHT); + contentPanel.add(label); + contentPanel.add(url_); + + label = new JLabel("Username:"); + label.setHorizontalAlignment(JLabel.RIGHT); + contentPanel.add(label); + contentPanel.add(username_); + + label = new JLabel("Password:"); + label.setHorizontalAlignment(JLabel.RIGHT); + contentPanel.add(label); + contentPanel.add(password_); + + getContentPane().setLayout(new BorderLayout()); + getContentPane().add(contentPanel, BorderLayout.NORTH); + + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); + getContentPane().add(buttonPane, BorderLayout.SOUTH); + { + { + JButton test = new JButton("Test connection"); + test.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + OrthancConnection orthanc = CreateConnection(); + try + { + JSONObject system = (JSONObject) orthanc.ReadJson("system"); + JOptionPane.showMessageDialog(null, "Successfully connected to this Orthanc server " + + "(version: " + (String) system.get("Version") + ")!", + "Success", JOptionPane.INFORMATION_MESSAGE); + } + catch (IOException e) + { + JOptionPane.showMessageDialog(null, "Cannot connect to this Orthanc server!", + "Error", JOptionPane.ERROR_MESSAGE); + } + } + }); + buttonPane.add(test); + } + { + JButton okButton = new JButton("Add"); + okButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + isSuccess_ = true; + setVisible(false); + } + }); + buttonPane.add(okButton); + getRootPane().setDefaultButton(okButton); + } + { + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + setVisible(false); + } + }); + buttonPane.add(cancelButton); + } + } + + setUndecorated(false); + setSize(500,500); + setTitle("Add new server"); + setModal(true); + } + + + + public OrthancConnection ShowModal() + { + isSuccess_ = false; + setVisible(true); + if (isSuccess_) + { + return CreateConnection(); + } + else + { + return null; + } + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/com/orthancserver/OrthancConnection.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,217 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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 <http://www.gnu.org/licenses/>. + **/ + + +package com.orthancserver; + +import java.awt.image.BufferedImage; +import java.io.BufferedReader; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.ConnectException; +import java.net.URL; +import java.net.URLConnection; +import javax.imageio.ImageIO; +import javax.xml.bind.DatatypeConverter; +import org.json.simple.JSONObject; +import org.json.simple.JSONValue; + +public class OrthancConnection +{ + private String baseUrl_; + private String authentication_; + private String name_; + + OrthancConnection() + { + baseUrl_ = "http://localhost:8042/"; + authentication_ = null; + name_ = "Default Orthanc server"; + } + + + private static InputStream OpenUrl(String urlString) throws IOException + { + URL url = new URL(urlString); + + try + { + return url.openStream(); + } + catch (ConnectException e) + { + throw new IOException(); + } + } + + + private static InputStream OpenUrl(String urlString, + String authentication) throws IOException + { + try + { + URL url = new URL(urlString); + // http://blogs.deepal.org/2008/01/sending-basic-authentication-using-url.html + URLConnection uc = url.openConnection(); + uc.setRequestProperty("Authorization", "Basic " + authentication); + return uc.getInputStream(); + } + catch (ConnectException e) + { + throw new IOException(); + } + } + + + private static String ComputeAuthentication(String username, + String password) + { + String auth = (new StringBuffer(username).append(":").append(password)).toString(); + // http://stackoverflow.com/a/14413290/881731 + return DatatypeConverter.printBase64Binary(auth.getBytes()); + } + + + public InputStream OpenStream(String uri) throws IOException + { + String url = baseUrl_ + uri; + return authentication_ == null ? OpenUrl(url) : OpenUrl(url, authentication_); + } + + + public void SetCredentials(String username, + String password) + { + authentication_ = ComputeAuthentication(username, password); + } + + public void SetBaseUrl(String url) + { + if (url.endsWith("/")) + { + baseUrl_ = url; + } + else + { + baseUrl_ = url + "/"; + } + } + + public String GetBaseUrl() + { + return baseUrl_; + } + + public String ReadString(String uri) throws IOException + { + InputStream stream = OpenStream(uri); + + BufferedReader reader = null; + try + { + reader = new BufferedReader(new InputStreamReader(stream)); + + StringBuffer buffer = new StringBuffer(); + int read; + char[] chars = new char[1024 * 16]; + while ((read = reader.read(chars)) != -1) + { + buffer.append(chars, 0, read); + } + + return buffer.toString(); + } + finally + { + try + { + if (reader != null) + { + reader.close(); + } + } + catch (IOException e) + { + } + } + } + + public Object ReadJson(String uri) throws IOException + { + String content = ReadString(uri); + Object json = JSONValue.parse(content); + + if (json == null) + { + throw new IOException(); + } + else + { + return json; + } + } + + public BufferedImage ReadImage(String uri) throws IOException + { + return ImageIO.read(OpenStream(uri)); + } + + public String GetName() + { + return name_; + } + + public void SetName(String name) + { + name_ = name; + } + + public JSONObject Serialize() + { + JSONObject json = new JSONObject(); + json.put("Name", name_); + json.put("Url", baseUrl_); + + if (authentication_ != null) + { + json.put("Authentication", authentication_); + } + + return json; + } + + public static OrthancConnection Unserialize(JSONObject json) + { + OrthancConnection c = new OrthancConnection(); + c.SetName((String) json.get("Name")); + c.SetBaseUrl((String) json.get("Url")); + + if (json.containsKey("Authentication")) + { + c.authentication_ = (String) json.get("Authentication"); + } + else + { + c.authentication_ = null; + } + + return c; + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/com/orthancserver/PreviewPanel.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,83 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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 <http://www.gnu.org/licenses/>. + **/ + + +package com.orthancserver; + +import java.awt.Graphics; +import java.awt.image.BufferedImage; +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.io.ByteArrayInputStream; +import java.util.logging.Level; +import java.util.logging.Logger; +import javax.imageio.ImageIO; +import javax.swing.JPanel; + +public class PreviewPanel extends JPanel +{ + private BufferedImage image_ = null; + + public void Reset() + { + image_ = null; + repaint(); + } + + public void Load(OrthancConnection orthanc, + String uri) + { + try + { + image_ = orthanc.ReadImage(uri); + repaint(); + } + catch (IOException e) + { + Reset(); + } + } + + @Override + protected void paintComponent(Graphics g) + { + super.paintComponent(g); + + if (image_ != null) + { + float scaleX = (float) getWidth() / (float) image_.getWidth(); + float scaleY = (float) getHeight() / (float) image_.getHeight(); + float scale = Math.min(scaleX, scaleY); + if (scale > 1) + { + // Do not upscale the image + scale = 1; + } + + int width = Math.round((float) image_.getWidth() * scale); + int height = Math.round((float) image_.getHeight() * scale); + + int dx = (getWidth() - width) / 2; + int dy = (getHeight() - height) / 2; + g.drawImage(image_, dx, dy, dx + width, dy + height, + 0, 0, image_.getWidth(), image_.getHeight(), null); + } + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/com/orthancserver/SelectImageDialog.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,580 @@ +/** + * Orthanc - A Lightweight, RESTful DICOM Store + * Copyright (C) 2012-2014 Medical Physics Department, CHU of Liege, + * Belgium + * + * 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 <http://www.gnu.org/licenses/>. + **/ + + +package com.orthancserver; + +import org.json.simple.JSONValue; +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; +import java.io.IOException; +import java.util.ArrayList; +import java.util.List; +import java.util.Collections; +import java.util.Enumeration; + + +import java.awt.Canvas; +import java.awt.GridLayout; +import java.awt.event.MouseAdapter; +import java.awt.event.MouseEvent; +import javax.swing.BoxLayout; +import javax.swing.JButton; +import javax.swing.JDialog; +import javax.swing.JOptionPane; +import javax.swing.JPanel; +import javax.swing.JSplitPane; +import javax.swing.JScrollPane; +import javax.swing.JTree; +import javax.swing.SwingWorker; +import javax.swing.border.EmptyBorder; +import java.awt.BorderLayout; +import java.awt.FlowLayout; +import java.awt.event.ActionListener; +import java.awt.event.ActionEvent; + +import javax.xml.bind.DatatypeConverter; +import javax.swing.event.TreeExpansionEvent; +import javax.swing.event.TreeWillExpandListener; +import javax.swing.event.TreeSelectionEvent; +import javax.swing.event.TreeSelectionListener; +import javax.swing.tree.DefaultMutableTreeNode; +import javax.swing.tree.DefaultTreeModel; +import javax.swing.tree.ExpandVetoException; +import javax.swing.tree.MutableTreeNode; +import javax.swing.tree.TreePath; + + +public class SelectImageDialog extends JDialog +{ + private enum ResourceType { + ROOT, + SERVER, + PATIENT, + STUDY, + SERIES, + INSTANCE, + INFO; + } + + + private static class MyTreeNode extends DefaultMutableTreeNode implements Comparable + { + private OrthancConnection orthanc_; + private boolean loaded_ = false; + private ResourceType type_; + private String uuid_; + + + public String GetUuid() + { + return uuid_; + } + + public ResourceType GetResourceType() + { + return type_; + } + + public OrthancConnection GetConnection() + { + return orthanc_; + } + + public boolean UpdatePreview(PreviewPanel preview) + { + if (type_ == ResourceType.INSTANCE) + { + preview.Load(orthanc_, "/instances/" + uuid_ + "/preview"); + return true; + } + else if (type_ == ResourceType.SERIES) + { + try + { + JSONObject series = (JSONObject) orthanc_.ReadJson("series/" + uuid_); + JSONArray instances = (JSONArray) series.get("Instances"); + if (instances.size() > 0) + { + preview.Load(orthanc_, "/instances/" + instances.get(0) + "/preview"); + return true; + } + } + catch (IOException e) + { + } + } + + preview.Reset(); + return false; + } + + + private String AddComponent(String source, String component) + { + if (component == null || + component.length() == 0) + { + return source; + } + + if (source.length() == 0) + { + return component; + } + else + { + return source + " - " + component; + } + } + + + private List<MyTreeNode> LoadPatients() throws IOException + { + List<MyTreeNode> children = new ArrayList<MyTreeNode>(); + + JSONArray patients = (JSONArray) orthanc_.ReadJson("patients"); + for (int i = 0; i < patients.size(); i++) + { + String uuid = (String) patients.get(i); + JSONObject patient = (JSONObject) orthanc_.ReadJson("patients/" + uuid); + JSONObject main = (JSONObject) patient.get("MainDicomTags"); + + String s = new String(); + s = AddComponent(s, (String) main.get("PatientID")); + s = AddComponent(s, (String) main.get("PatientName")); + children.add(new MyTreeNode(orthanc_, ResourceType.PATIENT, uuid, s)); + } + + return children; + } + + + private List<MyTreeNode> LoadStudies() throws IOException + { + List<MyTreeNode> children = new ArrayList<MyTreeNode>(); + + JSONObject patient = (JSONObject) orthanc_.ReadJson("patients/" + uuid_); + JSONArray studies = (JSONArray) patient.get("Studies"); + for (int i = 0; i < studies.size(); i++) + { + String uuid = (String) studies.get(i); + JSONObject study = (JSONObject) orthanc_.ReadJson("studies/" + uuid); + JSONObject main = (JSONObject) study.get("MainDicomTags"); + + String s = new String(); + s = AddComponent(s, (String) main.get("StudyDescription")); + s = AddComponent(s, (String) main.get("StudyDate")); + children.add(new MyTreeNode(orthanc_, ResourceType.STUDY, uuid, s)); + } + + return children; + } + + + private List<MyTreeNode> LoadSeries() throws IOException + { + List<MyTreeNode> children = new ArrayList<MyTreeNode>(); + + JSONObject study = (JSONObject) orthanc_.ReadJson("studies/" + uuid_); + JSONArray seriesSet = (JSONArray) study.get("Series"); + for (int i = 0; i < seriesSet.size(); i++) + { + String uuid = (String) seriesSet.get(i); + JSONObject series = (JSONObject) orthanc_.ReadJson("series/" + uuid); + JSONObject main = (JSONObject) series.get("MainDicomTags"); + + String s = new String(); + s = AddComponent(s, (String) main.get("Modality")); + s = AddComponent(s, (String) main.get("SeriesDescription")); + children.add(new MyTreeNode(orthanc_, ResourceType.SERIES, uuid, s)); + } + + return children; + } + + + private List<MyTreeNode> LoadInstances() throws IOException + { + List<MyTreeNode> children = new ArrayList<MyTreeNode>(); + + JSONObject series = (JSONObject) orthanc_.ReadJson("series/" + uuid_); + JSONArray instances = (JSONArray) series.get("Instances"); + for (int i = 0; i < instances.size(); i++) + { + String uuid = (String) instances.get(i); + JSONObject instance = (JSONObject) orthanc_.ReadJson("instances/" + uuid); + Long index = (Long) instance.get("IndexInSeries"); + String s; + if (index == null) + { + s = uuid; + } + else + { + s = String.valueOf(index); + } + + children.add(new MyTreeNode(orthanc_, ResourceType.INSTANCE, uuid, s)); + } + + return children; + } + + + public MyTreeNode() // Create root node + { + loaded_ = true; + orthanc_ = null; + type_ = ResourceType.ROOT; + uuid_ = ""; + setAllowsChildren(true); + } + + public MyTreeNode(OrthancConnection orthanc, + ResourceType type, + String id, + String name) + { + orthanc_ = orthanc; + type_ = type; + uuid_ = id; + add(new DefaultMutableTreeNode("Loading...", false)); + setAllowsChildren(true); + setUserObject(name); + } + + @Override + public int compareTo(Object other) + { + String a = (String) getUserObject(); + String b = (String) ((MyTreeNode) other).getUserObject(); + return a.compareTo(b); + } + + private void SetChildren(List<MyTreeNode> children) + { + Collections.sort(children); + + removeAllChildren(); + setAllowsChildren(children.size() > 0); + for (MutableTreeNode node : children) + { + add(node); + } + loaded_ = true; + } + + @Override + public boolean isLeaf() + { + return type_ == ResourceType.INSTANCE || type_ == ResourceType.INFO; + } + + public void LoadChildren(final DefaultTreeModel model) + { + if (loaded_) + { + return; + } + + SwingWorker<List<MyTreeNode>, Void> worker = new SwingWorker<List<MyTreeNode>, Void>() { + @Override + protected List<MyTreeNode> doInBackground() + { + List<MyTreeNode> children = null; + + try + { + switch (type_) + { + case SERVER: children = LoadPatients(); break; + case PATIENT: children = LoadStudies(); break; + case STUDY: children = LoadSeries(); break; + case SERIES: children = LoadInstances(); break; + default: + break; + } + } + catch (IOException e) + { + children = null; + } + + if (children == null) + { + children = new ArrayList<MyTreeNode>(); + children.add(new MyTreeNode(orthanc_, ResourceType.INFO, "", "Orthanc is not running, or bad credentials")); + } + + return children; + } + + @Override + protected void done() + { + try + { + SetChildren(get()); + model.nodeStructureChanged(MyTreeNode.this); + } + catch (Exception e) + { + } + + super.done(); + } + }; + + worker.execute(); + } + + } + + + private MyTreeNode root_ = new MyTreeNode(); + private JTree tree_ = null; + private boolean isSuccess_; + private String selectedUuid_; + private ResourceType selectedType_; + private OrthancConnection selectedConnection_; + private JButton okButton_ = new JButton("Open"); + private JButton removeServer_ = new JButton("Remove server"); + private PreviewPanel preview_ = new PreviewPanel(); + + public SelectImageDialog() + { + tree_ = new JTree(); + + tree_.addTreeWillExpandListener(new TreeWillExpandListener() + { + @Override + public void treeWillExpand(TreeExpansionEvent event) throws ExpandVetoException { + TreePath path = event.getPath(); + if (path.getLastPathComponent() instanceof MyTreeNode) { + MyTreeNode node = (MyTreeNode) path.getLastPathComponent(); + node.LoadChildren((DefaultTreeModel) tree_.getModel()); + } + } + + @Override + public void treeWillCollapse(TreeExpansionEvent event) throws ExpandVetoException { + } + }); + + + tree_.addTreeSelectionListener(new TreeSelectionListener() + { + @Override + public void valueChanged(TreeSelectionEvent e) { + TreePath path = e.getNewLeadSelectionPath(); + if (path != null) + { + MyTreeNode node = (MyTreeNode) path.getLastPathComponent(); + if (node.UpdatePreview(preview_)) + { + selectedType_ = node.GetResourceType(); + selectedUuid_ = node.GetUuid(); + selectedConnection_ = node.GetConnection(); + okButton_.setEnabled(true); + } + + removeServer_.setEnabled(node.GetResourceType() == ResourceType.SERVER); + } + } + }); + + + tree_.addMouseListener(new MouseAdapter() + { + public void mousePressed(MouseEvent e) { + TreePath path = tree_.getPathForLocation(e.getX(), e.getY()); + if (path != null) { + MyTreeNode node = (MyTreeNode) path.getLastPathComponent(); + if (e.getClickCount() == 2 && + node.GetResourceType() == ResourceType.INSTANCE) { + // Double click on an instance, close the dialog + isSuccess_ = true; + setVisible(false); + } + } + } + }); + + + final JPanel contentPanel = new JPanel(); + getContentPane().setLayout(new BorderLayout()); + contentPanel.setBorder(new EmptyBorder(5, 5, 5, 5)); + getContentPane().add(contentPanel, BorderLayout.CENTER); + contentPanel.setLayout(new BorderLayout(0, 0)); + { + JSplitPane splitPane = new JSplitPane(); + splitPane.setResizeWeight(0.6); + contentPanel.add(splitPane); + + splitPane.setLeftComponent(new JScrollPane(tree_)); + splitPane.setRightComponent(preview_); + } + { + JPanel buttonPane = new JPanel(); + buttonPane.setLayout(new FlowLayout(FlowLayout.RIGHT)); + getContentPane().add(buttonPane, BorderLayout.SOUTH); + { + JButton btnAddServer = new JButton("Add server"); + btnAddServer.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + OrthancConfigurationDialog dd = new OrthancConfigurationDialog(); + dd.setLocationRelativeTo(null); // Center dialog on screen + + OrthancConnection orthanc = dd.ShowModal(); + if (orthanc != null) { + AddOrthancServer(orthanc); + ((DefaultTreeModel) tree_.getModel()).reload(); + } + } + }); + buttonPane.add(btnAddServer); + } + + { + buttonPane.add(removeServer_); + removeServer_.setEnabled(false); + + removeServer_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + MyTreeNode selected = (MyTreeNode) tree_.getLastSelectedPathComponent(); + if (selected.GetResourceType() == ResourceType.SERVER && + JOptionPane.showConfirmDialog(null, "Remove server \"" + selected.getUserObject() + "\"?", + "WARNING", JOptionPane.YES_NO_OPTION) == JOptionPane.YES_OPTION) + { + ((DefaultTreeModel) tree_.getModel()).removeNodeFromParent(selected); + } + } + }); + } + + { + okButton_.setEnabled(false); + okButton_.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + isSuccess_ = true; + setVisible(false); + } + }); + buttonPane.add(okButton_); + getRootPane().setDefaultButton(okButton_); + } + { + JButton cancelButton = new JButton("Cancel"); + cancelButton.addActionListener(new ActionListener() { + public void actionPerformed(ActionEvent arg) { + setVisible(false); + } + }); + buttonPane.add(cancelButton); + } + } + + setUndecorated(false); + setSize(500,500); + setTitle("Select some series or some instance in Orthanc"); + setModal(true); + } + + + public void AddOrthancServer(OrthancConnection orthanc) + { + root_.add(new MyTreeNode(orthanc, ResourceType.SERVER, "", orthanc.GetName())); + } + + public boolean ShowModal() + { + final DefaultTreeModel model = new DefaultTreeModel(root_); + root_.LoadChildren(model); + tree_.setRootVisible(false); + tree_.setShowsRootHandles(true); + tree_.setModel(model); + + isSuccess_ = false; + setVisible(true); + return isSuccess_; + } + + public String GetSelectedUuid() + { + return selectedUuid_; + } + + public boolean IsSeriesSelected() + { + return selectedType_ == ResourceType.SERIES; + } + + public boolean IsInstanceSelected() + { + return selectedType_ == ResourceType.INSTANCE; + } + + public OrthancConnection GetSelectedConnection() + { + return selectedConnection_; + } + + public void Select(OrthancConnection c, boolean isInstance, String uuid) // For test + { + selectedConnection_ = c; + selectedType_ = (isInstance ? ResourceType.INSTANCE : ResourceType.SERIES); + selectedUuid_ = uuid; + } + + public void Unserialize(String s) + { + if (s.length() == 0) + { + // Add default Orthanc server + AddOrthancServer(new OrthancConnection()); + } + else + { + String decoded = new String(DatatypeConverter.parseBase64Binary(s)); + JSONArray config = (JSONArray) JSONValue.parse(decoded); + if (config != null) + { + for (int i = 0; i < config.size(); i++) + { + AddOrthancServer(OrthancConnection.Unserialize((JSONObject) config.get(i))); + } + } + } + } + + public String Serialize() + { + JSONArray servers = new JSONArray(); + + for (int i = 0; i < root_.getChildCount(); i++) + { + MyTreeNode node = (MyTreeNode) root_.getChildAt(i); + servers.add(node.GetConnection().Serialize()); + } + + String config = servers.toJSONString(); + return DatatypeConverter.printBase64Binary(config.getBytes()); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/AUTHORS.txt Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,3 @@ +Yidong Fang +Chris Nokleberg +Dave Hughes
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/LICENSE.txt Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,202 @@ + + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "[]" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright [yyyy] [name of copyright owner] + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License.
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/README.txt Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,2 @@ +Please visit: +http://code.google.com/p/json-simple/ \ No newline at end of file
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/VERSION.txt Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,1 @@ +1.1.1
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/ItemList.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,147 @@ +/* + * $Id: ItemList.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-3-24 + */ +package org.json.simple; + +import java.util.ArrayList; +import java.util.List; +import java.util.StringTokenizer; + +/** + * |a:b:c| => |a|,|b|,|c| + * |:| => ||,|| + * |a:| => |a|,|| + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public class ItemList { + private String sp=","; + List items=new ArrayList(); + + + public ItemList(){} + + + public ItemList(String s){ + this.split(s,sp,items); + } + + public ItemList(String s,String sp){ + this.sp=s; + this.split(s,sp,items); + } + + public ItemList(String s,String sp,boolean isMultiToken){ + split(s,sp,items,isMultiToken); + } + + public List getItems(){ + return this.items; + } + + public String[] getArray(){ + return (String[])this.items.toArray(); + } + + public void split(String s,String sp,List append,boolean isMultiToken){ + if(s==null || sp==null) + return; + if(isMultiToken){ + StringTokenizer tokens=new StringTokenizer(s,sp); + while(tokens.hasMoreTokens()){ + append.add(tokens.nextToken().trim()); + } + } + else{ + this.split(s,sp,append); + } + } + + public void split(String s,String sp,List append){ + if(s==null || sp==null) + return; + int pos=0; + int prevPos=0; + do{ + prevPos=pos; + pos=s.indexOf(sp,pos); + if(pos==-1) + break; + append.add(s.substring(prevPos,pos).trim()); + pos+=sp.length(); + }while(pos!=-1); + append.add(s.substring(prevPos).trim()); + } + + public void setSP(String sp){ + this.sp=sp; + } + + public void add(int i,String item){ + if(item==null) + return; + items.add(i,item.trim()); + } + + public void add(String item){ + if(item==null) + return; + items.add(item.trim()); + } + + public void addAll(ItemList list){ + items.addAll(list.items); + } + + public void addAll(String s){ + this.split(s,sp,items); + } + + public void addAll(String s,String sp){ + this.split(s,sp,items); + } + + public void addAll(String s,String sp,boolean isMultiToken){ + this.split(s,sp,items,isMultiToken); + } + + /** + * @param i 0-based + * @return + */ + public String get(int i){ + return (String)items.get(i); + } + + public int size(){ + return items.size(); + } + + public String toString(){ + return toString(sp); + } + + public String toString(String sp){ + StringBuffer sb=new StringBuffer(); + + for(int i=0;i<items.size();i++){ + if(i==0) + sb.append(items.get(i)); + else{ + sb.append(sp); + sb.append(items.get(i)); + } + } + return sb.toString(); + + } + + public void clear(){ + items.clear(); + } + + public void reset(){ + sp=","; + items.clear(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/JSONArray.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,107 @@ +/* + * $Id: JSONArray.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-4-10 + */ +package org.json.simple; + +import java.io.IOException; +import java.io.Writer; +import java.util.ArrayList; +import java.util.Iterator; +import java.util.List; + + +/** + * A JSON array. JSONObject supports java.util.List interface. + * + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public class JSONArray extends ArrayList implements List, JSONAware, JSONStreamAware { + private static final long serialVersionUID = 3957988303675231981L; + + /** + * Encode a list into JSON text and write it to out. + * If this list is also a JSONStreamAware or a JSONAware, JSONStreamAware and JSONAware specific behaviours will be ignored at this top level. + * + * @see org.json.simple.JSONValue#writeJSONString(Object, Writer) + * + * @param list + * @param out + */ + public static void writeJSONString(List list, Writer out) throws IOException{ + if(list == null){ + out.write("null"); + return; + } + + boolean first = true; + Iterator iter=list.iterator(); + + out.write('['); + while(iter.hasNext()){ + if(first) + first = false; + else + out.write(','); + + Object value=iter.next(); + if(value == null){ + out.write("null"); + continue; + } + + JSONValue.writeJSONString(value, out); + } + out.write(']'); + } + + public void writeJSONString(Writer out) throws IOException{ + writeJSONString(this, out); + } + + /** + * Convert a list to JSON text. The result is a JSON array. + * If this list is also a JSONAware, JSONAware specific behaviours will be omitted at this top level. + * + * @see org.json.simple.JSONValue#toJSONString(Object) + * + * @param list + * @return JSON text, or "null" if list is null. + */ + public static String toJSONString(List list){ + if(list == null) + return "null"; + + boolean first = true; + StringBuffer sb = new StringBuffer(); + Iterator iter=list.iterator(); + + sb.append('['); + while(iter.hasNext()){ + if(first) + first = false; + else + sb.append(','); + + Object value=iter.next(); + if(value == null){ + sb.append("null"); + continue; + } + sb.append(JSONValue.toJSONString(value)); + } + sb.append(']'); + return sb.toString(); + } + + public String toJSONString(){ + return toJSONString(this); + } + + public String toString() { + return toJSONString(); + } + + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/JSONAware.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,12 @@ +package org.json.simple; + +/** + * Beans that support customized output of JSON text shall implement this interface. + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public interface JSONAware { + /** + * @return JSON text + */ + String toJSONString(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/JSONObject.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,146 @@ +/* + * $Id: JSONObject.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-4-10 + */ +package org.json.simple; + +import java.io.IOException; +import java.io.Writer; +import java.util.HashMap; +import java.util.Iterator; +import java.util.Map; + +/** + * A JSON object. Key value pairs are unordered. JSONObject supports java.util.Map interface. + * + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public class JSONObject extends HashMap implements Map, JSONAware, JSONStreamAware{ + + private static final long serialVersionUID = -503443796854799292L; + + + public JSONObject() { + super(); + } + + /** + * Allows creation of a JSONObject from a Map. After that, both the + * generated JSONObject and the Map can be modified independently. + * + * @param map + */ + public JSONObject(Map map) { + super(map); + } + + + /** + * Encode a map into JSON text and write it to out. + * If this map is also a JSONAware or JSONStreamAware, JSONAware or JSONStreamAware specific behaviours will be ignored at this top level. + * + * @see org.json.simple.JSONValue#writeJSONString(Object, Writer) + * + * @param map + * @param out + */ + public static void writeJSONString(Map map, Writer out) throws IOException { + if(map == null){ + out.write("null"); + return; + } + + boolean first = true; + Iterator iter=map.entrySet().iterator(); + + out.write('{'); + while(iter.hasNext()){ + if(first) + first = false; + else + out.write(','); + Map.Entry entry=(Map.Entry)iter.next(); + out.write('\"'); + out.write(escape(String.valueOf(entry.getKey()))); + out.write('\"'); + out.write(':'); + JSONValue.writeJSONString(entry.getValue(), out); + } + out.write('}'); + } + + public void writeJSONString(Writer out) throws IOException{ + writeJSONString(this, out); + } + + /** + * Convert a map to JSON text. The result is a JSON object. + * If this map is also a JSONAware, JSONAware specific behaviours will be omitted at this top level. + * + * @see org.json.simple.JSONValue#toJSONString(Object) + * + * @param map + * @return JSON text, or "null" if map is null. + */ + public static String toJSONString(Map map){ + if(map == null) + return "null"; + + StringBuffer sb = new StringBuffer(); + boolean first = true; + Iterator iter=map.entrySet().iterator(); + + sb.append('{'); + while(iter.hasNext()){ + if(first) + first = false; + else + sb.append(','); + + Map.Entry entry=(Map.Entry)iter.next(); + toJSONString(String.valueOf(entry.getKey()),entry.getValue(), sb); + } + sb.append('}'); + return sb.toString(); + } + + public String toJSONString(){ + return toJSONString(this); + } + + private static String toJSONString(String key,Object value, StringBuffer sb){ + sb.append('\"'); + if(key == null) + sb.append("null"); + else + JSONValue.escape(key, sb); + sb.append('\"').append(':'); + + sb.append(JSONValue.toJSONString(value)); + + return sb.toString(); + } + + public String toString(){ + return toJSONString(); + } + + public static String toString(String key,Object value){ + StringBuffer sb = new StringBuffer(); + toJSONString(key, value, sb); + return sb.toString(); + } + + /** + * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). + * It's the same as JSONValue.escape() only for compatibility here. + * + * @see org.json.simple.JSONValue#escape(String) + * + * @param s + * @return + */ + public static String escape(String s){ + return JSONValue.escape(s); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/JSONStreamAware.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,15 @@ +package org.json.simple; + +import java.io.IOException; +import java.io.Writer; + +/** + * Beans that support customized output of JSON text to a writer shall implement this interface. + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public interface JSONStreamAware { + /** + * write JSON string to out. + */ + void writeJSONString(Writer out) throws IOException; +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/JSONValue.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,272 @@ +/* + * $Id: JSONValue.java,v 1.1 2006/04/15 14:37:04 platform Exp $ + * Created on 2006-4-15 + */ +package org.json.simple; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.io.Writer; +import java.util.List; +import java.util.Map; + +import org.json.simple.parser.JSONParser; +import org.json.simple.parser.ParseException; + + +/** + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public class JSONValue { + /** + * Parse JSON text into java object from the input source. + * Please use parseWithException() if you don't want to ignore the exception. + * + * @see org.json.simple.parser.JSONParser#parse(Reader) + * @see #parseWithException(Reader) + * + * @param in + * @return Instance of the following: + * org.json.simple.JSONObject, + * org.json.simple.JSONArray, + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean, + * null + * + */ + public static Object parse(Reader in){ + try{ + JSONParser parser=new JSONParser(); + return parser.parse(in); + } + catch(Exception e){ + return null; + } + } + + public static Object parse(String s){ + StringReader in=new StringReader(s); + return parse(in); + } + + /** + * Parse JSON text into java object from the input source. + * + * @see org.json.simple.parser.JSONParser + * + * @param in + * @return Instance of the following: + * org.json.simple.JSONObject, + * org.json.simple.JSONArray, + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean, + * null + * + * @throws IOException + * @throws ParseException + */ + public static Object parseWithException(Reader in) throws IOException, ParseException{ + JSONParser parser=new JSONParser(); + return parser.parse(in); + } + + public static Object parseWithException(String s) throws ParseException{ + JSONParser parser=new JSONParser(); + return parser.parse(s); + } + + /** + * Encode an object into JSON text and write it to out. + * <p> + * If this object is a Map or a List, and it's also a JSONStreamAware or a JSONAware, JSONStreamAware or JSONAware will be considered firstly. + * <p> + * DO NOT call this method from writeJSONString(Writer) of a class that implements both JSONStreamAware and (Map or List) with + * "this" as the first parameter, use JSONObject.writeJSONString(Map, Writer) or JSONArray.writeJSONString(List, Writer) instead. + * + * @see org.json.simple.JSONObject#writeJSONString(Map, Writer) + * @see org.json.simple.JSONArray#writeJSONString(List, Writer) + * + * @param value + * @param writer + */ + public static void writeJSONString(Object value, Writer out) throws IOException { + if(value == null){ + out.write("null"); + return; + } + + if(value instanceof String){ + out.write('\"'); + out.write(escape((String)value)); + out.write('\"'); + return; + } + + if(value instanceof Double){ + if(((Double)value).isInfinite() || ((Double)value).isNaN()) + out.write("null"); + else + out.write(value.toString()); + return; + } + + if(value instanceof Float){ + if(((Float)value).isInfinite() || ((Float)value).isNaN()) + out.write("null"); + else + out.write(value.toString()); + return; + } + + if(value instanceof Number){ + out.write(value.toString()); + return; + } + + if(value instanceof Boolean){ + out.write(value.toString()); + return; + } + + if((value instanceof JSONStreamAware)){ + ((JSONStreamAware)value).writeJSONString(out); + return; + } + + if((value instanceof JSONAware)){ + out.write(((JSONAware)value).toJSONString()); + return; + } + + if(value instanceof Map){ + JSONObject.writeJSONString((Map)value, out); + return; + } + + if(value instanceof List){ + JSONArray.writeJSONString((List)value, out); + return; + } + + out.write(value.toString()); + } + + /** + * Convert an object to JSON text. + * <p> + * If this object is a Map or a List, and it's also a JSONAware, JSONAware will be considered firstly. + * <p> + * DO NOT call this method from toJSONString() of a class that implements both JSONAware and Map or List with + * "this" as the parameter, use JSONObject.toJSONString(Map) or JSONArray.toJSONString(List) instead. + * + * @see org.json.simple.JSONObject#toJSONString(Map) + * @see org.json.simple.JSONArray#toJSONString(List) + * + * @param value + * @return JSON text, or "null" if value is null or it's an NaN or an INF number. + */ + public static String toJSONString(Object value){ + if(value == null) + return "null"; + + if(value instanceof String) + return "\""+escape((String)value)+"\""; + + if(value instanceof Double){ + if(((Double)value).isInfinite() || ((Double)value).isNaN()) + return "null"; + else + return value.toString(); + } + + if(value instanceof Float){ + if(((Float)value).isInfinite() || ((Float)value).isNaN()) + return "null"; + else + return value.toString(); + } + + if(value instanceof Number) + return value.toString(); + + if(value instanceof Boolean) + return value.toString(); + + if((value instanceof JSONAware)) + return ((JSONAware)value).toJSONString(); + + if(value instanceof Map) + return JSONObject.toJSONString((Map)value); + + if(value instanceof List) + return JSONArray.toJSONString((List)value); + + return value.toString(); + } + + /** + * Escape quotes, \, /, \r, \n, \b, \f, \t and other control characters (U+0000 through U+001F). + * @param s + * @return + */ + public static String escape(String s){ + if(s==null) + return null; + StringBuffer sb = new StringBuffer(); + escape(s, sb); + return sb.toString(); + } + + /** + * @param s - Must not be null. + * @param sb + */ + static void escape(String s, StringBuffer sb) { + for(int i=0;i<s.length();i++){ + char ch=s.charAt(i); + switch(ch){ + case '"': + sb.append("\\\""); + break; + case '\\': + sb.append("\\\\"); + break; + case '\b': + sb.append("\\b"); + break; + case '\f': + sb.append("\\f"); + break; + case '\n': + sb.append("\\n"); + break; + case '\r': + sb.append("\\r"); + break; + case '\t': + sb.append("\\t"); + break; + case '/': + sb.append("\\/"); + break; + default: + //Reference: http://www.unicode.org/versions/Unicode5.1.0/ + if((ch>='\u0000' && ch<='\u001F') || (ch>='\u007F' && ch<='\u009F') || (ch>='\u2000' && ch<='\u20FF')){ + String ss=Integer.toHexString(ch); + sb.append("\\u"); + for(int k=0;k<4-ss.length();k++){ + sb.append('0'); + } + sb.append(ss.toUpperCase()); + } + else{ + sb.append(ch); + } + } + }//for + } + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/parser/ContainerFactory.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,23 @@ +package org.json.simple.parser; + +import java.util.List; +import java.util.Map; + +/** + * Container factory for creating containers for JSON object and JSON array. + * + * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContainerFactory) + * + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public interface ContainerFactory { + /** + * @return A Map instance to store JSON object, or null if you want to use org.json.simple.JSONObject. + */ + Map createObjectContainer(); + + /** + * @return A List instance to store JSON array, or null if you want to use org.json.simple.JSONArray. + */ + List creatArrayContainer(); +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/parser/ContentHandler.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,110 @@ +package org.json.simple.parser; + +import java.io.IOException; + +/** + * A simplified and stoppable SAX-like content handler for stream processing of JSON text. + * + * @see org.xml.sax.ContentHandler + * @see org.json.simple.parser.JSONParser#parse(java.io.Reader, ContentHandler, boolean) + * + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public interface ContentHandler { + /** + * Receive notification of the beginning of JSON processing. + * The parser will invoke this method only once. + * + * @throws ParseException + * - JSONParser will stop and throw the same exception to the caller when receiving this exception. + */ + void startJSON() throws ParseException, IOException; + + /** + * Receive notification of the end of JSON processing. + * + * @throws ParseException + */ + void endJSON() throws ParseException, IOException; + + /** + * Receive notification of the beginning of a JSON object. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * - JSONParser will stop and throw the same exception to the caller when receiving this exception. + * @see #endJSON + */ + boolean startObject() throws ParseException, IOException; + + /** + * Receive notification of the end of a JSON object. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #startObject + */ + boolean endObject() throws ParseException, IOException; + + /** + * Receive notification of the beginning of a JSON object entry. + * + * @param key - Key of a JSON object entry. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #endObjectEntry + */ + boolean startObjectEntry(String key) throws ParseException, IOException; + + /** + * Receive notification of the end of the value of previous object entry. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #startObjectEntry + */ + boolean endObjectEntry() throws ParseException, IOException; + + /** + * Receive notification of the beginning of a JSON array. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #endArray + */ + boolean startArray() throws ParseException, IOException; + + /** + * Receive notification of the end of a JSON array. + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + * + * @see #startArray + */ + boolean endArray() throws ParseException, IOException; + + /** + * Receive notification of the JSON primitive values: + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean + * null + * + * @param value - Instance of the following: + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean + * null + * + * @return false if the handler wants to stop parsing after return. + * @throws ParseException + */ + boolean primitive(Object value) throws ParseException, IOException; + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/parser/JSONParser.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,533 @@ +/* + * $Id: JSONParser.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-4-15 + */ +package org.json.simple.parser; + +import java.io.IOException; +import java.io.Reader; +import java.io.StringReader; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +import org.json.simple.JSONArray; +import org.json.simple.JSONObject; + + +/** + * Parser for JSON text. Please note that JSONParser is NOT thread-safe. + * + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public class JSONParser { + public static final int S_INIT=0; + public static final int S_IN_FINISHED_VALUE=1;//string,number,boolean,null,object,array + public static final int S_IN_OBJECT=2; + public static final int S_IN_ARRAY=3; + public static final int S_PASSED_PAIR_KEY=4; + public static final int S_IN_PAIR_VALUE=5; + public static final int S_END=6; + public static final int S_IN_ERROR=-1; + + private LinkedList handlerStatusStack; + private Yylex lexer = new Yylex((Reader)null); + private Yytoken token = null; + private int status = S_INIT; + + private int peekStatus(LinkedList statusStack){ + if(statusStack.size()==0) + return -1; + Integer status=(Integer)statusStack.getFirst(); + return status.intValue(); + } + + /** + * Reset the parser to the initial state without resetting the underlying reader. + * + */ + public void reset(){ + token = null; + status = S_INIT; + handlerStatusStack = null; + } + + /** + * Reset the parser to the initial state with a new character reader. + * + * @param in - The new character reader. + * @throws IOException + * @throws ParseException + */ + public void reset(Reader in){ + lexer.yyreset(in); + reset(); + } + + /** + * @return The position of the beginning of the current token. + */ + public int getPosition(){ + return lexer.getPosition(); + } + + public Object parse(String s) throws ParseException{ + return parse(s, (ContainerFactory)null); + } + + public Object parse(String s, ContainerFactory containerFactory) throws ParseException{ + StringReader in=new StringReader(s); + try{ + return parse(in, containerFactory); + } + catch(IOException ie){ + /* + * Actually it will never happen. + */ + throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie); + } + } + + public Object parse(Reader in) throws IOException, ParseException{ + return parse(in, (ContainerFactory)null); + } + + /** + * Parse JSON text into java object from the input source. + * + * @param in + * @param containerFactory - Use this factory to createyour own JSON object and JSON array containers. + * @return Instance of the following: + * org.json.simple.JSONObject, + * org.json.simple.JSONArray, + * java.lang.String, + * java.lang.Number, + * java.lang.Boolean, + * null + * + * @throws IOException + * @throws ParseException + */ + public Object parse(Reader in, ContainerFactory containerFactory) throws IOException, ParseException{ + reset(in); + LinkedList statusStack = new LinkedList(); + LinkedList valueStack = new LinkedList(); + + try{ + do{ + nextToken(); + switch(status){ + case S_INIT: + switch(token.type){ + case Yytoken.TYPE_VALUE: + status=S_IN_FINISHED_VALUE; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(token.value); + break; + case Yytoken.TYPE_LEFT_BRACE: + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(createObjectContainer(containerFactory)); + break; + case Yytoken.TYPE_LEFT_SQUARE: + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(createArrayContainer(containerFactory)); + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + + case S_IN_FINISHED_VALUE: + if(token.type==Yytoken.TYPE_EOF) + return valueStack.removeFirst(); + else + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + + case S_IN_OBJECT: + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + if(token.value instanceof String){ + String key=(String)token.value; + valueStack.addFirst(key); + status=S_PASSED_PAIR_KEY; + statusStack.addFirst(new Integer(status)); + } + else{ + status=S_IN_ERROR; + } + break; + case Yytoken.TYPE_RIGHT_BRACE: + if(valueStack.size()>1){ + statusStack.removeFirst(); + valueStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + break; + default: + status=S_IN_ERROR; + break; + }//inner switch + break; + + case S_PASSED_PAIR_KEY: + switch(token.type){ + case Yytoken.TYPE_COLON: + break; + case Yytoken.TYPE_VALUE: + statusStack.removeFirst(); + String key=(String)valueStack.removeFirst(); + Map parent=(Map)valueStack.getFirst(); + parent.put(key,token.value); + status=peekStatus(statusStack); + break; + case Yytoken.TYPE_LEFT_SQUARE: + statusStack.removeFirst(); + key=(String)valueStack.removeFirst(); + parent=(Map)valueStack.getFirst(); + List newArray=createArrayContainer(containerFactory); + parent.put(key,newArray); + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newArray); + break; + case Yytoken.TYPE_LEFT_BRACE: + statusStack.removeFirst(); + key=(String)valueStack.removeFirst(); + parent=(Map)valueStack.getFirst(); + Map newObject=createObjectContainer(containerFactory); + parent.put(key,newObject); + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newObject); + break; + default: + status=S_IN_ERROR; + } + break; + + case S_IN_ARRAY: + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + List val=(List)valueStack.getFirst(); + val.add(token.value); + break; + case Yytoken.TYPE_RIGHT_SQUARE: + if(valueStack.size()>1){ + statusStack.removeFirst(); + valueStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + break; + case Yytoken.TYPE_LEFT_BRACE: + val=(List)valueStack.getFirst(); + Map newObject=createObjectContainer(containerFactory); + val.add(newObject); + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newObject); + break; + case Yytoken.TYPE_LEFT_SQUARE: + val=(List)valueStack.getFirst(); + List newArray=createArrayContainer(containerFactory); + val.add(newArray); + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + valueStack.addFirst(newArray); + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + case S_IN_ERROR: + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + }//switch + if(status==S_IN_ERROR){ + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + }while(token.type!=Yytoken.TYPE_EOF); + } + catch(IOException ie){ + throw ie; + } + + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + + private void nextToken() throws ParseException, IOException{ + token = lexer.yylex(); + if(token == null) + token = new Yytoken(Yytoken.TYPE_EOF, null); + } + + private Map createObjectContainer(ContainerFactory containerFactory){ + if(containerFactory == null) + return new JSONObject(); + Map m = containerFactory.createObjectContainer(); + + if(m == null) + return new JSONObject(); + return m; + } + + private List createArrayContainer(ContainerFactory containerFactory){ + if(containerFactory == null) + return new JSONArray(); + List l = containerFactory.creatArrayContainer(); + + if(l == null) + return new JSONArray(); + return l; + } + + public void parse(String s, ContentHandler contentHandler) throws ParseException{ + parse(s, contentHandler, false); + } + + public void parse(String s, ContentHandler contentHandler, boolean isResume) throws ParseException{ + StringReader in=new StringReader(s); + try{ + parse(in, contentHandler, isResume); + } + catch(IOException ie){ + /* + * Actually it will never happen. + */ + throw new ParseException(-1, ParseException.ERROR_UNEXPECTED_EXCEPTION, ie); + } + } + + public void parse(Reader in, ContentHandler contentHandler) throws IOException, ParseException{ + parse(in, contentHandler, false); + } + + /** + * Stream processing of JSON text. + * + * @see ContentHandler + * + * @param in + * @param contentHandler + * @param isResume - Indicates if it continues previous parsing operation. + * If set to true, resume parsing the old stream, and parameter 'in' will be ignored. + * If this method is called for the first time in this instance, isResume will be ignored. + * + * @throws IOException + * @throws ParseException + */ + public void parse(Reader in, ContentHandler contentHandler, boolean isResume) throws IOException, ParseException{ + if(!isResume){ + reset(in); + handlerStatusStack = new LinkedList(); + } + else{ + if(handlerStatusStack == null){ + isResume = false; + reset(in); + handlerStatusStack = new LinkedList(); + } + } + + LinkedList statusStack = handlerStatusStack; + + try{ + do{ + switch(status){ + case S_INIT: + contentHandler.startJSON(); + nextToken(); + switch(token.type){ + case Yytoken.TYPE_VALUE: + status=S_IN_FINISHED_VALUE; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.primitive(token.value)) + return; + break; + case Yytoken.TYPE_LEFT_BRACE: + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObject()) + return; + break; + case Yytoken.TYPE_LEFT_SQUARE: + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startArray()) + return; + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + + case S_IN_FINISHED_VALUE: + nextToken(); + if(token.type==Yytoken.TYPE_EOF){ + contentHandler.endJSON(); + status = S_END; + return; + } + else{ + status = S_IN_ERROR; + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + + case S_IN_OBJECT: + nextToken(); + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + if(token.value instanceof String){ + String key=(String)token.value; + status=S_PASSED_PAIR_KEY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObjectEntry(key)) + return; + } + else{ + status=S_IN_ERROR; + } + break; + case Yytoken.TYPE_RIGHT_BRACE: + if(statusStack.size()>1){ + statusStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + if(!contentHandler.endObject()) + return; + break; + default: + status=S_IN_ERROR; + break; + }//inner switch + break; + + case S_PASSED_PAIR_KEY: + nextToken(); + switch(token.type){ + case Yytoken.TYPE_COLON: + break; + case Yytoken.TYPE_VALUE: + statusStack.removeFirst(); + status=peekStatus(statusStack); + if(!contentHandler.primitive(token.value)) + return; + if(!contentHandler.endObjectEntry()) + return; + break; + case Yytoken.TYPE_LEFT_SQUARE: + statusStack.removeFirst(); + statusStack.addFirst(new Integer(S_IN_PAIR_VALUE)); + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startArray()) + return; + break; + case Yytoken.TYPE_LEFT_BRACE: + statusStack.removeFirst(); + statusStack.addFirst(new Integer(S_IN_PAIR_VALUE)); + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObject()) + return; + break; + default: + status=S_IN_ERROR; + } + break; + + case S_IN_PAIR_VALUE: + /* + * S_IN_PAIR_VALUE is just a marker to indicate the end of an object entry, it doesn't proccess any token, + * therefore delay consuming token until next round. + */ + statusStack.removeFirst(); + status = peekStatus(statusStack); + if(!contentHandler.endObjectEntry()) + return; + break; + + case S_IN_ARRAY: + nextToken(); + switch(token.type){ + case Yytoken.TYPE_COMMA: + break; + case Yytoken.TYPE_VALUE: + if(!contentHandler.primitive(token.value)) + return; + break; + case Yytoken.TYPE_RIGHT_SQUARE: + if(statusStack.size()>1){ + statusStack.removeFirst(); + status=peekStatus(statusStack); + } + else{ + status=S_IN_FINISHED_VALUE; + } + if(!contentHandler.endArray()) + return; + break; + case Yytoken.TYPE_LEFT_BRACE: + status=S_IN_OBJECT; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startObject()) + return; + break; + case Yytoken.TYPE_LEFT_SQUARE: + status=S_IN_ARRAY; + statusStack.addFirst(new Integer(status)); + if(!contentHandler.startArray()) + return; + break; + default: + status=S_IN_ERROR; + }//inner switch + break; + + case S_END: + return; + + case S_IN_ERROR: + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + }//switch + if(status==S_IN_ERROR){ + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } + }while(token.type!=Yytoken.TYPE_EOF); + } + catch(IOException ie){ + status = S_IN_ERROR; + throw ie; + } + catch(ParseException pe){ + status = S_IN_ERROR; + throw pe; + } + catch(RuntimeException re){ + status = S_IN_ERROR; + throw re; + } + catch(Error e){ + status = S_IN_ERROR; + throw e; + } + + status = S_IN_ERROR; + throw new ParseException(getPosition(), ParseException.ERROR_UNEXPECTED_TOKEN, token); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/parser/ParseException.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,90 @@ +package org.json.simple.parser; + +/** + * ParseException explains why and where the error occurs in source JSON text. + * + * @author FangYidong<fangyidong@yahoo.com.cn> + * + */ +public class ParseException extends Exception { + private static final long serialVersionUID = -7880698968187728548L; + + public static final int ERROR_UNEXPECTED_CHAR = 0; + public static final int ERROR_UNEXPECTED_TOKEN = 1; + public static final int ERROR_UNEXPECTED_EXCEPTION = 2; + + private int errorType; + private Object unexpectedObject; + private int position; + + public ParseException(int errorType){ + this(-1, errorType, null); + } + + public ParseException(int errorType, Object unexpectedObject){ + this(-1, errorType, unexpectedObject); + } + + public ParseException(int position, int errorType, Object unexpectedObject){ + this.position = position; + this.errorType = errorType; + this.unexpectedObject = unexpectedObject; + } + + public int getErrorType() { + return errorType; + } + + public void setErrorType(int errorType) { + this.errorType = errorType; + } + + /** + * @see org.json.simple.parser.JSONParser#getPosition() + * + * @return The character position (starting with 0) of the input where the error occurs. + */ + public int getPosition() { + return position; + } + + public void setPosition(int position) { + this.position = position; + } + + /** + * @see org.json.simple.parser.Yytoken + * + * @return One of the following base on the value of errorType: + * ERROR_UNEXPECTED_CHAR java.lang.Character + * ERROR_UNEXPECTED_TOKEN org.json.simple.parser.Yytoken + * ERROR_UNEXPECTED_EXCEPTION java.lang.Exception + */ + public Object getUnexpectedObject() { + return unexpectedObject; + } + + public void setUnexpectedObject(Object unexpectedObject) { + this.unexpectedObject = unexpectedObject; + } + + public String toString(){ + StringBuffer sb = new StringBuffer(); + + switch(errorType){ + case ERROR_UNEXPECTED_CHAR: + sb.append("Unexpected character (").append(unexpectedObject).append(") at position ").append(position).append("."); + break; + case ERROR_UNEXPECTED_TOKEN: + sb.append("Unexpected token ").append(unexpectedObject).append(" at position ").append(position).append("."); + break; + case ERROR_UNEXPECTED_EXCEPTION: + sb.append("Unexpected exception at position ").append(position).append(": ").append(unexpectedObject); + break; + default: + sb.append("Unkown error at position ").append(position).append("."); + break; + } + return sb.toString(); + } +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/parser/Yylex.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,688 @@ +/* The following code was generated by JFlex 1.4.2 */ + +package org.json.simple.parser; + +class Yylex { + + /** This character denotes the end of file */ + public static final int YYEOF = -1; + + /** initial size of the lookahead buffer */ + private static final int ZZ_BUFFERSIZE = 16384; + + /** lexical states */ + public static final int YYINITIAL = 0; + public static final int STRING_BEGIN = 2; + + /** + * ZZ_LEXSTATE[l] is the state in the DFA for the lexical state l + * ZZ_LEXSTATE[l+1] is the state in the DFA for the lexical state l + * at the beginning of a line + * l is of the form l = 2*k, k a non negative integer + */ + private static final int ZZ_LEXSTATE[] = { + 0, 0, 1, 1 + }; + + /** + * Translates characters to character classes + */ + private static final String ZZ_CMAP_PACKED = + "\11\0\1\7\1\7\2\0\1\7\22\0\1\7\1\0\1\11\10\0"+ + "\1\6\1\31\1\2\1\4\1\12\12\3\1\32\6\0\4\1\1\5"+ + "\1\1\24\0\1\27\1\10\1\30\3\0\1\22\1\13\2\1\1\21"+ + "\1\14\5\0\1\23\1\0\1\15\3\0\1\16\1\24\1\17\1\20"+ + "\5\0\1\25\1\0\1\26\uff82\0"; + + /** + * Translates characters to character classes + */ + private static final char [] ZZ_CMAP = zzUnpackCMap(ZZ_CMAP_PACKED); + + /** + * Translates DFA states to action switch labels. + */ + private static final int [] ZZ_ACTION = zzUnpackAction(); + + private static final String ZZ_ACTION_PACKED_0 = + "\2\0\2\1\1\2\1\3\1\4\3\1\1\5\1\6"+ + "\1\7\1\10\1\11\1\12\1\13\1\14\1\15\5\0"+ + "\1\14\1\16\1\17\1\20\1\21\1\22\1\23\1\24"+ + "\1\0\1\25\1\0\1\25\4\0\1\26\1\27\2\0"+ + "\1\30"; + + private static int [] zzUnpackAction() { + int [] result = new int[45]; + int offset = 0; + offset = zzUnpackAction(ZZ_ACTION_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAction(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + + /** + * Translates a state to a row index in the transition table + */ + private static final int [] ZZ_ROWMAP = zzUnpackRowMap(); + + private static final String ZZ_ROWMAP_PACKED_0 = + "\0\0\0\33\0\66\0\121\0\154\0\207\0\66\0\242"+ + "\0\275\0\330\0\66\0\66\0\66\0\66\0\66\0\66"+ + "\0\363\0\u010e\0\66\0\u0129\0\u0144\0\u015f\0\u017a\0\u0195"+ + "\0\66\0\66\0\66\0\66\0\66\0\66\0\66\0\66"+ + "\0\u01b0\0\u01cb\0\u01e6\0\u01e6\0\u0201\0\u021c\0\u0237\0\u0252"+ + "\0\66\0\66\0\u026d\0\u0288\0\66"; + + private static int [] zzUnpackRowMap() { + int [] result = new int[45]; + int offset = 0; + offset = zzUnpackRowMap(ZZ_ROWMAP_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackRowMap(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int high = packed.charAt(i++) << 16; + result[j++] = high | packed.charAt(i++); + } + return j; + } + + /** + * The transition table of the DFA + */ + private static final int ZZ_TRANS [] = { + 2, 2, 3, 4, 2, 2, 2, 5, 2, 6, + 2, 2, 7, 8, 2, 9, 2, 2, 2, 2, + 2, 10, 11, 12, 13, 14, 15, 16, 16, 16, + 16, 16, 16, 16, 16, 17, 18, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 4, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 4, 19, 20, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 20, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 5, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 21, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 22, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 23, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 16, 16, 16, 16, 16, 16, 16, + 16, -1, -1, 16, 16, 16, 16, 16, 16, 16, + 16, 16, 16, 16, 16, 16, 16, 16, 16, 16, + -1, -1, -1, -1, -1, -1, -1, -1, 24, 25, + 26, 27, 28, 29, 30, 31, 32, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 33, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 34, 35, -1, -1, + 34, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + 36, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, 37, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, 38, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 39, -1, 39, -1, 39, -1, -1, + -1, -1, -1, 39, 39, -1, -1, -1, -1, 39, + 39, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 33, -1, 20, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, 20, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 35, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 38, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 40, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, -1, 41, -1, -1, -1, -1, -1, + -1, -1, -1, -1, -1, 42, -1, 42, -1, 42, + -1, -1, -1, -1, -1, 42, 42, -1, -1, -1, + -1, 42, 42, -1, -1, -1, -1, -1, -1, -1, + -1, -1, 43, -1, 43, -1, 43, -1, -1, -1, + -1, -1, 43, 43, -1, -1, -1, -1, 43, 43, + -1, -1, -1, -1, -1, -1, -1, -1, -1, 44, + -1, 44, -1, 44, -1, -1, -1, -1, -1, 44, + 44, -1, -1, -1, -1, 44, 44, -1, -1, -1, + -1, -1, -1, -1, -1, + }; + + /* error codes */ + private static final int ZZ_UNKNOWN_ERROR = 0; + private static final int ZZ_NO_MATCH = 1; + private static final int ZZ_PUSHBACK_2BIG = 2; + + /* error messages for the codes above */ + private static final String ZZ_ERROR_MSG[] = { + "Unkown internal scanner error", + "Error: could not match input", + "Error: pushback value was too large" + }; + + /** + * ZZ_ATTRIBUTE[aState] contains the attributes of state <code>aState</code> + */ + private static final int [] ZZ_ATTRIBUTE = zzUnpackAttribute(); + + private static final String ZZ_ATTRIBUTE_PACKED_0 = + "\2\0\1\11\3\1\1\11\3\1\6\11\2\1\1\11"+ + "\5\0\10\11\1\0\1\1\1\0\1\1\4\0\2\11"+ + "\2\0\1\11"; + + private static int [] zzUnpackAttribute() { + int [] result = new int[45]; + int offset = 0; + offset = zzUnpackAttribute(ZZ_ATTRIBUTE_PACKED_0, offset, result); + return result; + } + + private static int zzUnpackAttribute(String packed, int offset, int [] result) { + int i = 0; /* index in packed string */ + int j = offset; /* index in unpacked array */ + int l = packed.length(); + while (i < l) { + int count = packed.charAt(i++); + int value = packed.charAt(i++); + do result[j++] = value; while (--count > 0); + } + return j; + } + + /** the input device */ + private java.io.Reader zzReader; + + /** the current state of the DFA */ + private int zzState; + + /** the current lexical state */ + private int zzLexicalState = YYINITIAL; + + /** this buffer contains the current text to be matched and is + the source of the yytext() string */ + private char zzBuffer[] = new char[ZZ_BUFFERSIZE]; + + /** the textposition at the last accepting state */ + private int zzMarkedPos; + + /** the current text position in the buffer */ + private int zzCurrentPos; + + /** startRead marks the beginning of the yytext() string in the buffer */ + private int zzStartRead; + + /** endRead marks the last character in the buffer, that has been read + from input */ + private int zzEndRead; + + /** number of newlines encountered up to the start of the matched text */ + private int yyline; + + /** the number of characters up to the start of the matched text */ + private int yychar; + + /** + * the number of characters from the last newline up to the start of the + * matched text + */ + private int yycolumn; + + /** + * zzAtBOL == true <=> the scanner is currently at the beginning of a line + */ + private boolean zzAtBOL = true; + + /** zzAtEOF == true <=> the scanner is at the EOF */ + private boolean zzAtEOF; + + /* user code: */ +private StringBuffer sb=new StringBuffer(); + +int getPosition(){ + return yychar; +} + + + + /** + * Creates a new scanner + * There is also a java.io.InputStream version of this constructor. + * + * @param in the java.io.Reader to read input from. + */ + Yylex(java.io.Reader in) { + this.zzReader = in; + } + + /** + * Creates a new scanner. + * There is also java.io.Reader version of this constructor. + * + * @param in the java.io.Inputstream to read input from. + */ + Yylex(java.io.InputStream in) { + this(new java.io.InputStreamReader(in)); + } + + /** + * Unpacks the compressed character translation table. + * + * @param packed the packed character translation table + * @return the unpacked character translation table + */ + private static char [] zzUnpackCMap(String packed) { + char [] map = new char[0x10000]; + int i = 0; /* index in packed string */ + int j = 0; /* index in unpacked array */ + while (i < 90) { + int count = packed.charAt(i++); + char value = packed.charAt(i++); + do map[j++] = value; while (--count > 0); + } + return map; + } + + + /** + * Refills the input buffer. + * + * @return <code>false</code>, iff there was new input. + * + * @exception java.io.IOException if any I/O-Error occurs + */ + private boolean zzRefill() throws java.io.IOException { + + /* first: make room (if you can) */ + if (zzStartRead > 0) { + System.arraycopy(zzBuffer, zzStartRead, + zzBuffer, 0, + zzEndRead-zzStartRead); + + /* translate stored positions */ + zzEndRead-= zzStartRead; + zzCurrentPos-= zzStartRead; + zzMarkedPos-= zzStartRead; + zzStartRead = 0; + } + + /* is the buffer big enough? */ + if (zzCurrentPos >= zzBuffer.length) { + /* if not: blow it up */ + char newBuffer[] = new char[zzCurrentPos*2]; + System.arraycopy(zzBuffer, 0, newBuffer, 0, zzBuffer.length); + zzBuffer = newBuffer; + } + + /* finally: fill the buffer with new input */ + int numRead = zzReader.read(zzBuffer, zzEndRead, + zzBuffer.length-zzEndRead); + + if (numRead > 0) { + zzEndRead+= numRead; + return false; + } + // unlikely but not impossible: read 0 characters, but not at end of stream + if (numRead == 0) { + int c = zzReader.read(); + if (c == -1) { + return true; + } else { + zzBuffer[zzEndRead++] = (char) c; + return false; + } + } + + // numRead < 0 + return true; + } + + + /** + * Closes the input stream. + */ + public final void yyclose() throws java.io.IOException { + zzAtEOF = true; /* indicate end of file */ + zzEndRead = zzStartRead; /* invalidate buffer */ + + if (zzReader != null) + zzReader.close(); + } + + + /** + * Resets the scanner to read from a new input stream. + * Does not close the old reader. + * + * All internal variables are reset, the old input stream + * <b>cannot</b> be reused (internal buffer is discarded and lost). + * Lexical state is set to <tt>ZZ_INITIAL</tt>. + * + * @param reader the new input stream + */ + public final void yyreset(java.io.Reader reader) { + zzReader = reader; + zzAtBOL = true; + zzAtEOF = false; + zzEndRead = zzStartRead = 0; + zzCurrentPos = zzMarkedPos = 0; + yyline = yychar = yycolumn = 0; + zzLexicalState = YYINITIAL; + } + + + /** + * Returns the current lexical state. + */ + public final int yystate() { + return zzLexicalState; + } + + + /** + * Enters a new lexical state + * + * @param newState the new lexical state + */ + public final void yybegin(int newState) { + zzLexicalState = newState; + } + + + /** + * Returns the text matched by the current regular expression. + */ + public final String yytext() { + return new String( zzBuffer, zzStartRead, zzMarkedPos-zzStartRead ); + } + + + /** + * Returns the character at position <tt>pos</tt> from the + * matched text. + * + * It is equivalent to yytext().charAt(pos), but faster + * + * @param pos the position of the character to fetch. + * A value from 0 to yylength()-1. + * + * @return the character at position pos + */ + public final char yycharat(int pos) { + return zzBuffer[zzStartRead+pos]; + } + + + /** + * Returns the length of the matched text region. + */ + public final int yylength() { + return zzMarkedPos-zzStartRead; + } + + + /** + * Reports an error that occured while scanning. + * + * In a wellformed scanner (no or only correct usage of + * yypushback(int) and a match-all fallback rule) this method + * will only be called with things that "Can't Possibly Happen". + * If this method is called, something is seriously wrong + * (e.g. a JFlex bug producing a faulty scanner etc.). + * + * Usual syntax/scanner level error handling should be done + * in error fallback rules. + * + * @param errorCode the code of the errormessage to display + */ + private void zzScanError(int errorCode) { + String message; + try { + message = ZZ_ERROR_MSG[errorCode]; + } + catch (ArrayIndexOutOfBoundsException e) { + message = ZZ_ERROR_MSG[ZZ_UNKNOWN_ERROR]; + } + + throw new Error(message); + } + + + /** + * Pushes the specified amount of characters back into the input stream. + * + * They will be read again by then next call of the scanning method + * + * @param number the number of characters to be read again. + * This number must not be greater than yylength()! + */ + public void yypushback(int number) { + if ( number > yylength() ) + zzScanError(ZZ_PUSHBACK_2BIG); + + zzMarkedPos -= number; + } + + + /** + * Resumes scanning until the next regular expression is matched, + * the end of input is encountered or an I/O-Error occurs. + * + * @return the next token + * @exception java.io.IOException if any I/O-Error occurs + */ + public Yytoken yylex() throws java.io.IOException, ParseException { + int zzInput; + int zzAction; + + // cached fields: + int zzCurrentPosL; + int zzMarkedPosL; + int zzEndReadL = zzEndRead; + char [] zzBufferL = zzBuffer; + char [] zzCMapL = ZZ_CMAP; + + int [] zzTransL = ZZ_TRANS; + int [] zzRowMapL = ZZ_ROWMAP; + int [] zzAttrL = ZZ_ATTRIBUTE; + + while (true) { + zzMarkedPosL = zzMarkedPos; + + yychar+= zzMarkedPosL-zzStartRead; + + zzAction = -1; + + zzCurrentPosL = zzCurrentPos = zzStartRead = zzMarkedPosL; + + zzState = ZZ_LEXSTATE[zzLexicalState]; + + + zzForAction: { + while (true) { + + if (zzCurrentPosL < zzEndReadL) + zzInput = zzBufferL[zzCurrentPosL++]; + else if (zzAtEOF) { + zzInput = YYEOF; + break zzForAction; + } + else { + // store back cached positions + zzCurrentPos = zzCurrentPosL; + zzMarkedPos = zzMarkedPosL; + boolean eof = zzRefill(); + // get translated positions and possibly new buffer + zzCurrentPosL = zzCurrentPos; + zzMarkedPosL = zzMarkedPos; + zzBufferL = zzBuffer; + zzEndReadL = zzEndRead; + if (eof) { + zzInput = YYEOF; + break zzForAction; + } + else { + zzInput = zzBufferL[zzCurrentPosL++]; + } + } + int zzNext = zzTransL[ zzRowMapL[zzState] + zzCMapL[zzInput] ]; + if (zzNext == -1) break zzForAction; + zzState = zzNext; + + int zzAttributes = zzAttrL[zzState]; + if ( (zzAttributes & 1) == 1 ) { + zzAction = zzState; + zzMarkedPosL = zzCurrentPosL; + if ( (zzAttributes & 8) == 8 ) break zzForAction; + } + + } + } + + // store back cached position + zzMarkedPos = zzMarkedPosL; + + switch (zzAction < 0 ? zzAction : ZZ_ACTION[zzAction]) { + case 11: + { sb.append(yytext()); + } + case 25: break; + case 4: + { sb.delete(0, sb.length());yybegin(STRING_BEGIN); + } + case 26: break; + case 16: + { sb.append('\b'); + } + case 27: break; + case 6: + { return new Yytoken(Yytoken.TYPE_RIGHT_BRACE,null); + } + case 28: break; + case 23: + { Boolean val=Boolean.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); + } + case 29: break; + case 22: + { return new Yytoken(Yytoken.TYPE_VALUE, null); + } + case 30: break; + case 13: + { yybegin(YYINITIAL);return new Yytoken(Yytoken.TYPE_VALUE, sb.toString()); + } + case 31: break; + case 12: + { sb.append('\\'); + } + case 32: break; + case 21: + { Double val=Double.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); + } + case 33: break; + case 1: + { throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_CHAR, new Character(yycharat(0))); + } + case 34: break; + case 8: + { return new Yytoken(Yytoken.TYPE_RIGHT_SQUARE,null); + } + case 35: break; + case 19: + { sb.append('\r'); + } + case 36: break; + case 15: + { sb.append('/'); + } + case 37: break; + case 10: + { return new Yytoken(Yytoken.TYPE_COLON,null); + } + case 38: break; + case 14: + { sb.append('"'); + } + case 39: break; + case 5: + { return new Yytoken(Yytoken.TYPE_LEFT_BRACE,null); + } + case 40: break; + case 17: + { sb.append('\f'); + } + case 41: break; + case 24: + { try{ + int ch=Integer.parseInt(yytext().substring(2),16); + sb.append((char)ch); + } + catch(Exception e){ + throw new ParseException(yychar, ParseException.ERROR_UNEXPECTED_EXCEPTION, e); + } + } + case 42: break; + case 20: + { sb.append('\t'); + } + case 43: break; + case 7: + { return new Yytoken(Yytoken.TYPE_LEFT_SQUARE,null); + } + case 44: break; + case 2: + { Long val=Long.valueOf(yytext()); return new Yytoken(Yytoken.TYPE_VALUE, val); + } + case 45: break; + case 18: + { sb.append('\n'); + } + case 46: break; + case 9: + { return new Yytoken(Yytoken.TYPE_COMMA,null); + } + case 47: break; + case 3: + { + } + case 48: break; + default: + if (zzInput == YYEOF && zzStartRead == zzCurrentPos) { + zzAtEOF = true; + return null; + } + else { + zzScanError(ZZ_NO_MATCH); + } + } + } + } + + +}
--- /dev/null Thu Jan 01 00:00:00 1970 +0000 +++ b/org/json/simple/parser/Yytoken.java Mon Dec 08 16:04:48 2014 +0100 @@ -0,0 +1,58 @@ +/* + * $Id: Yytoken.java,v 1.1 2006/04/15 14:10:48 platform Exp $ + * Created on 2006-4-15 + */ +package org.json.simple.parser; + +/** + * @author FangYidong<fangyidong@yahoo.com.cn> + */ +public class Yytoken { + public static final int TYPE_VALUE=0;//JSON primitive value: string,number,boolean,null + public static final int TYPE_LEFT_BRACE=1; + public static final int TYPE_RIGHT_BRACE=2; + public static final int TYPE_LEFT_SQUARE=3; + public static final int TYPE_RIGHT_SQUARE=4; + public static final int TYPE_COMMA=5; + public static final int TYPE_COLON=6; + public static final int TYPE_EOF=-1;//end of file + + public int type=0; + public Object value=null; + + public Yytoken(int type,Object value){ + this.type=type; + this.value=value; + } + + public String toString(){ + StringBuffer sb = new StringBuffer(); + switch(type){ + case TYPE_VALUE: + sb.append("VALUE(").append(value).append(")"); + break; + case TYPE_LEFT_BRACE: + sb.append("LEFT BRACE({)"); + break; + case TYPE_RIGHT_BRACE: + sb.append("RIGHT BRACE(})"); + break; + case TYPE_LEFT_SQUARE: + sb.append("LEFT SQUARE([)"); + break; + case TYPE_RIGHT_SQUARE: + sb.append("RIGHT SQUARE(])"); + break; + case TYPE_COMMA: + sb.append("COMMA(,)"); + break; + case TYPE_COLON: + sb.append("COLON(:)"); + break; + case TYPE_EOF: + sb.append("END OF FILE"); + break; + } + return sb.toString(); + } +}