changeset 0:d5f459244111

initial commit
author Sebastien Jodogne <s.jodogne@gmail.com>
date Fri, 13 Mar 2015 16:06:05 +0100
parents
children 174f4b0ec527
files AUTHORS CMakeLists.txt COPYING Core/ChunkedBuffer.cpp Core/ChunkedBuffer.h Core/Configuration.cpp Core/Configuration.h Core/Dicom.cpp Core/Dicom.h Core/MultipartWriter.cpp Core/MultipartWriter.h Core/Toolbox.cpp Core/Toolbox.h NEWS Plugin/Plugin.cpp Plugin/Plugin.h Plugin/QidoRs.cpp Plugin/QidoRs.h Plugin/StowRs.cpp Plugin/StowRs.h Plugin/WadoRs.cpp Plugin/WadoRs.h README Resources/BuildInstructions.txt Resources/CMake/BoostConfiguration.cmake Resources/CMake/DownloadPackage.cmake Resources/CMake/GdcmConfiguration.cmake Resources/CMake/GoogleTestConfiguration.cmake Resources/CMake/JsonCppConfiguration.cmake Resources/CMake/PugixmlConfiguration.cmake Resources/MinGWToolchain.cmake Resources/VersionScript.map Samples/SendStow.py Samples/WadoRetrieveStudy.py UnitTestsSources/UnitTestsMain.cpp
diffstat 35 files changed, 4484 insertions(+), 0 deletions(-) [+]
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/AUTHORS	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,13 @@
+DICOM Web plugin for Orthanc
+============================
+
+
+Authors
+-------
+
+* Sebastien Jodogne <s.jodogne@gmail.com>
+  Department of Medical Physics
+  University Hospital of Liege
+  Belgium
+
+  Overall design and lead developer.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/CMakeLists.txt	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,137 @@
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+cmake_minimum_required(VERSION 2.8)
+
+project(OrthancPostgreSQL)
+
+set(ORTHANC_DICOM_WEB_VERSION "1.0")
+
+
+# Parameters of the build
+set(STATIC_BUILD OFF CACHE BOOL "Static build of the third-party libraries (necessary for Windows)")
+set(ALLOW_DOWNLOADS OFF CACHE BOOL "Allow CMake to download packages")
+
+# Advanced parameters to fine-tune linking against system libraries
+set(USE_SYSTEM_BOOST ON CACHE BOOL "Use the system version of Boost")
+set(USE_SYSTEM_GDCM ON CACHE BOOL "Use the system version of Grassroot DICOM (GDCM)")
+set(USE_SYSTEM_GOOGLE_TEST ON CACHE BOOL "Use the system version of Google Test")
+set(USE_SYSTEM_JSONCPP ON CACHE BOOL "Use the system version of JsonCpp")
+SET(USE_SYSTEM_PUGIXML ON CACHE BOOL "Use the system version of Pugixml)")
+
+# Distribution-specific settings
+set(USE_GTEST_DEBIAN_SOURCE_PACKAGE OFF CACHE BOOL "Use the sources of Google Test shipped with libgtest-dev (Debian only)")
+mark_as_advanced(USE_GTEST_DEBIAN_SOURCE_PACKAGE)
+
+# Force static build when cross-compiling
+if (CMAKE_CROSSCOMPILING)
+  set(STATIC_BUILD ON)
+  set(STANDALONE_BUILD ON)
+endif()
+
+if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
+  SET(OS_LIBRARIES uuid rt dl)
+  SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -pthread")
+  SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -pthread")
+elseif (${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
+  SET(OS_LIBRARIES rpcrt4 ws2_32 secur32)
+  if (CMAKE_COMPILER_IS_GNUCXX)
+    SET(CMAKE_EXE_LINKER_FLAGS "${CMAKE_EXE_LINKER_FLAGS} -static-libgcc -static-libstdc++")
+    SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -static-libgcc -static-libstdc++")
+  endif()
+endif ()
+
+if (CMAKE_COMPILER_IS_GNUCXX)
+  SET(CMAKE_SHARED_LINKER_FLAGS "${CMAKE_SHARED_LINKER_FLAGS} -Wl,--version-script=${CMAKE_SOURCE_DIR}/Resources/VersionScript.map -Wl,--no-undefined")
+endif()
+
+
+include(CheckIncludeFiles)
+include(CheckIncludeFileCXX)
+include(CheckLibraryExists)
+include(${CMAKE_SOURCE_DIR}/Resources/CMake/DownloadPackage.cmake)
+
+include(${CMAKE_SOURCE_DIR}/Resources/CMake/BoostConfiguration.cmake)
+include(${CMAKE_SOURCE_DIR}/Resources/CMake/GdcmConfiguration.cmake)
+include(${CMAKE_SOURCE_DIR}/Resources/CMake/GoogleTestConfiguration.cmake)
+include(${CMAKE_SOURCE_DIR}/Resources/CMake/JsonCppConfiguration.cmake)
+include(${CMAKE_SOURCE_DIR}/Resources/CMake/PugixmlConfiguration.cmake)
+
+
+# Check that the Orthanc SDK headers are available or download them
+set(AUTOGENERATED_DIR ${CMAKE_CURRENT_BINARY_DIR}/AUTOGENERATED)
+if (STATIC_BUILD)
+  set(ORTHANC_SDK_URL "http://orthanc.googlecode.com/hg-history/Orthanc-0.8.6")
+  file(MAKE_DIRECTORY ${AUTOGENERATED_DIR}/orthanc)
+  file(DOWNLOAD "${ORTHANC_SDK_URL}/Plugins/Include/OrthancCPlugin.h"
+    "${AUTOGENERATED_DIR}/orthanc/OrthancCPlugin.h" SHOW_PROGRESS)
+  if (${MSVC})
+    add_definitions(-D_CRT_SECURE_NO_WARNINGS=1)
+    file(DOWNLOAD "${ORTHANC_SDK_URL}/Resources/ThirdParty/VisualStudio/stdint.h" 
+      "${AUTOGENERATED_DIR}/stdint.h" SHOW_PROGRESS)
+  endif()
+  include_directories(${AUTOGENERATED_DIR})
+else ()
+  CHECK_INCLUDE_FILE_CXX(orthanc/OrthancCPlugin.h HAVE_ORTHANC_H)
+  if (NOT HAVE_ORTHANC_H)
+    message(FATAL_ERROR "Please install the headers of the Orthanc plugins SDK")
+  endif()
+endif()
+
+
+set(CORE_SOURCES
+  ${BOOST_SOURCES}
+  ${JSONCPP_SOURCES}
+  ${PUGIXML_SOURCES}
+  Core/ChunkedBuffer.cpp
+  Core/Configuration.cpp
+  Core/Toolbox.cpp
+  Core/Dicom.cpp
+  Core/MultipartWriter.cpp
+  )
+
+add_library(OrthancDicomWeb SHARED ${CORE_SOURCES}
+  ${CMAKE_SOURCE_DIR}/Plugin/Plugin.cpp
+  ${CMAKE_SOURCE_DIR}/Plugin/QidoRs.cpp
+  ${CMAKE_SOURCE_DIR}/Plugin/StowRs.cpp
+  ${CMAKE_SOURCE_DIR}/Plugin/WadoRs.cpp
+  )
+
+target_link_libraries(OrthancDicomWeb ${GDCM_LIBRARIES} ${OS_LIBRARIES})
+
+message("Setting the version of the library to ${ORTHANC_DICOM_WEB_VERSION}")
+
+add_definitions(-DORTHANC_DICOM_WEB_VERSION="${ORTHANC_DICOM_WEB_VERSION}")
+
+set_target_properties(OrthancDicomWeb PROPERTIES 
+  VERSION ${ORTHANC_DICOM_WEB_VERSION} 
+  SOVERSION ${ORTHANC_DICOM_WEB_VERSION}
+  )
+
+add_executable(UnitTests
+  ${CORE_SOURCES}
+  ${GTEST_SOURCES}
+  UnitTestsSources/UnitTestsMain.cpp
+  )
+
+target_link_libraries(UnitTests ${GDCM_LIBRARIES} ${OS_LIBRARIES})
+
+if (STATIC_BUILD OR NOT USE_SYSTEM_GDCM)
+  add_dependencies(OrthancDicomWeb GDCM)
+  add_dependencies(UnitTests GDCM)
+endif()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/COPYING	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,661 @@
+                    GNU AFFERO GENERAL PUBLIC LICENSE
+                       Version 3, 19 November 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 Affero General Public License is a free, copyleft license for
+software and other kinds of works, specifically designed to ensure
+cooperation with the community in the case of network server software.
+
+  The licenses for most software and other practical works are designed
+to take away your freedom to share and change the works.  By contrast,
+our General Public Licenses are 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.
+
+  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.
+
+  Developers that use our General Public Licenses protect your rights
+with two steps: (1) assert copyright on the software, and (2) offer
+you this License which gives you legal permission to copy, distribute
+and/or modify the software.
+
+  A secondary benefit of defending all users' freedom is that
+improvements made in alternate versions of the program, if they
+receive widespread use, become available for other developers to
+incorporate.  Many developers of free software are heartened and
+encouraged by the resulting cooperation.  However, in the case of
+software used on network servers, this result may fail to come about.
+The GNU General Public License permits making a modified version and
+letting the public access it on a server without ever releasing its
+source code to the public.
+
+  The GNU Affero General Public License is designed specifically to
+ensure that, in such cases, the modified source code becomes available
+to the community.  It requires the operator of a network server to
+provide the source code of the modified version running there to the
+users of that server.  Therefore, public use of a modified version, on
+a publicly accessible server, gives the public access to the source
+code of the modified version.
+
+  An older license, called the Affero General Public License and
+published by Affero, was designed to accomplish similar goals.  This is
+a different license, not a version of the Affero GPL, but Affero has
+released a new version of the Affero GPL which permits relicensing under
+this license.
+
+  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 Affero 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. Remote Network Interaction; Use with the GNU General Public License.
+
+  Notwithstanding any other provision of this License, if you modify the
+Program, your modified version must prominently offer all users
+interacting with it remotely through a computer network (if your version
+supports such interaction) an opportunity to receive the Corresponding
+Source of your version by providing access to the Corresponding Source
+from a network server at no charge, through some standard or customary
+means of facilitating copying of software.  This Corresponding Source
+shall include the Corresponding Source for any work covered by version 3
+of the GNU General Public License that is incorporated pursuant to the
+following paragraph.
+
+  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 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 work with which it is combined will remain governed by version
+3 of the GNU General Public License.
+
+  14. Revised Versions of this License.
+
+  The Free Software Foundation may publish revised and/or new versions of
+the GNU Affero 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 Affero 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 Affero 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 Affero 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 Affero 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 Affero General Public License for more details.
+
+    You should have received a copy of the GNU Affero 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 your software can interact with users remotely through a computer
+network, you should also make sure that it provides a way for users to
+get its source.  For example, if your program is a web application, its
+interface could display a "Source" link that leads users to an archive
+of the code.  There are many ways you could offer source, and different
+solutions will be better for different programs; see section 13 for the
+specific requirements.
+
+  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 AGPL, see
+<http://www.gnu.org/licenses/>.
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/ChunkedBuffer.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,86 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "ChunkedBuffer.h"
+
+#include <cassert>
+#include <string.h>
+
+
+namespace OrthancPlugins
+{
+  void ChunkedBuffer::Clear()
+  {
+    numBytes_ = 0;
+
+    for (Chunks::iterator it = chunks_.begin(); 
+         it != chunks_.end(); ++it)
+    {
+      delete *it;
+    }
+  }
+
+
+  void ChunkedBuffer::AddChunk(const char* chunkData,
+                               size_t chunkSize)
+  {
+    if (chunkSize == 0)
+    {
+      return;
+    }
+
+    assert(chunkData != NULL);
+    chunks_.push_back(new std::string(chunkData, chunkSize));
+    numBytes_ += chunkSize;
+  }
+
+
+  void ChunkedBuffer::AddChunk(const std::string& chunk)
+  {
+    if (chunk.size() > 0)
+    {
+      AddChunk(&chunk[0], chunk.size());
+    }
+  }
+
+
+  void ChunkedBuffer::Flatten(std::string& result)
+  {
+    result.resize(numBytes_);
+
+    size_t pos = 0;
+    for (Chunks::iterator it = chunks_.begin(); 
+         it != chunks_.end(); ++it)
+    {
+      assert(*it != NULL);
+
+      size_t s = (*it)->size();
+      if (s != 0)
+      {
+        memcpy(&result[pos], (*it)->c_str(), s);
+        pos += s;
+      }
+
+      delete *it;
+    }
+
+    chunks_.clear();
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/ChunkedBuffer.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,59 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include <list>
+#include <string>
+
+namespace OrthancPlugins
+{
+  class ChunkedBuffer
+  {
+  private:
+    typedef std::list<std::string*>  Chunks;
+    size_t numBytes_;
+    Chunks chunks_;
+  
+    void Clear();
+
+  public:
+    ChunkedBuffer() : numBytes_(0)
+    {
+    }
+
+    ~ChunkedBuffer()
+    {
+      Clear();
+    }
+
+    size_t GetNumBytes() const
+    {
+      return numBytes_;
+    }
+
+    void AddChunk(const char* chunkData,
+                  size_t chunkSize);
+
+    void AddChunk(const std::string& chunk);
+
+    void Flatten(std::string& result);
+  };
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/Configuration.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,107 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "Configuration.h"
+
+#include "Toolbox.h"
+
+#include <fstream>
+#include <json/reader.h>
+
+namespace OrthancPlugins
+{
+  namespace Configuration
+  {
+    bool Read(Json::Value& configuration,
+              OrthancPluginContext* context)
+    {
+      std::string path;
+
+      {
+        char* pathTmp = OrthancPluginGetConfigurationPath(context);
+        if (pathTmp == NULL)
+        {
+          OrthancPluginLogError(context, "No configuration file is provided");
+          return false;
+        }
+
+        path = std::string(pathTmp);
+
+        OrthancPluginFreeString(context, pathTmp);
+      }
+
+      std::ifstream f(path.c_str());
+
+      Json::Reader reader;
+      if (!reader.parse(f, configuration) ||
+          configuration.type() != Json::objectValue)
+      {
+        std::string s = "Unable to parse the configuration file: " + std::string(path);
+        OrthancPluginLogError(context, s.c_str());
+        return false;
+      }
+
+      return true;
+    }
+
+
+    std::string GetStringValue(const Json::Value& configuration,
+                               const std::string& key,
+                               const std::string& defaultValue)
+    {
+      if (configuration.type() != Json::objectValue ||
+          !configuration.isMember(key) ||
+          configuration[key].type() != Json::stringValue)
+      {
+        return defaultValue;
+      }
+      else
+      {
+        return configuration[key].asString();
+      }
+    }
+
+
+    std::string  GetBaseUrl(const Json::Value& configuration,
+                            const OrthancPluginHttpRequest* request)
+    {
+      std::string host;
+
+      if (configuration.isMember("DicomWeb") &&
+          configuration["DicomWeb"].type() == Json::objectValue)
+      {
+        host = GetStringValue(configuration["DicomWeb"], "Host", "");
+        if (!host.empty())
+        {
+          return host;
+        }
+      }
+
+      if (LookupHttpHeader(host, request, "host"))
+      {
+        return "http://" + host;
+      }
+
+      // Should never happen: The "host" header should always be present
+      // in HTTP requests. Provide a default value anyway.
+      return "http://localhost:8042/";
+    }
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/Configuration.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,40 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include <orthanc/OrthancCPlugin.h>
+#include <json/value.h>
+
+namespace OrthancPlugins
+{
+  namespace Configuration
+  {
+    bool Read(Json::Value& configuration,
+              OrthancPluginContext* context);
+
+    std::string GetStringValue(const Json::Value& configuration,
+                               const std::string& key,
+                               const std::string& defaultValue);
+    
+    std::string  GetBaseUrl(const Json::Value& configuration,
+                            const OrthancPluginHttpRequest* request);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/Dicom.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,330 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "Dicom.h"
+
+#include "ChunkedBuffer.h"
+
+#include <gdcmDictEntry.h>
+#include <boost/lexical_cast.hpp>
+#include <json/writer.h>
+
+namespace OrthancPlugins
+{
+  namespace
+  {
+    class ChunkedBufferWriter : public pugi::xml_writer
+    {
+    private:
+      ChunkedBuffer buffer_;
+
+    public:
+      virtual void write(const void *data, size_t size)
+      {
+        if (size > 0)
+        {
+          buffer_.AddChunk(reinterpret_cast<const char*>(data), size);
+        }
+      }
+
+      void Flatten(std::string& s)
+      {
+        buffer_.Flatten(s);
+      }
+    };
+  }
+
+
+
+  void ParsedDicomFile::Setup(const std::string& dicom)
+  {
+    // Prepare a memory stream over the DICOM instance
+    std::stringstream stream(dicom);
+
+    // Parse the DICOM instance using GDCM
+    reader_.SetStream(stream);
+    if (!reader_.Read())
+    {
+      throw std::runtime_error("GDCM cannot read this DICOM instance");
+    }
+  }
+
+
+  ParsedDicomFile::ParsedDicomFile(const OrthancPlugins::MultipartItem& item)
+  {
+    std::string dicom(item.data_, item.data_ + item.size_);
+    Setup(dicom);
+  }
+
+
+  bool ParsedDicomFile::GetTag(std::string& result,
+                               const gdcm::Tag& tag,
+                               bool stripSpaces) const
+  {
+    const gdcm::DataSet& dataset = GetDataSet();
+
+    if (dataset.FindDataElement(tag))
+    {
+      const gdcm::ByteValue* value = dataset.GetDataElement(tag).GetByteValue();
+      if (value)
+      {
+        result = std::string(value->GetPointer(), value->GetLength());
+
+        if (stripSpaces)
+        {
+          result = OrthancPlugins::StripSpaces(result);
+        }
+
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+
+  std::string ParsedDicomFile::GetTagWithDefault(const gdcm::Tag& tag,
+                                                 const std::string& defaultValue,
+                                                 bool stripSpaces) const
+  {
+    std::string result;
+    if (!GetTag(result, tag, false))
+    {
+      result = defaultValue;
+    }
+
+    if (stripSpaces)
+    {
+      result = OrthancPlugins::StripSpaces(result);
+    }
+
+    return result;
+  }
+
+
+  static std::string FormatTag(const gdcm::Tag& tag)
+  {
+    char tmp[16];
+    sprintf(tmp, "%04X%04X", tag.GetGroup(), tag.GetElement());
+    return std::string(tmp);
+  }
+
+
+  static const char* GetKeyword(const gdcm::Dict& dictionary,
+                                const gdcm::Tag& tag)
+  {
+    const gdcm::DictEntry &entry = dictionary.GetDictEntry(tag);
+    const char* keyword = entry.GetKeyword();
+
+    if (strlen(keyword) != 0)
+    {
+      return keyword;
+    }
+
+    if (tag == DICOM_TAG_RETRIEVE_URL)
+    {
+      return "RetrieveURL";
+    }
+
+    throw std::runtime_error("Unknown keyword for tag: " + FormatTag(tag));
+  }
+
+
+
+  static const char* GetVRName(bool& isSequence,
+                               const gdcm::Dict& dictionary,
+                               const gdcm::DataElement& element)
+  {
+    gdcm::VR vr = element.GetVR();
+    if (vr == gdcm::VR::INVALID)
+    {
+      const gdcm::DictEntry &entry = dictionary.GetDictEntry(element.GetTag());
+      vr = entry.GetVR();
+    }
+
+    isSequence = (vr == gdcm::VR::SQ);
+
+    return gdcm::VR::GetVRString(vr);
+  }
+
+
+  static void DicomToXmlInternal(pugi::xml_node& target,
+                                 const gdcm::Dict& dictionary,
+                                 const gdcm::DataSet& dicom)
+  {
+    for (gdcm::DataSet::ConstIterator it = dicom.Begin();
+         it != dicom.End(); ++it)  // "*it" represents a "gdcm::DataElement"
+    {
+      pugi::xml_node node = target.append_child("DicomAttribute");
+      node.append_attribute("tag").set_value(FormatTag(it->GetTag()).c_str());
+      node.append_attribute("keyword").set_value(GetKeyword(dictionary, it->GetTag()));
+
+      bool isSequence = false;
+      if (it->GetTag() == DICOM_TAG_RETRIEVE_URL)
+      {
+        // The VR of this attribute has changed from UT to UR.
+        node.append_attribute("vr").set_value("UR");
+      }
+      else
+      {
+        node.append_attribute("vr").set_value(GetVRName(isSequence, dictionary, *it));
+      }
+
+      if (isSequence)
+      {
+        gdcm::SmartPointer<gdcm::SequenceOfItems> seq = it->GetValueAsSQ();
+
+        for (gdcm::SequenceOfItems::SizeType i = 1; i <= seq->GetNumberOfItems(); i++)
+        {
+          pugi::xml_node item = node.append_child("Item");
+          std::string number = boost::lexical_cast<std::string>(i);
+          item.append_attribute("number").set_value(number.c_str());
+          DicomToXmlInternal(item, dictionary, seq->GetItem(i).GetNestedDataSet());
+        }
+      }
+      else
+      {
+        // Deal with other value representations
+        pugi::xml_node value = node.append_child("Value");
+        value.append_attribute("number").set_value("1");
+
+        const gdcm::ByteValue* data = it->GetByteValue();
+        if (data)
+        {
+          std::string tmp(data->GetPointer(), data->GetLength());
+          tmp = OrthancPlugins::StripSpaces(tmp);
+          value.append_child(pugi::node_pcdata).set_value(tmp.c_str());
+        }
+      }
+    }
+  }
+
+
+  void DicomToXml(pugi::xml_document& target,
+                  const gdcm::Dict& dictionary,
+                  const gdcm::DataSet& dicom)
+  {
+    pugi::xml_node root = target.append_child("NativeDicomModel");
+    root.append_attribute("xmlns").set_value("http://dicom.nema.org/PS3.19/models/NativeDICOM");
+    root.append_attribute("xsi:schemaLocation").set_value("http://dicom.nema.org/PS3.19/models/NativeDICOM");
+    root.append_attribute("xmlns:xsi").set_value("http://www.w3.org/2001/XMLSchema-instance");
+
+    DicomToXmlInternal(root, dictionary, dicom);
+
+    pugi::xml_node decl = target.prepend_child(pugi::node_declaration);
+    decl.append_attribute("version").set_value("1.0");
+    decl.append_attribute("encoding").set_value("utf-8");
+  }
+
+
+
+
+  void DicomToJson(Json::Value& target,
+                   const gdcm::Dict& dictionary,
+                   const gdcm::DataSet& dicom)
+  {
+    target = Json::objectValue;
+
+    for (gdcm::DataSet::ConstIterator it = dicom.Begin();
+         it != dicom.End(); ++it)  // "*it" represents a "gdcm::DataElement"
+    {
+      Json::Value node = Json::objectValue;
+
+      bool isSequence = false;
+      if (it->GetTag() == DICOM_TAG_RETRIEVE_URL)
+      {
+        // The VR of this attribute has changed from UT to UR.
+        node["vr"] = "UR";
+      }
+      else
+      {
+        node["vr"] = GetVRName(isSequence, dictionary, *it);
+      }
+
+      if (isSequence)
+      {
+        // Deal with sequences
+        node["Value"] = Json::arrayValue;
+
+        gdcm::SmartPointer<gdcm::SequenceOfItems> seq = it->GetValueAsSQ();
+
+        for (gdcm::SequenceOfItems::SizeType i = 1; i <= seq->GetNumberOfItems(); i++)
+        {
+          Json::Value child;
+          DicomToJson(child, dictionary, seq->GetItem(i).GetNestedDataSet());
+          node["Value"].append(child);
+        }
+      }
+      else
+      {
+        // Deal with other value representations
+        node["Value"] = Json::arrayValue;
+
+        const gdcm::ByteValue* data = it->GetByteValue();
+        if (data)
+        {
+          std::string tmp(data->GetPointer(), data->GetLength());
+          node["Value"].append(OrthancPlugins::StripSpaces(tmp));
+        }
+      }
+
+      target[FormatTag(it->GetTag())] = node;
+    }
+  }
+
+
+  void GenerateSingleDicomAnswer(std::string& result,
+                                 const gdcm::Dict& dictionary,
+                                 const gdcm::DataSet& dicom,
+                                 bool isXml)
+  {
+    if (isXml)
+    {
+      pugi::xml_document doc;
+      DicomToXml(doc, dictionary, dicom);
+    
+      ChunkedBufferWriter writer;
+      doc.save(writer, "  ", pugi::format_default, pugi::encoding_utf8);
+
+      writer.Flatten(result);
+    }
+    else
+    {
+      Json::Value v;
+      DicomToJson(v, dictionary, dicom);
+
+      Json::FastWriter writer;
+      result = writer.write(v); 
+    }
+  }
+
+
+  void AnswerDicom(OrthancPluginContext* context,
+                   OrthancPluginRestOutput* output,
+                   const gdcm::Dict& dictionary,
+                   const gdcm::DataSet& dicom,
+                   bool isXml)
+  {
+    std::string answer;
+    GenerateSingleDicomAnswer(answer, dictionary, dicom, isXml);
+    OrthancPluginAnswerBuffer(context, output, answer.c_str(), answer.size(), 
+                              isXml ? "application/dicom+xml" : "application/json");
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/Dicom.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,95 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include "Toolbox.h"
+
+#include <gdcmReader.h>
+#include <gdcmDataSet.h>
+#include <pugixml.hpp>
+#include <gdcmDict.h>
+
+
+namespace OrthancPlugins
+{
+  static const gdcm::Tag DICOM_TAG_SOP_CLASS_UID(0x0008, 0x0016);
+  static const gdcm::Tag DICOM_TAG_SOP_INSTANCE_UID(0x0008, 0x0018);
+  static const gdcm::Tag DICOM_TAG_STUDY_INSTANCE_UID(0x0020, 0x000d);
+  static const gdcm::Tag DICOM_TAG_SERIES_INSTANCE_UID(0x0020, 0x000e);
+  static const gdcm::Tag DICOM_TAG_REFERENCED_SOP_CLASS_UID(0x0008, 0x1150);
+  static const gdcm::Tag DICOM_TAG_REFERENCED_SOP_INSTANCE_UID(0x0008, 0x1155);
+  static const gdcm::Tag DICOM_TAG_RETRIEVE_URL(0x0008, 0x1190);
+  static const gdcm::Tag DICOM_TAG_FAILED_SOP_SEQUENCE(0x0008, 0x1198);
+  static const gdcm::Tag DICOM_TAG_FAILURE_REASON(0x0008, 0x1197);
+  static const gdcm::Tag DICOM_TAG_WARNING_REASON(0x0008, 0x1196);
+  static const gdcm::Tag DICOM_TAG_REFERENCED_SOP_SEQUENCE(0x0008, 0x1199);
+  static const gdcm::Tag DICOM_TAG_ACCESSION_NUMBER(0x0008, 0x0050);
+
+
+  class ParsedDicomFile
+  {
+  private:
+    gdcm::Reader reader_;
+
+    void Setup(const std::string& dicom);
+
+  public:
+    ParsedDicomFile(const OrthancPlugins::MultipartItem& item);
+
+    ParsedDicomFile(const std::string& dicom)
+    {
+      Setup(dicom);
+    }
+
+    const gdcm::DataSet& GetDataSet() const
+    {
+      return reader_.GetFile().GetDataSet();
+    }
+
+    bool GetTag(std::string& result,
+                const gdcm::Tag& tag,
+                bool stripSpaces) const;
+
+    std::string GetTagWithDefault(const gdcm::Tag& tag,
+                                  const std::string& defaultValue,
+                                  bool stripSpaces) const;
+  };
+
+
+  void DicomToXml(pugi::xml_document& target,
+                  const gdcm::Dict& dictionary,
+                  const gdcm::DataSet& dicom);
+
+  void DicomToJson(Json::Value& target,
+                  const gdcm::Dict& dictionary,
+                   const gdcm::DataSet& dicom);
+
+  void GenerateSingleDicomAnswer(std::string& result,
+                                 const gdcm::Dict& dictionary,
+                                 const gdcm::DataSet& dicom,
+                                 bool isXml);
+
+  void AnswerDicom(OrthancPluginContext* context,
+                   OrthancPluginRestOutput* output,
+                   const gdcm::Dict& dictionary,
+                   const gdcm::DataSet& dicom,
+                   bool isXml);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/MultipartWriter.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,54 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "MultipartWriter.h"
+
+namespace OrthancPlugins
+{
+  MultipartWriter::MultipartWriter(const std::string& contentType) : 
+    contentType_(contentType)
+  {
+    // Some random string
+    boundary_ = "123456789abcdefghijklmnopqrstuvwxyz@^";
+  }
+
+  void MultipartWriter::AddPart(const std::string& part)
+  {
+    std::string header = "--" + boundary_ + "\n";
+    header += "Content-Type: " + contentType_ + "\n";
+    header += "MIME-Version: 1.0\n\n";
+    chunks_.AddChunk(header);
+    chunks_.AddChunk(part);
+    chunks_.AddChunk("\n");
+  }
+
+  void MultipartWriter::Answer(OrthancPluginContext* context,
+                               OrthancPluginRestOutput* output)
+  {
+    // Close the body
+    chunks_.AddChunk("--" + boundary_ + "--\n");
+
+    std::string header = "multipart/related; type=" + contentType_ + "; boundary=" + boundary_;
+
+    std::string body;
+    chunks_.Flatten(body);
+    OrthancPluginAnswerBuffer(context, output, body.c_str(), body.size(), header.c_str());
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/MultipartWriter.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,44 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include "ChunkedBuffer.h"
+
+#include <orthanc/OrthancCPlugin.h>
+
+namespace OrthancPlugins
+{
+  class MultipartWriter
+  {
+  private:
+    ChunkedBuffer  chunks_;
+    std::string    contentType_;
+    std::string    boundary_;
+
+  public:
+    MultipartWriter(const std::string& contentType);
+
+    void AddPart(const std::string& part);
+
+    void Answer(OrthancPluginContext* context,
+                OrthancPluginRestOutput* output);
+  };
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/Toolbox.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,244 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "Toolbox.h"
+
+#include <string>
+#include <algorithm>
+#include <boost/regex.hpp>
+#include <json/reader.h>
+
+
+namespace OrthancPlugins
+{
+  void ToLowerCase(std::string& s)
+  {
+    std::transform(s.begin(), s.end(), s.begin(), ::tolower);
+  }
+
+
+  void ToUpperCase(std::string& s)
+  {
+    std::transform(s.begin(), s.end(), s.begin(), ::toupper);
+  }
+
+
+  std::string StripSpaces(const std::string& source)
+  {
+    size_t first = 0;
+
+    while (first < source.length() &&
+           isspace(source[first]))
+    {
+      first++;
+    }
+
+    if (first == source.length())
+    {
+      // String containing only spaces
+      return "";
+    }
+
+    size_t last = source.length();
+    while (last > first &&
+           (isspace(source[last - 1]) ||
+            source[last - 1] == '\0'))
+    {
+      last--;
+    }          
+    
+    assert(first <= last);
+    return source.substr(first, last - first);
+  }
+
+  
+
+  void TokenizeString(std::vector<std::string>& result,
+                      const std::string& value,
+                      char separator)
+  {
+    result.clear();
+
+    std::string currentItem;
+
+    for (size_t i = 0; i < value.size(); i++)
+    {
+      if (value[i] == separator)
+      {
+        result.push_back(currentItem);
+        currentItem.clear();
+      }
+      else
+      {
+        currentItem.push_back(value[i]);
+      }
+    }
+
+    result.push_back(currentItem);
+  }
+
+
+
+  void ParseContentType(std::string& application,
+                        std::map<std::string, std::string>& attributes,
+                        const std::string& header)
+  {
+    application.clear();
+    attributes.clear();
+
+    std::vector<std::string> tokens;
+    TokenizeString(tokens, header, ';');
+
+    assert(tokens.size() > 0);
+    application = tokens[0];
+    StripSpaces(application);
+    ToLowerCase(application);
+
+    boost::regex pattern("\\s*([^=]+)\\s*=\\s*([^=]+)\\s*");
+
+    for (size_t i = 1; i < tokens.size(); i++)
+    {
+      boost::cmatch what;
+      if (boost::regex_match(tokens[i].c_str(), what, pattern))
+      {
+        std::string key(what[1]);
+        std::string value(what[2]);
+        ToLowerCase(key);
+        attributes[key] = value;
+      }
+    }
+  }
+
+
+  bool LookupHttpHeader(std::string& value,
+                        const OrthancPluginHttpRequest* request,
+                        const std::string& header)
+  {
+    value.clear();
+
+    for (uint32_t i = 0; i < request->headersCount; i++)
+    {
+      std::string s = request->headersKeys[i];
+      ToLowerCase(s);
+      if (s == header)
+      {
+        value = request->headersValues[i];
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+
+
+  void ParseMultipartBody(std::vector<MultipartItem>& result,
+                          const char* body,
+                          const uint64_t bodySize,
+                          const std::string& boundary)
+  {
+    result.clear();
+
+    boost::regex header("(\n?)--" + boundary + "(--|.*\n\n)");
+    boost::regex pattern(".*^Content-Type\\s*:\\s*([^\\s]*).*",
+                         boost::regex::icase /* case insensitive */);
+    
+    boost::cmatch what;
+    boost::match_flag_type flags = (boost::match_perl | 
+                                    boost::match_not_dot_null);
+    const char* start = body;
+    const char* end = body + bodySize;
+    std::string currentType;
+
+    while (boost::regex_search(start, end, what, header, flags))   
+    {
+      if (start != body)
+      {
+        MultipartItem item;
+        item.data_ = start;
+        item.size_ = what[0].first - start;
+        item.contentType_ = currentType;
+
+        result.push_back(item);
+      }
+
+      boost::cmatch contentType;
+      if (boost::regex_match(what[0].first, what[0].second, contentType, pattern))
+      {
+        currentType = contentType[1];
+      }
+      else
+      {
+        currentType.clear();
+      }
+    
+      start = what[0].second;
+      flags |= boost::match_prev_avail;
+    }
+  }
+
+
+  bool RestApiGetString(std::string& result,
+                        OrthancPluginContext* context,
+                        const std::string& uri)
+  {
+    OrthancPluginMemoryBuffer buffer;
+    int code = OrthancPluginRestApiGet(context, &buffer, uri.c_str());
+    if (code)
+    {
+      // Error
+      return false;
+    }
+
+    bool ok = true;
+
+    try
+    {
+      if (buffer.size)
+      {
+        result.assign(reinterpret_cast<const char*>(buffer.data), buffer.size);
+      }
+      else
+      {
+        result.clear();
+      }
+    }
+    catch (std::bad_alloc&)
+    {
+      ok = false;
+    }
+
+    OrthancPluginFreeMemoryBuffer(context, &buffer);
+
+    return ok;
+  }
+
+
+  bool RestApiGetJson(Json::Value& result,
+                      OrthancPluginContext* context,
+                      const std::string& uri)
+  {
+    std::string content;
+    RestApiGetString(content, context, uri);
+    
+    Json::Reader reader;
+    return reader.parse(content, result);
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Core/Toolbox.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,68 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include <orthanc/OrthancCPlugin.h>
+#include <string>
+#include <vector>
+#include <json/value.h>
+#include <map>
+
+namespace OrthancPlugins
+{
+  struct MultipartItem
+  {
+    const char*   data_;
+    size_t        size_;
+    std::string   contentType_;
+  };
+
+  void ToLowerCase(std::string& s);
+
+  void ToUpperCase(std::string& s);
+
+  std::string StripSpaces(const std::string& source);
+
+  void TokenizeString(std::vector<std::string>& result,
+                      const std::string& source,
+                      char separator);
+
+  void ParseContentType(std::string& application,
+                        std::map<std::string, std::string>& attributes,
+                        const std::string& header);
+
+  bool LookupHttpHeader(std::string& value,
+                        const OrthancPluginHttpRequest* request,
+                        const std::string& header);
+
+  void ParseMultipartBody(std::vector<MultipartItem>& result,
+                          const char* body,
+                          const uint64_t bodySize,
+                          const std::string& boundary);
+
+  bool RestApiGetString(std::string& result,
+                        OrthancPluginContext* context,
+                        const std::string& uri);
+
+  bool RestApiGetJson(Json::Value& result,
+                      OrthancPluginContext* context,
+                      const std::string& uri);
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/NEWS	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,11 @@
+Pending changes in the mainline
+===============================
+
+No official release yet. Still work in progress.
+
+
+
+2015/03/13
+==========
+
+* Initial commit
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/Plugin.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,111 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "Plugin.h"
+
+#include "QidoRs.h"
+#include "StowRs.h"
+#include "WadoRs.h"
+#include "../Core/Configuration.h"
+
+
+#include <gdcmDictEntry.h>
+#include <gdcmDict.h>
+#include <gdcmDicts.h>
+#include <gdcmGlobal.h>
+
+
+// Global state
+OrthancPluginContext* context_ = NULL;
+Json::Value configuration_;
+const gdcm::Dict* dictionary_ = NULL;
+
+
+extern "C"
+{
+  ORTHANC_PLUGINS_API int32_t OrthancPluginInitialize(OrthancPluginContext* context)
+  {
+    context_ = context;
+
+    /* Check the version of the Orthanc core */
+    if (OrthancPluginCheckVersion(context_) == 0)
+    {
+      char info[1024];
+      sprintf(info, "Your version of Orthanc (%s) must be above %d.%d.%d to run this plugin",
+              context_->orthancVersion,
+              ORTHANC_PLUGINS_MINIMAL_MAJOR_NUMBER,
+              ORTHANC_PLUGINS_MINIMAL_MINOR_NUMBER,
+              ORTHANC_PLUGINS_MINIMAL_REVISION_NUMBER);
+      OrthancPluginLogError(context_, info);
+      return -1;
+    }
+
+
+    dictionary_ = &gdcm::Global::GetInstance().GetDicts().GetPublicDict();
+
+
+    if (!OrthancPlugins::Configuration::Read(configuration_, context) ||
+        configuration_.type() != Json::objectValue)
+    {
+      OrthancPluginLogError(context_, "Unable to read the configuration file");
+      return -1;
+    }
+
+    OrthancPluginSetDescription(context_, "Implementation of DICOM Web (QIDO-RS, STOW-RS and WADO-RS).");
+
+    // WADO-RS callbacks
+    OrthancPluginRegisterRestCallback(context, "/wado-rs/studies/([^/]*)", RetrieveDicomStudy);
+    OrthancPluginRegisterRestCallback(context, "/wado-rs/studies/([^/]*)/series/([^/]*)", RetrieveDicomSeries);
+    OrthancPluginRegisterRestCallback(context, "/wado-rs/studies/([^/]*)/series/([^/]*)/instances/([^/]*)", RetrieveDicomInstance);
+
+    // STOW-RS callbacks
+    OrthancPluginRegisterRestCallback(context, "/stow-rs/studies", StowCallback);
+    OrthancPluginRegisterRestCallback(context, "/stow-rs/studies/([^/]*)", StowCallback);
+
+    // QIDO-RS callbacks
+    OrthancPluginRegisterRestCallback(context, "/qido-rs/studies", SearchForStudies);    
+
+    OrthancPluginRegisterRestCallback(context, "/qido-rs/studies/([^/]*)/series", SearchForSeries);    
+    OrthancPluginRegisterRestCallback(context, "/qido-rs/series", SearchForSeries);    
+
+    OrthancPluginRegisterRestCallback(context, "/qido-rs/studies/([^/]*)/series/([^/]*)/instances", SearchForInstances);    
+    OrthancPluginRegisterRestCallback(context, "/qido-rs/studies/([^/]*)/instances", SearchForInstances);    
+    OrthancPluginRegisterRestCallback(context, "/qido-rs/instances", SearchForInstances);    
+
+    return 0;
+  }
+
+
+  ORTHANC_PLUGINS_API void OrthancPluginFinalize()
+  {
+  }
+
+
+  ORTHANC_PLUGINS_API const char* OrthancPluginGetName()
+  {
+    return "dicom-web";
+  }
+
+
+  ORTHANC_PLUGINS_API const char* OrthancPluginGetVersion()
+  {
+    return ORTHANC_DICOM_WEB_VERSION;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/Plugin.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,30 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include <orthanc/OrthancCPlugin.h>
+#include <json/value.h>
+#include <gdcmDict.h>
+
+// Global state
+extern OrthancPluginContext* context_;
+extern Json::Value configuration_;
+extern const gdcm::Dict* dictionary_;
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/QidoRs.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,959 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "QidoRs.h"
+
+#include "Plugin.h"
+#include "StowRs.h"  // For IsXmlExpected()
+#include "../Core/Dicom.h"
+#include "../Core/Toolbox.h"
+#include "../Core/Configuration.h"
+#include "../Core/MultipartWriter.h"
+
+#include <gdcmTag.h>
+#include <list>
+#include <stdexcept>
+#include <boost/lexical_cast.hpp>
+#include <gdcmDict.h>
+#include <gdcmDicts.h>
+#include <gdcmGlobal.h>
+#include <gdcmDictEntry.h>
+#include <boost/regex.hpp>
+#include <boost/algorithm/string/replace.hpp>
+
+
+
+enum QueryLevel
+{
+  QueryLevel_Study,
+  QueryLevel_Series,
+  QueryLevel_Instance
+};
+
+
+class ModuleMatcher
+{
+private:
+  typedef std::map<gdcm::Tag, std::string>  Filters;
+
+  const gdcm::Dict&     dictionary_;
+  bool                  fuzzy_;
+  unsigned int          offset_;
+  unsigned int          limit_;
+  std::list<gdcm::Tag>  includeFields_;
+  bool                  includeAllFields_;
+  Filters               filters_;
+
+
+
+  static inline uint16_t GetCharValue(char c)
+  {
+    if (c >= '0' && c <= '9')
+      return c - '0';
+    else if (c >= 'a' && c <= 'f')
+      return c - 'a' + 10;
+    else if (c >= 'A' && c <= 'F')
+      return c - 'A' + 10;
+    else
+      return 0;
+  }
+
+  static inline uint16_t GetTagValue(const char* c)
+  {
+    return ((GetCharValue(c[0]) << 12) + 
+            (GetCharValue(c[1]) << 8) + 
+            (GetCharValue(c[2]) << 4) + 
+            GetCharValue(c[3]));
+  }
+
+
+  gdcm::Tag  ParseTag(const std::string& key) const
+  {
+    if (key.size() == 8 &&
+        isxdigit(key[0]) &&
+        isxdigit(key[1]) &&
+        isxdigit(key[2]) &&
+        isxdigit(key[3]) &&
+        isxdigit(key[4]) &&
+        isxdigit(key[5]) &&
+        isxdigit(key[6]) &&
+        isxdigit(key[7]))        
+    {
+      return gdcm::Tag(GetTagValue(key.c_str()),
+                       GetTagValue(key.c_str() + 4));
+    }
+    else
+    {
+      gdcm::Tag tag;
+      dictionary_.GetDictEntryByKeyword(key.c_str(), tag);
+
+      if (tag.IsIllegal() || tag.IsPrivate())
+      {
+        if (key.find('.') != std::string::npos)
+        {
+          throw std::runtime_error("This QIDO-RS implementation does not support search over sequences: " + key);
+        }
+        else
+        {
+          throw std::runtime_error("Illegal tag name in QIDO-RS: " + key);
+        }
+      }
+
+      return tag;
+    }
+  }
+
+
+  static bool IsWildcard(const std::string& constraint)
+  {
+    return (constraint.find('-') != std::string::npos ||
+            constraint.find('*') != std::string::npos ||
+            constraint.find('\\') != std::string::npos ||
+            constraint.find('?') != std::string::npos);
+  }
+
+  static bool ApplyRangeConstraint(const std::string& value,
+                                   const std::string& constraint)
+  {
+    size_t separator = constraint.find('-');
+    std::string lower(constraint.substr(0, separator));
+    std::string upper(constraint.substr(separator + 1));
+    std::string v(value);
+
+    OrthancPlugins::ToLowerCase(lower);
+    OrthancPlugins::ToLowerCase(upper);
+    OrthancPlugins::ToLowerCase(v);
+
+    if (lower.size() == 0 && upper.size() == 0)
+    {
+      return false;
+    }
+
+    if (lower.size() == 0)
+    {
+      return v <= upper;
+    }
+
+    if (upper.size() == 0)
+    {
+      return v >= lower;
+    }
+    
+    return (v >= lower && v <= upper);
+  }
+
+
+  static bool ApplyListConstraint(const std::string& value,
+                                  const std::string& constraint)
+  {
+    std::string v1(value);
+    OrthancPlugins::ToLowerCase(v1);
+
+    std::vector<std::string> items;
+    OrthancPlugins::TokenizeString(items, constraint, '\\');
+
+    for (size_t i = 0; i < items.size(); i++)
+    {
+      std::string lower(items[i]);
+      OrthancPlugins::ToLowerCase(lower);
+      if (lower == v1)
+      {
+        return true;
+      }
+    }
+
+    return false;
+  }
+
+
+  static std::string WildcardToRegularExpression(const std::string& source)
+  {
+    std::string result = source;
+
+    // Escape all special characters
+    boost::replace_all(result, "\\", "\\\\");
+    boost::replace_all(result, "^", "\\^");
+    boost::replace_all(result, ".", "\\.");
+    boost::replace_all(result, "$", "\\$");
+    boost::replace_all(result, "|", "\\|");
+    boost::replace_all(result, "(", "\\(");
+    boost::replace_all(result, ")", "\\)");
+    boost::replace_all(result, "[", "\\[");
+    boost::replace_all(result, "]", "\\]");
+    boost::replace_all(result, "+", "\\+");
+    boost::replace_all(result, "/", "\\/");
+    boost::replace_all(result, "{", "\\{");
+    boost::replace_all(result, "}", "\\}");
+
+    // Convert wildcards '*' and '?' to their regex equivalents
+    boost::replace_all(result, "?", ".");
+    boost::replace_all(result, "*", ".*");
+
+    return result;
+  }
+
+
+  static bool Matches(const std::string& value,
+                      const std::string& constraint)
+  {
+    // http://www.itk.org/Wiki/DICOM_QueryRetrieve_Explained
+    // http://dicomiseasy.blogspot.be/2012/01/dicom-queryretrieve-part-i.html  
+
+    if (constraint.find('-') != std::string::npos)
+    {
+      return ApplyRangeConstraint(value, constraint);
+    }
+    
+    if (constraint.find('\\') != std::string::npos)
+    {
+      return ApplyListConstraint(value, constraint);
+    }
+
+    if (constraint.find('*') != std::string::npos ||
+        constraint.find('?') != std::string::npos)
+    {
+      boost::regex pattern(WildcardToRegularExpression(constraint),
+                           boost::regex::icase /* case insensitive search */);
+      return boost::regex_match(value, pattern);
+    }
+    else
+    {
+      std::string v(value), c(constraint);
+      OrthancPlugins::ToLowerCase(v);
+      OrthancPlugins::ToLowerCase(c);
+      return v == c;
+    }
+  }
+
+
+
+  static void AddResultAttributesForLevel(std::list<gdcm::Tag>& result,
+                                          QueryLevel level)
+  {
+    switch (level)
+    {
+      case QueryLevel_Study:
+        // http://medical.nema.org/medical/dicom/current/output/html/part18.html#table_6.7.1-2
+        result.push_back(gdcm::Tag(0x0008, 0x0005));  // Specific Character Set
+        result.push_back(gdcm::Tag(0x0008, 0x0020));  // Study Date
+        result.push_back(gdcm::Tag(0x0008, 0x0030));  // Study Time
+        result.push_back(gdcm::Tag(0x0008, 0x0050));  // Accession Number
+        result.push_back(gdcm::Tag(0x0008, 0x0056));  // Instance Availability
+        result.push_back(gdcm::Tag(0x0008, 0x0061));  // Modalities in Study
+        result.push_back(gdcm::Tag(0x0008, 0x0090));  // Referring Physician's Name
+        result.push_back(gdcm::Tag(0x0008, 0x0201));  // Timezone Offset From UTC
+        //result.push_back(gdcm::Tag(0x0008, 0x1190));  // Retrieve URL  => SPECIAL CASE
+        result.push_back(gdcm::Tag(0x0010, 0x0010));  // Patient's Name
+        result.push_back(gdcm::Tag(0x0010, 0x0020));  // Patient ID
+        result.push_back(gdcm::Tag(0x0010, 0x0030));  // Patient's Birth Date
+        result.push_back(gdcm::Tag(0x0010, 0x0040));  // Patient's Sex
+        result.push_back(gdcm::Tag(0x0020, 0x000D));  // Study Instance UID
+        result.push_back(gdcm::Tag(0x0020, 0x0010));  // Study ID
+        result.push_back(gdcm::Tag(0x0020, 0x1206));  // Number of Study Related Series
+        result.push_back(gdcm::Tag(0x0020, 0x1208));  // Number of Study Related Instances
+        break;
+
+      case QueryLevel_Series:
+        // http://medical.nema.org/medical/dicom/current/output/html/part18.html#table_6.7.1-2a
+        result.push_back(gdcm::Tag(0x0008, 0x0005));  // Specific Character Set
+        result.push_back(gdcm::Tag(0x0008, 0x0056));  // Modality
+        result.push_back(gdcm::Tag(0x0008, 0x0201));  // Timezone Offset From UTC
+        result.push_back(gdcm::Tag(0x0008, 0x103E));  // Series Description
+        //result.push_back(gdcm::Tag(0x0008, 0x1190));  // Retrieve URL  => SPECIAL CASE
+        result.push_back(gdcm::Tag(0x0020, 0x000E));  // Series Instance UID
+        result.push_back(gdcm::Tag(0x0020, 0x0011));  // Series Number
+        result.push_back(gdcm::Tag(0x0020, 0x1209));  // Number of Series Related Instances
+        result.push_back(gdcm::Tag(0x0040, 0x0244));  // Performed Procedure Step Start Date
+        result.push_back(gdcm::Tag(0x0040, 0x0245));  // Performed Procedure Step Start Time
+        result.push_back(gdcm::Tag(0x0040, 0x0275));  // Request Attribute Sequence
+        break;
+
+      case QueryLevel_Instance:
+        // http://medical.nema.org/medical/dicom/current/output/html/part18.html#table_6.7.1-2b
+        result.push_back(gdcm::Tag(0x0008, 0x0005));  // Specific Character Set
+        result.push_back(gdcm::Tag(0x0008, 0x0016));  // SOP Class UID
+        result.push_back(gdcm::Tag(0x0008, 0x0018));  // SOP Instance UID
+        result.push_back(gdcm::Tag(0x0008, 0x0056));  // Instance Availability
+        result.push_back(gdcm::Tag(0x0008, 0x0201));  // Timezone Offset From UTC
+        result.push_back(gdcm::Tag(0x0008, 0x1190));  // Retrieve URL
+        result.push_back(gdcm::Tag(0x0020, 0x0013));  // Instance Number
+        result.push_back(gdcm::Tag(0x0028, 0x0010));  // Rows
+        result.push_back(gdcm::Tag(0x0028, 0x0011));  // Columns
+        result.push_back(gdcm::Tag(0x0028, 0x0100));  // Bits Allocated
+        result.push_back(gdcm::Tag(0x0028, 0x0008));  // Number of Frames
+        break;
+
+      default:
+        throw std::runtime_error("Internal error");
+    }
+  }
+
+
+
+public:
+  ModuleMatcher(const OrthancPluginHttpRequest* request) :
+  dictionary_(gdcm::Global::GetInstance().GetDicts().GetPublicDict()),
+  fuzzy_(false),
+  offset_(0),
+  limit_(0),
+  includeAllFields_(false)
+  {
+    for (int32_t i = 0; i < request->getCount; i++)
+    {
+      std::string key(request->getKeys[i]);
+      std::string value(request->getValues[i]);
+
+      if (key == "limit")
+      {
+        limit_ = boost::lexical_cast<unsigned int>(value);
+      }
+      else if (key == "offset")
+      {
+        offset_ = boost::lexical_cast<unsigned int>(value);
+      }
+      else if (key == "fuzzymatching")
+      {
+        if (value == "true")
+        {
+          fuzzy_ = true;
+        }
+        else if (value == "false")
+        {
+          fuzzy_ = false;
+        }
+        else
+        {
+          throw std::runtime_error("Not a proper value for fuzzy matching (true or false): " + value);
+        }
+      }
+      else if (key == "includefield")
+      {
+        if (key == "all")
+        {
+          includeAllFields_ = true;
+        }
+        else
+        {
+          includeFields_.push_back(ParseTag(key));
+        }
+      }
+      else
+      {
+        filters_[ParseTag(key)] = value;
+      }
+    }
+  }
+
+  unsigned int GetLimit() const
+  {
+    return limit_;
+  }
+
+  unsigned int GetOffset() const
+  {
+    return offset_;
+  }
+
+  void AddFilter(const gdcm::Tag& tag,
+                 const std::string& constraint)
+  {
+    filters_[tag] = constraint;
+  }
+
+  bool LookupExactFilter(std::string& constraint,
+                         const gdcm::Tag& tag) const
+  {
+    Filters::const_iterator it = filters_.find(tag);
+    if (it != filters_.end() &&
+        !IsWildcard(it->second))
+    {
+      constraint = it->second;
+      return true;
+    }
+    else
+    {
+      return false;
+    }
+  }
+
+  bool Matches(const OrthancPlugins::ParsedDicomFile& dicom) const
+  {
+    for (Filters::const_iterator it = filters_.begin();
+         it != filters_.end(); ++it)
+    {
+      std::string value;
+      if (!dicom.GetTag(value, it->first, true))
+      {
+        return false;
+      }
+
+      if (!Matches(value, it->second))
+      {
+        return false;
+      }
+    }
+
+    return true;
+  }
+
+
+  void ExtractFields(gdcm::DataSet& result,
+                     const OrthancPlugins::ParsedDicomFile& dicom,
+                     const std::string& wadoBase,
+                     QueryLevel level) const
+  {
+    std::list<gdcm::Tag> fields = includeFields_;
+
+    // The list of attributes for this query level
+    AddResultAttributesForLevel(fields, level);
+
+    // All other attributes passed as query keys
+    for (Filters::const_iterator it = filters_.begin();
+         it != filters_.end(); ++it)
+    {
+      fields.push_back(it->first);
+    }
+
+    // For instances and series, add all Study-level attributes if
+    // {StudyInstanceUID} is not specified.
+    if ((level == QueryLevel_Instance  || level == QueryLevel_Series) 
+        && filters_.find(OrthancPlugins::DICOM_TAG_STUDY_INSTANCE_UID) == filters_.end()
+      )
+    {
+      AddResultAttributesForLevel(fields, QueryLevel_Study);
+    }
+
+    // For instances, add all Series-level attributes if
+    // {SeriesInstanceUID} is not specified.
+    if (level == QueryLevel_Instance
+        && filters_.find(OrthancPlugins::DICOM_TAG_SERIES_INSTANCE_UID) == filters_.end()
+      )
+    {
+      AddResultAttributesForLevel(fields, QueryLevel_Series);
+    }
+
+    // Copy all the required fields to the target
+    for (std::list<gdcm::Tag>::const_iterator
+           it = fields.begin(); it != fields.end(); it++)
+    {
+      if (dicom.GetDataSet().FindDataElement(*it))
+      {
+        const gdcm::DataElement& element = dicom.GetDataSet().GetDataElement(*it);
+        result.Replace(element);
+      }
+    }
+
+    // Set the retrieve URL for WADO-RS
+    std::string url = (wadoBase + "/studies/" + 
+                       dicom.GetTagWithDefault(OrthancPlugins::DICOM_TAG_STUDY_INSTANCE_UID, "", true));
+
+    if (level == QueryLevel_Series || level == QueryLevel_Instance)
+    {
+      url += "/series/" + dicom.GetTagWithDefault(OrthancPlugins::DICOM_TAG_SERIES_INSTANCE_UID, "", true);
+    }
+
+    if (level == QueryLevel_Instance)
+    {
+      url += "/instances/" + dicom.GetTagWithDefault(OrthancPlugins::DICOM_TAG_SOP_INSTANCE_UID, "", true);
+    }
+    
+    gdcm::DataElement element(OrthancPlugins::DICOM_TAG_RETRIEVE_URL);
+    element.SetByteValue(url.c_str(), url.size());
+    result.Replace(element);
+  }
+};
+
+
+
+
+class CandidateResources
+{
+private:
+  typedef std::set<std::string>  Resources;
+
+  bool        all_;
+  QueryLevel  level_;
+  Resources   resources_;
+
+  static bool CallLookup(std::string& orthancId,
+                         const std::string& dicomId,
+                         char* (lookup) (OrthancPluginContext*, const char*))
+  {
+    bool result = false;
+
+    char* tmp = lookup(context_, dicomId.c_str());
+    if (tmp != NULL)
+    {
+      orthancId = tmp;
+      result = true;
+    }
+
+    OrthancPluginFreeString(context_, tmp);
+
+    return result;
+  }
+
+
+  void FilterByIdentifierInternal(const ModuleMatcher& matcher,
+                                  const gdcm::Tag& tag,
+                                  char* (lookup) (OrthancPluginContext*, const char*))
+  {
+    std::string orthancId, dicomId;
+
+    if (!matcher.LookupExactFilter(dicomId, tag))
+    {
+      // There is no restriction at this level
+      return;
+    }
+
+    if (CallLookup(orthancId, dicomId, lookup) &&
+        (all_ || resources_.find(orthancId) != resources_.end()))
+    {
+      // There remains a single candidate resource
+      resources_.clear();
+      resources_.insert(orthancId);
+    }
+    else
+    {
+      // No matching resource remains
+      resources_.clear();            
+    }
+
+    all_ = false;
+  }
+
+
+  bool PickOneInstance(std::string& instance,
+                       const std::string& resource) const
+  {
+    if (level_ == QueryLevel_Instance)
+    {
+      instance = resource;
+      return true;
+    }
+
+    std::string uri;
+    if (level_ == QueryLevel_Study)
+    {
+      uri = "/studies/" + resource + "/instances";
+    }
+    else
+    {
+      assert(level_ == QueryLevel_Series);
+      uri = "/series/" + resource + "/instances";
+    }
+
+    Json::Value instances;
+    if (!OrthancPlugins::RestApiGetJson(instances, context_, uri) ||
+        instances.type() != Json::arrayValue &&
+        instances.size() != 0)
+    {
+      return false;
+    }
+
+    instance = instances[0]["ID"].asString();
+    return true;
+  }
+
+
+public:
+  CandidateResources() : all_(true), level_(QueryLevel_Study)
+  {
+  }
+
+  void GoDown()
+  {
+    std::string baseUri;
+    std::string nextLevel;
+    switch (level_)
+    {
+      case QueryLevel_Study:
+        baseUri = "/studies/";
+        nextLevel = "Series";
+        break;
+
+      case QueryLevel_Series:
+        baseUri = "/series/";
+        nextLevel = "Instances";
+        break;
+
+      default:
+        throw std::runtime_error("Internal error");
+    }
+
+
+    if (!all_)
+    {
+      Resources  children;
+      
+      for (Resources::const_iterator it = resources_.begin();
+           it != resources_.end(); it++)
+      {
+        Json::Value tmp;
+        if (OrthancPlugins::RestApiGetJson(tmp, context_, baseUri + *it) &&
+            tmp.type() == Json::objectValue &&
+            tmp.isMember(nextLevel) &&
+            tmp[nextLevel].type() == Json::arrayValue)
+        {
+          for (Json::Value::ArrayIndex i = 0; i < tmp[nextLevel].size(); i++)
+          {
+            children.insert(tmp[nextLevel][i].asString());
+          }
+        }
+      }
+
+      resources_ = children;
+    }
+
+
+    switch (level_)
+    {
+      case QueryLevel_Study:
+        level_ = QueryLevel_Series;
+        break;
+
+      case QueryLevel_Series:
+        level_ = QueryLevel_Instance;
+        break;
+
+      default:
+        throw std::runtime_error("Internal error");
+    }
+  }
+
+
+  void FilterByIdentifier(const ModuleMatcher& matcher)
+  {
+    switch (level_)
+    {
+      case QueryLevel_Study:
+        FilterByIdentifierInternal(matcher, OrthancPlugins::DICOM_TAG_STUDY_INSTANCE_UID,
+                                   OrthancPluginLookupStudy);
+        FilterByIdentifierInternal(matcher, OrthancPlugins::DICOM_TAG_ACCESSION_NUMBER,
+                                   OrthancPluginLookupStudyWithAccessionNumber);
+        break;
+
+      case QueryLevel_Series:
+        FilterByIdentifierInternal(matcher, OrthancPlugins::DICOM_TAG_SERIES_INSTANCE_UID,
+                                   OrthancPluginLookupSeries);
+        break;
+
+      case QueryLevel_Instance:
+        FilterByIdentifierInternal(matcher, OrthancPlugins::DICOM_TAG_SOP_INSTANCE_UID,
+                                   OrthancPluginLookupInstance);
+        break;
+
+      default:
+        throw std::runtime_error("Internal error");
+    }
+  }
+
+
+  void Flatten(std::list<std::string>& result) const
+  {
+    std::string instance;
+
+    result.clear();
+
+    if (all_)
+    {
+      std::string uri;
+      switch (level_)
+      {
+        case QueryLevel_Study:
+          uri = "/studies/";
+          break;
+
+        case QueryLevel_Series:
+          uri = "/series/";
+          break;
+
+        case QueryLevel_Instance:
+          uri = "/instances/";
+          break;
+
+        default:
+          throw std::runtime_error("Internal error");
+      }
+
+      Json::Value tmp;
+      if (OrthancPlugins::RestApiGetJson(tmp, context_, uri) &&
+          tmp.type() == Json::arrayValue)
+      {
+        for (Json::Value::ArrayIndex i = 0; i < tmp.size(); i++)
+        {
+          if (PickOneInstance(instance, tmp[i].asString()))
+          {
+            result.push_back(instance);
+          }
+        }
+      }
+    }
+    else
+    {
+      for (Resources::const_iterator 
+             it = resources_.begin(); it != resources_.end(); it++)
+      {
+        if (PickOneInstance(instance, *it))
+        {
+          result.push_back(instance);
+        }
+      }
+    }
+  }
+};
+
+
+
+class SearchResults
+{
+private:
+  typedef std::list<gdcm::DataSet*>   Results;
+
+  Results results_;
+
+public:
+  ~SearchResults()
+  {
+    for (Results::iterator it = results_.begin();
+         it != results_.end(); it++)
+    {
+      delete *it;
+    }
+  }
+
+  void Add(const OrthancPlugins::ParsedDicomFile& dicom,
+           const ModuleMatcher& matcher,
+           const std::string& wadoBase,
+           QueryLevel level)
+  {
+    std::auto_ptr<gdcm::DataSet> result(new gdcm::DataSet);
+    matcher.ExtractFields(*result, dicom, wadoBase, level);
+    results_.push_back(result.release());
+  }
+
+  void Answer(OrthancPluginContext* context,
+              OrthancPluginRestOutput* output,
+              bool isXml)
+  {
+    if (isXml)
+    {
+      OrthancPlugins::MultipartWriter writer("application/dicom+xml");
+
+      for (Results::const_iterator it = results_.begin();
+           it != results_.end(); it++)
+      {
+        std::string answer;
+        OrthancPlugins::GenerateSingleDicomAnswer(answer, *dictionary_, **it, true);
+        writer.AddPart(answer);
+      }
+
+      writer.Answer(context_, output);
+    }
+    else
+    {
+      OrthancPlugins::ChunkedBuffer chunks;
+      chunks.AddChunk("[\n");
+
+      std::string s = "[\n";
+
+      bool isFirst = true;
+      for (Results::const_iterator it = results_.begin();
+           it != results_.end(); it++)
+      {
+        std::string item;
+        OrthancPlugins::GenerateSingleDicomAnswer(item, *dictionary_, **it, false);
+        chunks.AddChunk(item);
+        
+        if (isFirst)
+        {
+          isFirst = false;
+        }
+        else
+        {
+          chunks.AddChunk(",\n");
+        }
+      }
+
+      chunks.AddChunk("]\n");
+
+      std::string answer;
+      chunks.Flatten(answer);
+      OrthancPluginAnswerBuffer(context, output, answer.c_str(), answer.size(), "application/json");
+    }
+  }
+};
+
+
+
+static void ApplyMatcher(OrthancPluginRestOutput* output,
+                         const OrthancPluginHttpRequest* request,
+                         const ModuleMatcher& matcher,
+                         const CandidateResources& candidates,
+                         QueryLevel level)
+{
+  std::list<std::string> resources;
+  candidates.Flatten(resources);
+
+  std::string wadoBase = OrthancPlugins::Configuration::GetBaseUrl(configuration_, request) + "/wado-rs";
+  SearchResults results;
+  for (std::list<std::string>::const_iterator
+         it = resources.begin(); it != resources.end(); it++)
+  {
+    std::string file;
+    if (OrthancPlugins::RestApiGetString(file, context_, "/instances/" + *it + "/file"))
+    {
+      OrthancPlugins::ParsedDicomFile dicom(file);
+      if (matcher.Matches(dicom))
+      {
+        results.Add(dicom, matcher, wadoBase, level);
+      }
+    }
+  }
+
+  results.Answer(context_, output, IsXmlExpected(request));
+}
+
+
+
+int32_t SearchForStudies(OrthancPluginRestOutput* output,
+                         const char* url,
+                         const OrthancPluginHttpRequest* request)
+{
+  try
+  {
+    if (request->method != OrthancPluginHttpMethod_Get)
+    {
+      OrthancPluginSendMethodNotAllowed(context_, output, "GET");
+      return 0;
+    }
+
+    ModuleMatcher matcher(request);
+
+    CandidateResources candidates;
+    candidates.FilterByIdentifier(matcher);
+
+    ApplyMatcher(output, request, matcher, candidates, QueryLevel_Study);
+
+    return 0;
+  }
+  catch (std::runtime_error& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+  catch (boost::bad_lexical_cast& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+}
+
+
+int32_t SearchForSeries(OrthancPluginRestOutput* output,
+                        const char* url,
+                        const OrthancPluginHttpRequest* request)
+{
+  try
+  {
+    if (request->method != OrthancPluginHttpMethod_Get)
+    {
+      OrthancPluginSendMethodNotAllowed(context_, output, "GET");
+      return 0;
+    }
+
+    ModuleMatcher matcher(request);
+
+    if (request->groupsCount == 1)
+    {
+      // The "StudyInstanceUID" is provided by the regular expression
+      matcher.AddFilter(OrthancPlugins::DICOM_TAG_STUDY_INSTANCE_UID, request->groups[0]);
+    }
+
+    CandidateResources candidates;
+    candidates.FilterByIdentifier(matcher);
+    candidates.GoDown();
+    candidates.FilterByIdentifier(matcher);
+
+    ApplyMatcher(output, request, matcher, candidates, QueryLevel_Series);
+
+    return 0;
+  }
+  catch (std::runtime_error& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+  catch (boost::bad_lexical_cast& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+}
+
+
+int32_t SearchForInstances(OrthancPluginRestOutput* output,
+                           const char* url,
+                           const OrthancPluginHttpRequest* request)
+{
+  try
+  {
+    if (request->method != OrthancPluginHttpMethod_Get)
+    {
+      OrthancPluginSendMethodNotAllowed(context_, output, "GET");
+      return 0;
+    }
+
+    ModuleMatcher matcher(request);
+
+    if (request->groupsCount == 1 || request->groupsCount == 2)
+    {
+      // The "StudyInstanceUID" is provided by the regular expression
+      matcher.AddFilter(OrthancPlugins::DICOM_TAG_STUDY_INSTANCE_UID, request->groups[0]);
+    }
+
+    if (request->groupsCount == 2)
+    {
+      // The "SeriesInstanceUID" is provided by the regular expression
+      matcher.AddFilter(OrthancPlugins::DICOM_TAG_SERIES_INSTANCE_UID, request->groups[1]);
+    }
+
+    CandidateResources candidates;
+    candidates.FilterByIdentifier(matcher);
+    candidates.GoDown();
+    candidates.FilterByIdentifier(matcher);
+    candidates.GoDown();
+    candidates.FilterByIdentifier(matcher);
+
+    ApplyMatcher(output, request, matcher, candidates, QueryLevel_Instance);
+
+    return 0;
+  }
+  catch (std::runtime_error& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+  catch (boost::bad_lexical_cast& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/QidoRs.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,35 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include <orthanc/OrthancCPlugin.h>
+
+int32_t SearchForStudies(OrthancPluginRestOutput* output,
+                         const char* url,
+                         const OrthancPluginHttpRequest* request);
+
+int32_t SearchForSeries(OrthancPluginRestOutput* output,
+                        const char* url,
+                        const OrthancPluginHttpRequest* request);
+
+int32_t SearchForInstances(OrthancPluginRestOutput* output,
+                           const char* url,
+                           const OrthancPluginHttpRequest* request);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/StowRs.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,234 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "StowRs.h"
+#include "Plugin.h"
+
+#include "../Core/Configuration.h"
+#include "../Core/Dicom.h"
+
+
+static void SetTag(gdcm::DataSet& dataset,
+                   const gdcm::Tag& tag,
+                   const gdcm::VR& vr,
+                   const std::string& value)
+{
+  gdcm::DataElement element(tag);
+  element.SetVR(vr);
+  element.SetByteValue(value.c_str(), value.size());
+  dataset.Insert(element);
+}
+
+
+static void SetSequenceTag(gdcm::DataSet& dataset,
+                           const gdcm::Tag& tag,
+                           gdcm::SmartPointer<gdcm::SequenceOfItems>& sequence)
+{
+  gdcm::DataElement element;
+  element.SetTag(tag);
+  element.SetVR(gdcm::VR::SQ);
+  element.SetValue(*sequence);
+  element.SetVLToUndefined();
+  dataset.Insert(element);
+}
+
+
+
+bool IsXmlExpected(const OrthancPluginHttpRequest* request)
+{
+  std::string accept;
+
+  if (!OrthancPlugins::LookupHttpHeader(accept, request, "accept"))
+  {
+    return true;   // By default, return XML Native DICOM Model
+  }
+
+  OrthancPlugins::ToLowerCase(accept);
+  if (accept == "application/json")
+  {
+    return false;
+  }
+
+  if (accept != "application/dicom+xml" &&
+      accept != "application/xml" &&
+      accept != "text/xml" &&
+      accept != "*/*")
+  {
+    std::string s = "Unsupported return MIME type: " + accept + ", will return XML";
+    OrthancPluginLogError(context_, s.c_str());
+  }
+
+  return true;
+}
+
+
+
+int32_t StowCallback(OrthancPluginRestOutput* output,
+                     const char* url,
+                     const OrthancPluginHttpRequest* request)
+{
+  try
+  {
+    const std::string wadoBase = OrthancPlugins::Configuration::GetBaseUrl(configuration_, request) + "/wado-rs";
+
+
+    if (request->method != OrthancPluginHttpMethod_Post)
+    {
+      OrthancPluginSendMethodNotAllowed(context_, output, "POST");
+      return 0;
+    }
+
+    std::string expectedStudy;
+    if (request->groupsCount == 1)
+    {
+      expectedStudy = request->groups[0];
+    }
+
+    if (expectedStudy.empty())
+    {
+      OrthancPluginLogInfo(context_, "STOW-RS request without study");
+    }
+    else
+    {
+      std::string s = "STOW-RS request restricted to study UID " + expectedStudy;
+      OrthancPluginLogInfo(context_, s.c_str());
+    }
+
+    bool isXml = IsXmlExpected(request);
+
+    std::string header;
+    if (!OrthancPlugins::LookupHttpHeader(header, request, "content-type"))
+    {
+      OrthancPluginLogError(context_, "No content type in the HTTP header of a STOW-RS request");
+      OrthancPluginSendHttpStatusCode(context_, output, 400 /* Bad request */);
+      return 0;    
+    }
+
+    std::string application;
+    std::map<std::string, std::string> attributes;
+    OrthancPlugins::ParseContentType(application, attributes, header);
+
+    if (application != "multipart/related" ||
+        attributes.find("type") == attributes.end() ||
+        attributes.find("boundary") == attributes.end())
+    {
+      std::string s = "Unable to parse the content type of a STOW-RS request (" + application + ")";
+      OrthancPluginLogError(context_, s.c_str());
+      OrthancPluginSendHttpStatusCode(context_, output, 400 /* Bad request */);
+      return 0;
+    }
+
+
+    std::string boundary = attributes["boundary"]; 
+
+    if (attributes["type"] != "application/dicom")
+    {
+      OrthancPluginLogError(context_, "The STOW-RS plugin currently only supports application/dicom");
+      OrthancPluginSendHttpStatusCode(context_, output, 415 /* Unsupported media type */);
+      return 0;
+    }
+
+
+
+    bool isFirst = true;
+    gdcm::DataSet result;
+    gdcm::SmartPointer<gdcm::SequenceOfItems> success = new gdcm::SequenceOfItems();
+    gdcm::SmartPointer<gdcm::SequenceOfItems> failed = new gdcm::SequenceOfItems();
+  
+    std::vector<OrthancPlugins::MultipartItem> items;
+    OrthancPlugins::ParseMultipartBody(items, request->body, request->bodySize, boundary);
+    for (size_t i = 0; i < items.size(); i++)
+    {
+      if (!items[i].contentType_.empty() &&
+          items[i].contentType_ != "application/dicom")
+      {
+        OrthancPluginLogError(context_, "The STOW-RS request contains a part that is not application/dicom");
+        OrthancPluginSendHttpStatusCode(context_, output, 415 /* Unsupported media type */);
+        return 0;
+      }
+
+      OrthancPlugins::ParsedDicomFile dicom(items[i]);
+
+      std::string studyInstanceUid = dicom.GetTagWithDefault(OrthancPlugins::DICOM_TAG_STUDY_INSTANCE_UID, "", true);
+      std::string sopClassUid = dicom.GetTagWithDefault(OrthancPlugins::DICOM_TAG_SOP_CLASS_UID, "", true);
+      std::string sopInstanceUid = dicom.GetTagWithDefault(OrthancPlugins::DICOM_TAG_SOP_INSTANCE_UID, "", true);
+
+      gdcm::Item item;
+      item.SetVLToUndefined();
+      gdcm::DataSet &status = item.GetNestedDataSet();
+
+      SetTag(status, OrthancPlugins::DICOM_TAG_REFERENCED_SOP_CLASS_UID, gdcm::VR::UI, sopClassUid);
+      SetTag(status, OrthancPlugins::DICOM_TAG_REFERENCED_SOP_INSTANCE_UID, gdcm::VR::UI, sopInstanceUid);
+
+      if (!expectedStudy.empty() &&
+          studyInstanceUid != expectedStudy)
+      {
+        std::string s = ("STOW-RS request restricted to study [" + expectedStudy + 
+                         "]: Ignoring instance from study [" + studyInstanceUid + "]");
+        OrthancPluginLogInfo(context_, s.c_str());
+
+        SetTag(status, OrthancPlugins::DICOM_TAG_WARNING_REASON, gdcm::VR::US, "B006");  // Elements discarded
+        success->AddItem(item);      
+      }
+      else
+      {
+        if (isFirst)
+        {
+          std::string url = wadoBase + "/studies/" + studyInstanceUid;
+          SetTag(result, OrthancPlugins::DICOM_TAG_RETRIEVE_URL, gdcm::VR::UT, url);
+          isFirst = false;
+        }
+
+        OrthancPluginMemoryBuffer result;
+        bool ok = OrthancPluginRestApiPost(context_, &result, "/instances", items[i].data_, items[i].size_) == 0;
+        OrthancPluginFreeMemoryBuffer(context_, &result);
+
+        if (ok)
+        {
+          std::string url = (wadoBase + 
+                             "/studies/" + studyInstanceUid +
+                             "/series/" + dicom.GetTagWithDefault(OrthancPlugins::DICOM_TAG_SERIES_INSTANCE_UID, "", true) +
+                             "/instances/" + sopInstanceUid);
+
+          SetTag(status, OrthancPlugins::DICOM_TAG_RETRIEVE_URL, gdcm::VR::UT, url);
+          success->AddItem(item);
+        }
+        else
+        {
+          OrthancPluginLogError(context_, "Orthanc was unable to store instance through STOW-RS request");
+          SetTag(status, OrthancPlugins::DICOM_TAG_FAILURE_REASON, gdcm::VR::US, "0110");  // Processing failure
+          failed->AddItem(item);
+        }
+      }
+    }
+
+    SetSequenceTag(result, OrthancPlugins::DICOM_TAG_FAILED_SOP_SEQUENCE, failed);
+    SetSequenceTag(result, OrthancPlugins::DICOM_TAG_REFERENCED_SOP_SEQUENCE, success);
+
+    OrthancPlugins::AnswerDicom(context_, output, *dictionary_, result, isXml);
+
+    return 0;
+  }
+  catch (std::runtime_error& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/StowRs.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,29 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include <orthanc/OrthancCPlugin.h>
+
+bool IsXmlExpected(const OrthancPluginHttpRequest* request);
+
+int32_t StowCallback(OrthancPluginRestOutput* output,
+                     const char* url,
+                     const OrthancPluginHttpRequest* request);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/WadoRs.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,278 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include "Plugin.h"
+
+#include "../Core/Configuration.h"
+#include "../Core/Dicom.h"
+#include "../Core/MultipartWriter.h"
+
+
+static bool AcceptMultipartDicom(const OrthancPluginHttpRequest* request)
+{
+  std::string accept;
+
+  if (!OrthancPlugins::LookupHttpHeader(accept, request, "accept"))
+  {
+    return true;   // By default, return "multipart/related; type=application/dicom;"
+  }
+
+  std::string application;
+  std::map<std::string, std::string> attributes;
+  OrthancPlugins::ParseContentType(application, attributes, accept);
+
+  if (application != "multipart/related" &&
+      application != "*/*")
+  {
+    std::string s = "This WADO-RS plugin cannot generate the following content type: " + accept;
+    OrthancPluginLogError(context_, s.c_str());
+    return false;
+  }
+
+  if (attributes.find("type") != attributes.end())
+  {
+    std::string s = attributes["type"];
+    OrthancPlugins::ToLowerCase(s);
+    if (s != "application/dicom")
+    {
+      std::string s = "This WADO-RS plugin only supports application/dicom return type (" + accept + ")";
+      OrthancPluginLogError(context_, s.c_str());
+      return false;
+    }
+  }
+
+  if (attributes.find("transfer-syntax") != attributes.end())
+  {
+    std::string s = "This WADO-RS plugin cannot change the transfer syntax to " + attributes["transfer-syntax"];
+    OrthancPluginLogError(context_, s.c_str());
+    return false;
+  }
+
+  return true;
+}
+
+
+
+static int32_t AnswerListOfDicomInstances(OrthancPluginRestOutput* output,
+                                          const std::string& resource)
+{
+  Json::Value instances;
+  if (!OrthancPlugins::RestApiGetJson(instances, context_, resource + "/instances"))
+  {
+    // Internal error
+    OrthancPluginSendHttpStatusCode(context_, output, 400);
+    return 0;
+  }
+  
+  
+  OrthancPlugins::MultipartWriter writer("application/dicom");
+  for (Json::Value::ArrayIndex i = 0; i < instances.size(); i++)
+  {
+    std::string uri = "/instances/" + instances[i]["ID"].asString() + "/file";
+    std::string dicom;
+    if (OrthancPlugins::RestApiGetString(dicom, context_, uri))
+    {
+      writer.AddPart(dicom);
+    }
+  }
+
+  writer.Answer(context_, output);
+}
+
+
+
+int32_t RetrieveDicomStudy(OrthancPluginRestOutput* output,
+                           const char* url,
+                           const OrthancPluginHttpRequest* request)
+{
+  try
+  {
+    if (request->method != OrthancPluginHttpMethod_Get)
+    {
+      OrthancPluginSendMethodNotAllowed(context_, output, "GET");
+      return 0;
+    }
+
+    if (!AcceptMultipartDicom(request))
+    {
+      OrthancPluginSendHttpStatusCode(context_, output, 400 /* Bad request */);
+      return 0;
+    }
+
+    std::string id;
+
+    {
+      char* tmp = OrthancPluginLookupStudy(context_, request->groups[0]);
+      if (tmp == NULL)
+      {
+        std::string s = "Accessing an inexistent study with WADO-RS: " + std::string(request->groups[0]);
+        OrthancPluginLogError(context_, s.c_str());
+        OrthancPluginSendHttpStatusCode(context_, output, 404);
+        return 0;
+      }
+
+      id.assign(tmp);
+      OrthancPluginFreeString(context_, tmp);
+    }
+  
+    AnswerListOfDicomInstances(output, "/studies/" + id);
+
+    return 0;
+  }
+  catch (std::runtime_error& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+}
+
+
+int32_t RetrieveDicomSeries(OrthancPluginRestOutput* output,
+                            const char* url,
+                            const OrthancPluginHttpRequest* request)
+{
+  try
+  {
+    if (request->method != OrthancPluginHttpMethod_Get)
+    {
+      OrthancPluginSendMethodNotAllowed(context_, output, "GET");
+      return 0;
+    }
+
+    if (!AcceptMultipartDicom(request))
+    {
+      OrthancPluginSendHttpStatusCode(context_, output, 400 /* Bad request */);
+      return 0;
+    }
+
+    std::string id;
+
+    {
+      char* tmp = OrthancPluginLookupSeries(context_, request->groups[1]);
+      if (tmp == NULL)
+      {
+        std::string s = "Accessing an inexistent series with WADO-RS: " + std::string(request->groups[1]);
+        OrthancPluginLogError(context_, s.c_str());
+        OrthancPluginSendHttpStatusCode(context_, output, 404);
+        return 0;
+      }
+
+      id.assign(tmp);
+      OrthancPluginFreeString(context_, tmp);
+    }
+  
+    Json::Value study;
+    if (!OrthancPlugins::RestApiGetJson(study, context_, "/series/" + id + "/study"))
+    {
+      OrthancPluginSendHttpStatusCode(context_, output, 404);
+      return 0;
+    }
+
+    if (study["MainDicomTags"]["StudyInstanceUID"].asString() != std::string(request->groups[0]))
+    {
+      std::string s = "No series " + std::string(request->groups[1]) + " in study " + std::string(request->groups[0]);
+      OrthancPluginLogError(context_, s.c_str());
+      OrthancPluginSendHttpStatusCode(context_, output, 404);
+      return 0;
+    }
+
+    AnswerListOfDicomInstances(output, "/series/" + id);
+
+    return 0;
+  }
+  catch (std::runtime_error& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+}
+
+
+
+int32_t RetrieveDicomInstance(OrthancPluginRestOutput* output,
+                              const char* url,
+                              const OrthancPluginHttpRequest* request)
+{
+  try
+  {
+    if (request->method != OrthancPluginHttpMethod_Get)
+    {
+      OrthancPluginSendMethodNotAllowed(context_, output, "GET");
+      return 0;
+    }
+
+    if (!AcceptMultipartDicom(request))
+    {
+      OrthancPluginSendHttpStatusCode(context_, output, 400 /* Bad request */);
+      return 0;
+    }
+
+    std::string id;
+
+    {
+      char* tmp = OrthancPluginLookupInstance(context_, request->groups[2]);
+      if (tmp == NULL)
+      {
+        std::string s = "Accessing an inexistent instance with WADO-RS: " + std::string(request->groups[2]);
+        OrthancPluginLogError(context_, s.c_str());
+        OrthancPluginSendHttpStatusCode(context_, output, 404);
+        return 0;
+      }
+
+      id.assign(tmp);
+      OrthancPluginFreeString(context_, tmp);
+    }
+  
+    Json::Value study, series;
+    if (!OrthancPlugins::RestApiGetJson(series, context_, "/instances/" + id + "/series") ||
+        !OrthancPlugins::RestApiGetJson(study, context_, "/instances/" + id + "/study"))
+    {
+      OrthancPluginSendHttpStatusCode(context_, output, 404);
+      return 0;
+    }
+
+    if (study["MainDicomTags"]["StudyInstanceUID"].asString() != std::string(request->groups[0]) ||
+        series["MainDicomTags"]["SeriesInstanceUID"].asString() != std::string(request->groups[1]))
+    {
+      std::string s = ("No instance " + std::string(request->groups[2]) + 
+                       " in study " + std::string(request->groups[0]) + " or " +
+                       " in series " + std::string(request->groups[1]));
+      OrthancPluginLogError(context_, s.c_str());
+      OrthancPluginSendHttpStatusCode(context_, output, 404);
+      return 0;
+    }
+
+    OrthancPlugins::MultipartWriter writer("application/dicom");
+    std::string dicom;
+    if (OrthancPlugins::RestApiGetString(dicom, context_, "/instances/" + id + "/file"))
+    {
+      writer.AddPart(dicom);
+    }
+
+    writer.Answer(context_, output);
+
+    return 0;
+  }
+  catch (std::runtime_error& e)
+  {
+    OrthancPluginLogError(context_, e.what());
+    return -1;
+  }
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Plugin/WadoRs.h	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,36 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#pragma once
+
+#include <orthanc/OrthancCPlugin.h>
+
+
+int32_t RetrieveDicomStudy(OrthancPluginRestOutput* output,
+                           const char* url,
+                           const OrthancPluginHttpRequest* request);
+
+int32_t RetrieveDicomSeries(OrthancPluginRestOutput* output,
+                            const char* url,
+                            const OrthancPluginHttpRequest* request);
+
+int32_t RetrieveDicomInstance(OrthancPluginRestOutput* output,
+                              const char* url,
+                              const OrthancPluginHttpRequest* request);
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/README	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,71 @@
+DICOM Web plugin for Orthanc
+============================
+
+
+General Information
+-------------------
+
+This repository contains the source code of a plugin for Orthanc, the
+lightweight Vendor Neutral Archive for medical imaging. This plugin
+extends the RESTful API of Orthanc with DICOM Web support.
+
+
+DICOM Web Support
+-----------------
+
+Currently, a basic support of the following protocols is provided:
+
+* WADO-RS (Web Access to DICOM Objects by RESTful Services)
+  http://medical.nema.org/medical/dicom/current/output/html/part18.html#sect_6.5
+
+* STOW-RS (STore Over the Web by RESTful Services)
+  http://medical.nema.org/medical/dicom/current/output/html/part18.html#sect_6.6
+
+* QIDO-RS (Query based on ID for DICOM Objects by RESTful Services)
+  http://medical.nema.org/medical/dicom/current/output/html/part18.html#sect_6.7
+
+The full status about the support of these protocols can be found in
+the "./Status.txt" file.
+
+
+Supported Platforms
+-------------------
+
+Currently, the supported platforms are:
+
+* Linux 32bit.
+* Linux 64bit.
+* Windows 32bit with MinGW.
+
+Build instructions can be found in "./Resources/BuildInstructions.txt".
+
+
+Samples
+-------
+
+Python samples to call the DICOM Web services can be found in the
+"./Samples" folder.
+
+
+Licensing
+---------
+
+The DICOM Web plugin for Orthanc is licensed under the AGPL 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}}
+}
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/BuildInstructions.txt	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,37 @@
+Generic Linux (static linking)
+==============================
+
+# mkdir Build
+# cd Build
+# cmake .. -DCMAKE_BUILD_TYPE=Debug -DALLOW_DOWNLOADS=ON -DSTATIC_BUILD=ON
+# make
+
+
+Dynamic linking for Ubuntu 12.10
+================================
+
+# mkdir Build
+# cd Build
+# cmake .. -DCMAKE_BUILD_TYPE=Debug \
+  -DALLOW_DOWNLOADS=ON \
+  -DUSE_SYSTEM_JSONCPP=OFF \
+  -DUSE_SYSTEM_PUGIXML=OFF \
+  -DUSE_GTEST_DEBIAN_SOURCE_PACKAGE=ON
+# make
+
+
+Cross-compiling for Windows from Linux using MinGW
+==================================================
+
+# mkdir Build
+# cd Build
+# cmake .. -DCMAKE_BUILD_TYPE=Debug -DCMAKE_TOOLCHAIN_FILE=../Resources/MinGWToolchain.cmake
+# make
+
+
+Notes
+=====
+
+List the public symbols exported by the shared library under Linux:
+
+# nm -C -D --defined-only ./libOrthancDicomWeb.so
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/CMake/BoostConfiguration.cmake	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,130 @@
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+if (STATIC_BUILD OR NOT USE_SYSTEM_BOOST)
+  set(BOOST_STATIC 1)
+else()
+  include(FindBoost)
+  set(BOOST_STATIC 0)
+  find_package(Boost COMPONENTS system thread filesystem regex)
+
+  if (NOT Boost_FOUND)
+    message(FATAL_ERROR "Unable to locate Boost on this system")
+  endif()
+
+  include_directories(${Boost_INCLUDE_DIRS})
+  link_libraries(${Boost_LIBRARIES})
+endif()
+
+
+if (BOOST_STATIC)
+  # Parameters for Boost 1.55.0
+  set(BOOST_NAME boost_1_55_0)
+  set(BOOST_BCP_SUFFIX bcpdigest-0.7.4)
+  set(BOOST_MD5 "409f7a0e4fb1f5659d07114f3133b67b")
+  set(BOOST_FILESYSTEM_SOURCES_DIR "${BOOST_NAME}/libs/filesystem/src")
+  
+  set(BOOST_SOURCES_DIR ${CMAKE_BINARY_DIR}/${BOOST_NAME})
+  DownloadPackage(
+    "${BOOST_MD5}"
+    "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/${BOOST_NAME}_${BOOST_BCP_SUFFIX}.tar.gz"
+    "${BOOST_SOURCES_DIR}"
+    )
+
+  add_definitions(
+    # Static build of Boost
+    -DBOOST_ALL_NO_LIB 
+    -DBOOST_ALL_NOLIB 
+    -DBOOST_DATE_TIME_NO_LIB 
+    -DBOOST_THREAD_BUILD_LIB
+    -DBOOST_PROGRAM_OPTIONS_NO_LIB
+    -DBOOST_REGEX_NO_LIB
+    -DBOOST_SYSTEM_NO_LIB
+    -DBOOST_LOCALE_NO_LIB
+    )
+
+  if (${CMAKE_COMPILER_IS_GNUCXX})
+    add_definitions(-isystem ${BOOST_SOURCES_DIR})
+  endif()
+
+  include_directories(
+    ${BOOST_SOURCES_DIR}
+    )
+
+  list(APPEND BOOST_SOURCES
+    ${BOOST_SOURCES_DIR}/libs/system/src/error_code.cpp
+    )
+
+
+  ## Boost::thread
+
+  if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux" OR
+      ${CMAKE_SYSTEM_NAME} STREQUAL "Darwin" OR
+      ${CMAKE_SYSTEM_NAME} STREQUAL "kFreeBSD")
+    list(APPEND BOOST_SOURCES
+      ${BOOST_SOURCES_DIR}/libs/thread/src/pthread/once.cpp
+      ${BOOST_SOURCES_DIR}/libs/thread/src/pthread/thread.cpp
+      )
+
+    if ("${CMAKE_SYSTEM_VERSION}" STREQUAL "LinuxStandardBase")
+      add_definitions(-DBOOST_HAS_SCHED_YIELD=1)
+    endif()
+
+  elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
+    list(APPEND BOOST_SOURCES
+      ${BOOST_SOURCES_DIR}/libs/thread/src/win32/tss_dll.cpp
+      ${BOOST_SOURCES_DIR}/libs/thread/src/win32/thread.cpp
+      ${BOOST_SOURCES_DIR}/libs/thread/src/win32/tss_pe.cpp
+      )
+  endif()
+
+
+  ## Boost::filesystem
+
+  list(APPEND BOOST_SOURCES
+    ${BOOST_FILESYSTEM_SOURCES_DIR}/codecvt_error_category.cpp
+    ${BOOST_FILESYSTEM_SOURCES_DIR}/operations.cpp
+    ${BOOST_FILESYSTEM_SOURCES_DIR}/path.cpp
+    ${BOOST_FILESYSTEM_SOURCES_DIR}/path_traits.cpp
+    )
+
+  if (${CMAKE_SYSTEM_NAME} STREQUAL "Darwin")
+    list(APPEND BOOST_SOURCES
+      ${BOOST_SOURCES_DIR}/libs/filesystem/src/utf8_codecvt_facet.cpp
+      )
+  elseif(${CMAKE_SYSTEM_NAME} STREQUAL "Windows")
+    list(APPEND BOOST_SOURCES
+      ${BOOST_FILESYSTEM_SOURCES_DIR}/windows_file_codecvt.cpp
+      )
+  endif()
+
+
+  ## Boost::regex
+
+  aux_source_directory(${BOOST_SOURCES_DIR}/libs/regex/src BOOST_REGEX_SOURCES)
+  list(APPEND BOOST_SOURCES ${BOOST_REGEX_SOURCES})
+
+
+  source_group(ThirdParty\\Boost REGULAR_EXPRESSION ${BOOST_SOURCES_DIR}/.*)
+endif()
+
+
+add_definitions(
+  -DBOOST_HAS_FILESYSTEM_V3=1
+  -DBOOST_HAS_LOCALE=1
+  )
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/CMake/DownloadPackage.cmake	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,156 @@
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+macro(GetUrlFilename TargetVariable Url)
+  string(REGEX REPLACE "^.*/" "" ${TargetVariable} "${Url}")
+endmacro()
+
+
+macro(GetUrlExtension TargetVariable Url)
+  #string(REGEX REPLACE "^.*/[^.]*\\." "" TMP "${Url}")
+  string(REGEX REPLACE "^.*\\." "" TMP "${Url}")
+  string(TOLOWER "${TMP}" "${TargetVariable}")
+endmacro()
+
+
+##
+## Check the existence of the required decompression tools
+##
+
+if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows")
+  find_program(ZIP_EXECUTABLE 7z 
+    PATHS 
+    "$ENV{ProgramFiles}/7-Zip"
+    "$ENV{ProgramW6432}/7-Zip"
+    )
+
+  if (${ZIP_EXECUTABLE} MATCHES "ZIP_EXECUTABLE-NOTFOUND")
+    message(FATAL_ERROR "Please install the '7-zip' software (http://www.7-zip.org/)")
+  endif()
+
+else()
+  find_program(UNZIP_EXECUTABLE unzip)
+  if (${UNZIP_EXECUTABLE} MATCHES "UNZIP_EXECUTABLE-NOTFOUND")
+    message(FATAL_ERROR "Please install the 'unzip' package")
+  endif()
+
+  find_program(TAR_EXECUTABLE tar)
+  if (${TAR_EXECUTABLE} MATCHES "TAR_EXECUTABLE-NOTFOUND")
+    message(FATAL_ERROR "Please install the 'tar' package")
+  endif()
+endif()
+
+
+macro(DownloadPackage MD5 Url TargetDirectory)
+  if (NOT IS_DIRECTORY "${TargetDirectory}")
+    GetUrlFilename(TMP_FILENAME "${Url}")
+
+    set(TMP_PATH "${CMAKE_SOURCE_DIR}/ThirdPartyDownloads/${TMP_FILENAME}")
+    if (NOT EXISTS "${TMP_PATH}")
+      message("Downloading ${Url}")
+
+      # This fixes issue 6: "I think cmake shouldn't download the
+      # packages which are not in the system, it should stop and let
+      # user know."
+      # https://code.google.com/p/orthanc/issues/detail?id=6
+      if (NOT STATIC_BUILD AND NOT ALLOW_DOWNLOADS)
+	message(FATAL_ERROR "CMake is not allowed to download from Internet. Please set the ALLOW_DOWNLOADS option to ON")
+      endif()
+
+      file(DOWNLOAD "${Url}" "${TMP_PATH}" SHOW_PROGRESS EXPECTED_MD5 "${MD5}")
+    else()
+      message("Using local copy of ${Url}")
+    endif()
+
+    GetUrlExtension(TMP_EXTENSION "${Url}")
+    #message(${TMP_EXTENSION})
+    message("Uncompressing ${TMP_FILENAME}")
+
+    if ("${CMAKE_HOST_SYSTEM_NAME}" STREQUAL "Windows")
+      # How to silently extract files using 7-zip
+      # http://superuser.com/questions/331148/7zip-command-line-extract-silently-quietly
+
+      if (("${TMP_EXTENSION}" STREQUAL "gz") OR ("${TMP_EXTENSION}" STREQUAL "tgz"))
+        execute_process(
+          COMMAND ${ZIP_EXECUTABLE} e -y ${TMP_PATH}
+          WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+          RESULT_VARIABLE Failure
+          OUTPUT_QUIET
+          )
+
+        if (Failure)
+          message(FATAL_ERROR "Error while running the uncompression tool")
+        endif()
+
+        if ("${TMP_EXTENSION}" STREQUAL "tgz")
+          string(REGEX REPLACE ".tgz$" ".tar" TMP_FILENAME2 "${TMP_FILENAME}")
+        else()
+          string(REGEX REPLACE ".gz$" "" TMP_FILENAME2 "${TMP_FILENAME}")
+        endif()
+
+        execute_process(
+          COMMAND ${ZIP_EXECUTABLE} x -y ${TMP_FILENAME2}
+          WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+          RESULT_VARIABLE Failure
+          OUTPUT_QUIET
+          )
+      elseif ("${TMP_EXTENSION}" STREQUAL "zip")
+        execute_process(
+          COMMAND ${ZIP_EXECUTABLE} x -y ${TMP_PATH}
+          WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+          RESULT_VARIABLE Failure
+          OUTPUT_QUIET
+          )
+      else()
+        message(FATAL_ERROR "Support your platform here")
+      endif()
+
+    else()
+      if ("${TMP_EXTENSION}" STREQUAL "zip")
+        execute_process(
+          COMMAND sh -c "${UNZIP_EXECUTABLE} -q ${TMP_PATH}"
+          WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+          RESULT_VARIABLE Failure
+        )
+      elseif (("${TMP_EXTENSION}" STREQUAL "gz") OR ("${TMP_EXTENSION}" STREQUAL "tgz"))
+        #message("tar xvfz ${TMP_PATH}")
+        execute_process(
+          COMMAND sh -c "${TAR_EXECUTABLE} xfz ${TMP_PATH}"
+          WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+          RESULT_VARIABLE Failure
+          )
+      elseif ("${TMP_EXTENSION}" STREQUAL "bz2")
+        execute_process(
+          COMMAND sh -c "${TAR_EXECUTABLE} xfj ${TMP_PATH}"
+          WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
+          RESULT_VARIABLE Failure
+          )
+      else()
+        message(FATAL_ERROR "Unknown package format.")
+      endif()
+    endif()
+   
+    if (Failure)
+      message(FATAL_ERROR "Error while running the uncompression tool")
+    endif()
+
+    if (NOT IS_DIRECTORY "${TargetDirectory}")
+      message(FATAL_ERROR "The package was not uncompressed at the proper location. Check the CMake instructions.")
+    endif()
+  endif()
+endmacro()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/CMake/GdcmConfiguration.cmake	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,87 @@
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+if (STATIC_BUILD OR NOT USE_SYSTEM_GDCM)
+  # If using gcc, build GDCM with the "-fPIC" argument to allow its
+  # embedding into the shared library containing the Orthanc plugin
+  if (${CMAKE_SYSTEM_NAME} STREQUAL "Linux")
+    set(Flags -DCMAKE_CXX_FLAGS:STRING=-fPIC -DCMAKE_C_FLAGS:STRING=-fPIC)
+  else()
+  endif()
+
+  if (CMAKE_TOOLCHAIN_FILE)
+    list(APPEND Flags -DCMAKE_TOOLCHAIN_FILE=${CMAKE_TOOLCHAIN_FILE})
+  endif()
+
+  include(ExternalProject)
+  externalproject_add(GDCM
+    URL "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/gdcm-2.4.4.tar.gz"
+    URL_MD5 "5dca87a061c536b6fa377263b7839dcb"
+    CMAKE_ARGS -DCMAKE_BUILD_TYPE:STRING=${CMAKE_BUILD_TYPE} ${Flags}
+    #-DLIBRARY_OUTPUT_PATH=${CMAKE_CURRENT_BINARY_DIR}
+    INSTALL_COMMAND ""  # Skip the install step
+    )
+
+  if(MSVC)
+    set(Suffix ".lib")
+  else()
+    set(Suffix ".a")
+  endif()
+
+  list(GET CMAKE_FIND_LIBRARY_PREFIXES 0 Prefix)
+  set(GDCM_LIBRARIES 
+    ${Prefix}gdcmMSFF${Suffix}
+    ${Prefix}gdcmcharls${Suffix}
+    ${Prefix}gdcmDICT${Suffix}
+    ${Prefix}gdcmDSED${Suffix}
+    ${Prefix}gdcmIOD${Suffix}
+    ${Prefix}gdcmjpeg8${Suffix}
+    ${Prefix}gdcmjpeg12${Suffix}
+    ${Prefix}gdcmjpeg16${Suffix}
+    ${Prefix}gdcmMEXD${Suffix}
+    ${Prefix}gdcmopenjpeg${Suffix}
+    ${Prefix}gdcmzlib${Suffix}
+    ${Prefix}socketxx${Suffix}
+    ${Prefix}gdcmCommon${Suffix}
+    ${Prefix}gdcmexpat${Suffix}
+
+    #${Prefix}gdcmgetopt${Suffix}
+    #${Prefix}gdcmuuid${Suffix}
+    )
+
+  ExternalProject_Get_Property(GDCM binary_dir)
+  include_directories(${binary_dir}/Source/Common)
+  link_directories(${binary_dir}/bin)
+
+  ExternalProject_Get_Property(GDCM source_dir)
+  include_directories(
+    ${source_dir}/Source/Common
+    ${source_dir}/Source/DataDictionary
+    ${source_dir}/Source/MediaStorageAndFileFormat
+    ${source_dir}/Source/DataStructureAndEncodingDefinition
+    )
+
+else()
+  find_package(GDCM REQUIRED)
+  if (GDCM_FOUND)
+    include(${GDCM_USE_FILE})
+    set(GDCM_LIBRARIES gdcmCommon gdcmMSFF)
+  else(GDCM_FOUND)
+    message(FATAL_ERROR "Cannot find GDCM, did you set GDCM_DIR?")
+  endif(GDCM_FOUND)
+endif()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/CMake/GoogleTestConfiguration.cmake	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,57 @@
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+if (USE_GTEST_DEBIAN_SOURCE_PACKAGE)
+  set(GTEST_SOURCES /usr/src/gtest/src/gtest-all.cc)
+  include_directories(/usr/src/gtest)
+
+  if (NOT EXISTS /usr/include/gtest/gtest.h OR
+      NOT EXISTS ${GTEST_SOURCES})
+    message(FATAL_ERROR "Please install the libgtest-dev package")
+  endif()
+
+elseif (STATIC_BUILD OR NOT USE_SYSTEM_GOOGLE_TEST)
+  set(GTEST_SOURCES_DIR ${CMAKE_BINARY_DIR}/gtest-1.7.0)
+  DownloadPackage(
+    "2d6ec8ccdf5c46b05ba54a9fd1d130d7"
+    "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/gtest-1.7.0.zip"
+    "${GTEST_SOURCES_DIR}")
+
+  include_directories(
+    ${GTEST_SOURCES_DIR}/include
+    ${GTEST_SOURCES_DIR}
+    )
+
+  set(GTEST_SOURCES
+    ${GTEST_SOURCES_DIR}/src/gtest-all.cc
+    )
+
+  # https://code.google.com/p/googletest/issues/detail?id=412
+  if (MSVC) # VS2012 does not support tuples correctly yet
+    add_definitions(/D _VARIADIC_MAX=10)
+  endif()
+
+else()
+  include(FindGTest)
+  if (NOT GTEST_FOUND)
+    message(FATAL_ERROR "Unable to find GoogleTest")
+  endif()
+
+  include_directories(${GTEST_INCLUDE_DIRS})
+  link_libraries(${GTEST_LIBRARIES})
+endif()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/CMake/JsonCppConfiguration.cmake	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,47 @@
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+if (STATIC_BUILD OR NOT USE_SYSTEM_JSONCPP)
+  set(JSONCPP_SOURCES_DIR ${CMAKE_BINARY_DIR}/jsoncpp-src-0.6.0-rc2)
+  DownloadPackage(
+    "363e2f4cbd3aeb63bf4e571f377400fb"
+    "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/jsoncpp-src-0.6.0-rc2.tar.gz"
+    "${JSONCPP_SOURCES_DIR}")
+
+  list(APPEND JSONCPP_SOURCES
+    ${JSONCPP_SOURCES_DIR}/src/lib_json/json_reader.cpp
+    ${JSONCPP_SOURCES_DIR}/src/lib_json/json_value.cpp
+    ${JSONCPP_SOURCES_DIR}/src/lib_json/json_writer.cpp
+    )
+
+  include_directories(
+    ${JSONCPP_SOURCES_DIR}/include
+    )
+
+  source_group(ThirdParty\\JsonCpp REGULAR_EXPRESSION ${JSONCPP_SOURCES_DIR}/.*)
+
+else()
+  CHECK_INCLUDE_FILE_CXX(jsoncpp/json/reader.h HAVE_JSONCPP_H)
+  if (NOT HAVE_JSONCPP_H)
+    message(FATAL_ERROR "Please install the libjsoncpp-dev package")
+  endif()
+
+  include_directories(/usr/include/jsoncpp)
+  link_libraries(jsoncpp)
+
+endif()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/CMake/PugixmlConfiguration.cmake	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,24 @@
+if (STATIC_BUILD OR NOT USE_SYSTEM_PUGIXML)
+  set(PUGIXML_SOURCES_DIR ${CMAKE_BINARY_DIR}/pugixml-1.4)
+
+  DownloadPackage(
+    "7c56c91cfe3ecdee248a8e4892ef5781"
+    "http://www.montefiore.ulg.ac.be/~jodogne/Orthanc/ThirdPartyDownloads/pugixml-1.4.tar.gz"
+    "${PUGIXML_SOURCES_DIR}")
+
+  include_directories(
+    ${PUGIXML_SOURCES_DIR}/src
+    )
+
+  set(PUGIXML_SOURCES
+    ${PUGIXML_SOURCES_DIR}/src/pugixml.cpp
+    )
+
+else()
+  CHECK_INCLUDE_FILE_CXX(pugixml.hpp HAVE_PUGIXML_H)
+  if (NOT HAVE_PUGIXML_H)
+    message(FATAL_ERROR "Please install the libpugixml-dev package")
+  endif()
+
+  link_libraries(pugixml)
+endif()
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/MinGWToolchain.cmake	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,37 @@
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+# http://www.vtk.org/Wiki/CmakeMingw
+
+# the name of the target operating system
+set(CMAKE_SYSTEM_NAME Windows)
+
+# which compilers to use for C and C++
+set(CMAKE_C_COMPILER i586-mingw32msvc-gcc)
+set(CMAKE_CXX_COMPILER i586-mingw32msvc-g++)
+set(CMAKE_RC_COMPILER i586-mingw32msvc-windres)
+
+# here is the target environment located
+set(CMAKE_FIND_ROOT_PATH /usr/i586-mingw32msvc)
+
+# adjust the default behaviour of the FIND_XXX() commands:
+# search headers and libraries in the target environment, search 
+# programs in the host environment
+set(CMAKE_FIND_ROOT_PATH_MODE_PROGRAM NEVER)
+set(CMAKE_FIND_ROOT_PATH_MODE_LIBRARY ONLY)
+set(CMAKE_FIND_ROOT_PATH_MODE_INCLUDE ONLY)
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Resources/VersionScript.map	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,12 @@
+# This is a version-script for Orthanc plugins
+
+{
+global:
+  OrthancPluginInitialize;
+  OrthancPluginFinalize;
+  OrthancPluginGetName;
+  OrthancPluginGetVersion;
+
+local:
+  *;
+};
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Samples/SendStow.py	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,67 @@
+#!/usr/bin/python
+
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+import email
+import requests
+import sys
+import json
+from email.mime.multipart import MIMEMultipart
+from email.mime.application import MIMEApplication
+
+if len(sys.argv) < 2:
+    print('Usage: %s <StowUri> <file>...' % sys.argv[0])
+    print('')
+    print('Example: %s http://localhost:8042/stow-rs/studies hello.dcm world.dcm' % sys.argv[0])
+    sys.exit(-1)
+
+URL = sys.argv[1]
+
+related = MIMEMultipart('related')
+related.set_boundary('hello')
+
+for i in range(2, len(sys.argv)):
+    try:
+        with open(sys.argv[i], 'rb') as f:
+            dicom = MIMEApplication(f.read(), 'dicom', email.encoders.encode_noop)
+            related.attach(dicom)
+    except:
+        print('Ignoring directory %s' % sys.argv[i])
+
+headers = dict(related.items())
+body = related.as_string()
+
+# Discard the header
+body = body.split('\n\n', 1)[1]
+
+headers['Content-Type'] = 'multipart/related; type=application/dicom; boundary=%s' % related.get_boundary()
+headers['Accept'] = 'application/json'
+
+r = requests.post(URL, data=body, headers=headers)
+j = json.loads(r.text)
+
+# Loop over the successful instances
+print('\nWADO-RS URL of the uploaded instances:')
+for instance in j['00081199']['Value']:
+    if '00081190' in instance:  # This instance has not been discarded
+        url = instance['00081190']['Value'][0]
+        print(url)
+
+print('\nWADO-RS URL of the study:')
+print(j['00081190']['Value'][0])
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/Samples/WadoRetrieveStudy.py	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,42 @@
+#!/usr/bin/python
+
+# Orthanc - A Lightweight, RESTful DICOM Store
+# Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+# Department, University Hospital of Liege, Belgium
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero 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
+# Affero General Public License for more details.
+# 
+# You should have received a copy of the GNU Affero General Public License
+# along with this program. If not, see <http://www.gnu.org/licenses/>.
+
+
+import email
+import urllib2
+import sys
+
+if len(sys.argv) != 2:
+    print('Usage: %s <Uri>' % sys.argv[0])
+    print('')
+    print('Example: %s http://localhost:8042/dicom-web/studies/1.3.51.0.1.1.192.168.29.133.1681753.1681732' % sys.argv[0])
+    sys.exit(-1)
+
+answer = urllib2.urlopen(sys.argv[1])
+s = str(answer.info()) + "\n" + answer.read()
+
+msg = email.message_from_string(s)
+
+for i, part in enumerate(msg.walk(), 1):
+    filename = 'wado-%06d.dcm' % i
+    dicom = part.get_payload(decode = True)
+    if dicom != None:
+        print('Storing DICOM file: %s' % filename)
+        with open(filename, 'wb') as f:
+            f.write(str(dicom))
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/UnitTestsSources/UnitTestsMain.cpp	Fri Mar 13 16:06:05 2015 +0100
@@ -0,0 +1,56 @@
+/**
+ * Orthanc - A Lightweight, RESTful DICOM Store
+ * Copyright (C) 2012-2015 Sebastien Jodogne, Medical Physics
+ * Department, University Hospital of Liege, Belgium
+ *
+ * This program is free software: you can redistribute it and/or
+ * modify it under the terms of the GNU Affero 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
+ * Affero General Public License for more details.
+ * 
+ * You should have received a copy of the GNU Affero General Public License
+ * along with this program. If not, see <http://www.gnu.org/licenses/>.
+ **/
+
+
+#include <gtest/gtest.h>
+#include <boost/lexical_cast.hpp>
+
+#include "../Core/Toolbox.h"
+#include "../Plugin/Plugin.h"
+
+using namespace OrthancPlugins;
+
+
+
+TEST(ContentType, Parse)
+{
+  std::string c;
+  std::map<std::string, std::string> a;
+
+  ParseContentType(c, a, "Multipart/Related; TYPE=Application/Dicom; Boundary=heLLO");
+  ASSERT_EQ(c, "multipart/related");
+  ASSERT_EQ(2, a.size());
+  ASSERT_EQ(a["type"], "Application/Dicom");
+  ASSERT_EQ(a["boundary"], "heLLO");
+
+  ParseContentType(c, a, "");
+  ASSERT_TRUE(c.empty());
+  ASSERT_EQ(0, a.size());  
+
+  ParseContentType(c, a, "multipart/related");
+  ASSERT_EQ(c, "multipart/related");
+  ASSERT_EQ(0, a.size());
+}
+
+
+int main(int argc, char **argv)
+{
+  ::testing::InitGoogleTest(&argc, argv);
+  return RUN_ALL_TESTS();
+}