diff --git a/.gitignore b/.gitignore new file mode 100644 index 00000000..31402b70 --- /dev/null +++ b/.gitignore @@ -0,0 +1,6 @@ +target +.cache +.classpath +.project +.scala_dependencies +.settings diff --git a/LICENSE b/LICENSE new file mode 100644 index 00000000..2bb9ad24 --- /dev/null +++ b/LICENSE @@ -0,0 +1,176 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS \ No newline at end of file diff --git a/LICENSE_CDDL_1.0 b/LICENSE_CDDL_1.0 new file mode 100644 index 00000000..d7e39667 --- /dev/null +++ b/LICENSE_CDDL_1.0 @@ -0,0 +1,93 @@ +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0 1. + +Definitions. + +1.1. Contributor means each individual or entity that creates or contributes to the creation of Modifications. + +1.2. Contributor Version means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor. + +1.3. Covered Software means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof. + +1.4. Executable means the Covered Software in any form other than Source Code. + +1.5. Initial Developer means the individual or entity that first makes Original Software available under this License. + +1.6. Larger Work means a work which combines Covered Software or portions thereof with code not governed by the terms of this License. + +1.7. License means this document. + +1.8. Licensable means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein. + +1.9. Modifications means the Source Code and Executable form of any of the following: A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications; B. Any new file that contains any part of the Original Software or previous Modification; or C. Any new file that is contributed or otherwise made available under the terms of this License. + +1.10. Original Software means the Source Code and Executable form of computer software code that is originally released under this License. + +1.11. Patent Claims means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor. + +1.12. Source Code means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code. + +1.13. You (or Your) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, You includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, control means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. + +2. License Grants. + + 2.1. The Initial Developer Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and + +(b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof); + + (c) The licenses granted in Sections 2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License; + + (d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for code that You delete from the Original Software, or (2) for infringements caused by: (i) the modification of the Original Software, or (ii) the combination of the Original Software with other software or devices. + +2.2. Contributor Grant. Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: + +(a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and + +(b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1) Modifications made by that Contributor (or portions thereof); and (2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination). + +(c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party. + +(d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for any code that Contributor has deleted from the Contributor Version; (2) for infringements caused by: (i) third party modifications of Contributor Version, or (ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3) under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor. + +3. Distribution Obligations. + +3.1. Availability of Source Code. Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange. + +3.2. Modifications. The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License. + +3.3. Required Notices. You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer. + +3.4. Application of Additional Terms. You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipients rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer. + +3.5. Distribution of Executable Versions. You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipients rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer. + +3.6. Larger Works. You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software. + +4. Versions of the License. + +4.1. New Versions. Sun Microsystems, Inc. is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License. + +4.2. Effect of New Versions. You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward. + +4.3. Modified Versions. When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a) rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b) otherwise make it clear that the license contains terms which differ from this License. + +5. DISCLAIMER OF WARRANTY. COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN AS IS BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +6. TERMINATION. + +6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive. + +6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as Participant) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant. + +6.3. In the event of termination under Sections 6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination. + +7. LIMITATION OF LIABILITY. UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOST PROFITS, LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTYS NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +8. U.S. GOVERNMENT END USERS. The Covered Software is a commercial item, as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of commercial computer software (as that term is defined at 48 C.F.R. 252.227-7014(a)(1)) and commercial computer software documentation as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License. + +9. MISCELLANEOUS. This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdictions conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneys fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software. + +10. RESPONSIBILITY FOR CLAIMS. As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability. + +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) The code released under the CDDL shall be governed by the laws of the State of California (excluding conflict-of-law provisions). Any litigation relating to this License shall be subject to the jurisdiction of the Federal Courts of the Northern District of California and the state courts of the State of California, with venue lying in Santa Clara County, California. \ No newline at end of file diff --git a/LICENSE_CDDL_1.1 b/LICENSE_CDDL_1.1 new file mode 100644 index 00000000..a8f568d7 --- /dev/null +++ b/LICENSE_CDDL_1.1 @@ -0,0 +1,133 @@ +COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL)Version 1.1 + +1. Definitions. + + 1.1. “Contributor” means each individual or entity that creates or contributes to the creation of Modifications. + + 1.2. “Contributor Version” means the combination of the Original Software, prior Modifications used by a Contributor (if any), and the Modifications made by that particular Contributor. + + 1.3. “Covered Software” means (a) the Original Software, or (b) Modifications, or (c) the combination of files containing Original Software with files containing Modifications, in each case including portions thereof. + + 1.4. “Executable” means the Covered Software in any form other than Source Code. + + 1.5. “Initial Developer” means the individual or entity that first makes Original Software available under this License. + + 1.6. “Larger Work” means a work which combines Covered Software or portions thereof with code not governed by the terms of this License. + + 1.7. “License” means this document. + + 1.8. “Licensable” means having the right to grant, to the maximum extent possible, whether at the time of the initial grant or subsequently acquired, any and all of the rights conveyed herein. + + 1.9. “Modifications” means the Source Code and Executable form of any of the following: + + A. Any file that results from an addition to, deletion from or modification of the contents of a file containing Original Software or previous Modifications; + + B. Any new file that contains any part of the Original Software or previous Modification; or + + C. Any new file that is contributed or otherwise made available under the terms of this License. + + 1.10. “Original Software” means the Source Code and Executable form of computer software code that is originally released under this License. + + 1.11. “Patent Claims” means any patent claim(s), now owned or hereafter acquired, including without limitation, method, process, and apparatus claims, in any patent Licensable by grantor. + + 1.12. “Source Code” means (a) the common form of computer software code in which modifications are made and (b) associated documentation included in or with such code. + + 1.13. “You” (or “Your”) means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, “You” includes any entity which controls, is controlled by, or is under common control with You. For purposes of this definition, “control” means (a) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (b) ownership of more than fifty percent (50%) of the outstanding shares or beneficial ownership of such entity. + +2. License Grants. + + 2.1. The Initial Developer Grant. + + Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, the Initial Developer hereby grants You a world-wide, royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than patent or trademark) Licensable by Initial Developer, to use, reproduce, modify, display, perform, sublicense and distribute the Original Software (or portions thereof), with or without Modifications, and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using or selling of Original Software, to make, have made, use, practice, sell, and offer for sale, and/or otherwise dispose of the Original Software (or portions thereof). + + (c) The licenses granted in Sections 2.1(a) and (b) are effective on the date Initial Developer first distributes or otherwise makes the Original Software available to a third party under the terms of this License. + + (d) Notwithstanding Section 2.1(b) above, no patent license is granted: (1) for code that You delete from the Original Software, or (2) for infringements caused by: (i) the modification of the Original Software, or (ii) the combination of the Original Software with other software or devices. + + 2.2. Contributor Grant. + + Conditioned upon Your compliance with Section 3.1 below and subject to third party intellectual property claims, each Contributor hereby grants You a world-wide, royalty-free, non-exclusive license: + + (a) under intellectual property rights (other than patent or trademark) Licensable by Contributor to use, reproduce, modify, display, perform, sublicense and distribute the Modifications created by such Contributor (or portions thereof), either on an unmodified basis, with other Modifications, as Covered Software and/or as part of a Larger Work; and + + (b) under Patent Claims infringed by the making, using, or selling of Modifications made by that Contributor either alone and/or in combination with its Contributor Version (or portions of such combination), to make, use, sell, offer for sale, have made, and/or otherwise dispose of: (1) Modifications made by that Contributor (or portions thereof); and (2) the combination of Modifications made by that Contributor with its Contributor Version (or portions of such combination). + + (c) The licenses granted in Sections 2.2(a) and 2.2(b) are effective on the date Contributor first distributes or otherwise makes the Modifications available to a third party. + + (d) Notwithstanding Section 2.2(b) above, no patent license is granted: (1) for any code that Contributor has deleted from the Contributor Version; (2) for infringements caused by: (i) third party modifications of Contributor Version, or (ii) the combination of Modifications made by that Contributor with other software (except as part of the Contributor Version) or other devices; or (3) under Patent Claims infringed by Covered Software in the absence of Modifications made by that Contributor. + +3. Distribution Obligations. + + 3.1. Availability of Source Code. + + Any Covered Software that You distribute or otherwise make available in Executable form must also be made available in Source Code form and that Source Code form must be distributed only under the terms of this License. You must include a copy of this License with every copy of the Source Code form of the Covered Software You distribute or otherwise make available. You must inform recipients of any such Covered Software in Executable form as to how they can obtain such Covered Software in Source Code form in a reasonable manner on or through a medium customarily used for software exchange. + + 3.2. Modifications. + + The Modifications that You create or to which You contribute are governed by the terms of this License. You represent that You believe Your Modifications are Your original creation(s) and/or You have sufficient rights to grant the rights conveyed by this License. + + 3.3. Required Notices. + + You must include a notice in each of Your Modifications that identifies You as the Contributor of the Modification. You may not remove or alter any copyright, patent or trademark notices contained within the Covered Software, or any notices of licensing or any descriptive text giving attribution to any Contributor or the Initial Developer. + + 3.4. Application of Additional Terms. + + You may not offer or impose any terms on any Covered Software in Source Code form that alters or restricts the applicable version of this License or the recipients' rights hereunder. You may choose to offer, and to charge a fee for, warranty, support, indemnity or liability obligations to one or more recipients of Covered Software. However, you may do so only on Your own behalf, and not on behalf of the Initial Developer or any Contributor. You must make it absolutely clear that any such warranty, support, indemnity or liability obligation is offered by You alone, and You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of warranty, support, indemnity or liability terms You offer. + + 3.5. Distribution of Executable Versions. + + You may distribute the Executable form of the Covered Software under the terms of this License or under the terms of a license of Your choice, which may contain terms different from this License, provided that You are in compliance with the terms of this License and that the license for the Executable form does not attempt to limit or alter the recipient's rights in the Source Code form from the rights set forth in this License. If You distribute the Covered Software in Executable form under a different license, You must make it absolutely clear that any terms which differ from this License are offered by You alone, not by the Initial Developer or Contributor. You hereby agree to indemnify the Initial Developer and every Contributor for any liability incurred by the Initial Developer or such Contributor as a result of any such terms You offer. + + 3.6. Larger Works. + + You may create a Larger Work by combining Covered Software with other code not governed by the terms of this License and distribute the Larger Work as a single product. In such a case, You must make sure the requirements of this License are fulfilled for the Covered Software. + +4. Versions of the License. + + 4.1. New Versions. + + Oracle is the initial license steward and may publish revised and/or new versions of this License from time to time. Each version will be given a distinguishing version number. Except as provided in Section 4.3, no one other than the license steward has the right to modify this License. + + 4.2. Effect of New Versions. + + You may always continue to use, distribute or otherwise make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. If the Initial Developer includes a notice in the Original Software prohibiting it from being distributed or otherwise made available under any subsequent version of the License, You must distribute and make the Covered Software available under the terms of the version of the License under which You originally received the Covered Software. Otherwise, You may also choose to use, distribute or otherwise make the Covered Software available under the terms of any subsequent version of the License published by the license steward. + + 4.3. Modified Versions. + + When You are an Initial Developer and You want to create a new license for Your Original Software, You may create and use a modified version of this License if You: (a) rename the license and remove any references to the name of the license steward (except to note that the license differs from this License); and (b) otherwise make it clear that the license contains terms which differ from this License. + +5. DISCLAIMER OF WARRANTY. + + COVERED SOFTWARE IS PROVIDED UNDER THIS LICENSE ON AN “AS IS” BASIS, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, WITHOUT LIMITATION, WARRANTIES THAT THE COVERED SOFTWARE IS FREE OF DEFECTS, MERCHANTABLE, FIT FOR A PARTICULAR PURPOSE OR NON-INFRINGING. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE COVERED SOFTWARE IS WITH YOU. SHOULD ANY COVERED SOFTWARE PROVE DEFECTIVE IN ANY RESPECT, YOU (NOT THE INITIAL DEVELOPER OR ANY OTHER CONTRIBUTOR) ASSUME THE COST OF ANY NECESSARY SERVICING, REPAIR OR CORRECTION. THIS DISCLAIMER OF WARRANTY CONSTITUTES AN ESSENTIAL PART OF THIS LICENSE. NO USE OF ANY COVERED SOFTWARE IS AUTHORIZED HEREUNDER EXCEPT UNDER THIS DISCLAIMER. + +6. TERMINATION. + + 6.1. This License and the rights granted hereunder will terminate automatically if You fail to comply with terms herein and fail to cure such breach within 30 days of becoming aware of the breach. Provisions which, by their nature, must remain in effect beyond the termination of this License shall survive. + + 6.2. If You assert a patent infringement claim (excluding declaratory judgment actions) against Initial Developer or a Contributor (the Initial Developer or Contributor against whom You assert such claim is referred to as “Participant”) alleging that the Participant Software (meaning the Contributor Version where the Participant is a Contributor or the Original Software where the Participant is the Initial Developer) directly or indirectly infringes any patent, then any and all rights granted directly or indirectly to You by such Participant, the Initial Developer (if the Initial Developer is not the Participant) and all Contributors under Sections 2.1 and/or 2.2 of this License shall, upon 60 days notice from Participant terminate prospectively and automatically at the expiration of such 60 day notice period, unless if within such 60 day period You withdraw Your claim with respect to the Participant Software against such Participant either unilaterally or pursuant to a written agreement with Participant. + + 6.3. If You assert a patent infringement claim against Participant alleging that the Participant Software directly or indirectly infringes any patent where such claim is resolved (such as by license or settlement) prior to the initiation of patent infringement litigation, then the reasonable value of the licenses granted by such Participant under Sections 2.1 or 2.2 shall be taken into account in determining the amount or value of any payment or license. + + 6.4. In the event of termination under Sections 6.1 or 6.2 above, all end user licenses that have been validly granted by You or any distributor hereunder prior to termination (excluding licenses granted to You by any distributor) shall survive termination. + +7. LIMITATION OF LIABILITY. + + UNDER NO CIRCUMSTANCES AND UNDER NO LEGAL THEORY, WHETHER TORT (INCLUDING NEGLIGENCE), CONTRACT, OR OTHERWISE, SHALL YOU, THE INITIAL DEVELOPER, ANY OTHER CONTRIBUTOR, OR ANY DISTRIBUTOR OF COVERED SOFTWARE, OR ANY SUPPLIER OF ANY OF SUCH PARTIES, BE LIABLE TO ANY PERSON FOR ANY INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES OF ANY CHARACTER INCLUDING, WITHOUT LIMITATION, DAMAGES FOR LOSS OF GOODWILL, WORK STOPPAGE, COMPUTER FAILURE OR MALFUNCTION, OR ANY AND ALL OTHER COMMERCIAL DAMAGES OR LOSSES, EVEN IF SUCH PARTY SHALL HAVE BEEN INFORMED OF THE POSSIBILITY OF SUCH DAMAGES. THIS LIMITATION OF LIABILITY SHALL NOT APPLY TO LIABILITY FOR DEATH OR PERSONAL INJURY RESULTING FROM SUCH PARTY'S NEGLIGENCE TO THE EXTENT APPLICABLE LAW PROHIBITS SUCH LIMITATION. SOME JURISDICTIONS DO NOT ALLOW THE EXCLUSION OR LIMITATION OF INCIDENTAL OR CONSEQUENTIAL DAMAGES, SO THIS EXCLUSION AND LIMITATION MAY NOT APPLY TO YOU. + +8. U.S. GOVERNMENT END USERS. + + The Covered Software is a “commercial item,” as that term is defined in 48 C.F.R. 2.101 (Oct. 1995), consisting of “commercial computer software” (as that term is defined at 48 C.F.R. § 252.227-7014(a)(1)) and “commercial computer software documentation” as such terms are used in 48 C.F.R. 12.212 (Sept. 1995). Consistent with 48 C.F.R. 12.212 and 48 C.F.R. 227.7202-1 through 227.7202-4 (June 1995), all U.S. Government End Users acquire Covered Software with only those rights set forth herein. This U.S. Government Rights clause is in lieu of, and supersedes, any other FAR, DFAR, or other clause or provision that addresses Government rights in computer software under this License. + +9. MISCELLANEOUS. + + This License represents the complete agreement concerning subject matter hereof. If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. This License shall be governed by the law of the jurisdiction specified in a notice contained within the Original Software (except to the extent applicable law, if any, provides otherwise), excluding such jurisdiction's conflict-of-law provisions. Any litigation relating to this License shall be subject to the jurisdiction of the courts located in the jurisdiction and venue specified in a notice contained within the Original Software, with the losing party responsible for costs, including, without limitation, court costs and reasonable attorneys' fees and expenses. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any law or regulation which provides that the language of a contract shall be construed against the drafter shall not apply to this License. You agree that You alone are responsible for compliance with the United States export administration regulations (and the export control laws and regulation of any other countries) when You use, distribute or otherwise make available any Covered Software. + +10. RESPONSIBILITY FOR CLAIMS. + + As between Initial Developer and the Contributors, each party is responsible for claims and damages arising, directly or indirectly, out of its utilization of rights under this License and You agree to work with Initial Developer and Contributors to distribute such responsibility on an equitable basis. Nothing herein is intended or shall be deemed to constitute any admission of liability. + +NOTICE PURSUANT TO SECTION 9 OF THE COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) \ No newline at end of file diff --git a/LICENSE_EPL_1.0 b/LICENSE_EPL_1.0 new file mode 100644 index 00000000..3d967aee --- /dev/null +++ b/LICENSE_EPL_1.0 @@ -0,0 +1,70 @@ +Eclipse Public License - v 1.0 + +THE ACCOMPANYING PROGRAM IS PROVIDED UNDER THE TERMS OF THIS ECLIPSE PUBLIC LICENSE ("AGREEMENT"). ANY USE, REPRODUCTION OR DISTRIBUTION OF THE PROGRAM CONSTITUTES RECIPIENT'S ACCEPTANCE OF THIS AGREEMENT. + +1. DEFINITIONS + +"Contribution" means: + +a) in the case of the initial Contributor, the initial code and documentation distributed under this Agreement, and +b) in the case of each subsequent Contributor: +i) changes to the Program, and +ii) additions to the Program; +where such changes and/or additions to the Program originate from and are distributed by that particular Contributor. A Contribution 'originates' from a Contributor if it was added to the Program by such Contributor itself or anyone acting on such Contributor's behalf. Contributions do not include additions to the Program which: (i) are separate modules of software distributed in conjunction with the Program under their own license agreement, and (ii) are not derivative works of the Program. +"Contributor" means any person or entity that distributes the Program. + +"Licensed Patents" mean patent claims licensable by a Contributor which are necessarily infringed by the use or sale of its Contribution alone or when combined with the Program. + +"Program" means the Contributions distributed in accordance with this Agreement. + +"Recipient" means anyone who receives the Program under this Agreement, including all Contributors. + +2. GRANT OF RIGHTS + +a) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free copyright license to reproduce, prepare derivative works of, publicly display, publicly perform, distribute and sublicense the Contribution of such Contributor, if any, and such derivative works, in source code and object code form. +b) Subject to the terms of this Agreement, each Contributor hereby grants Recipient a non-exclusive, worldwide, royalty-free patent license under Licensed Patents to make, use, sell, offer to sell, import and otherwise transfer the Contribution of such Contributor, if any, in source code and object code form. This patent license shall apply to the combination of the Contribution and the Program if, at the time the Contribution is added by the Contributor, such addition of the Contribution causes such combination to be covered by the Licensed Patents. The patent license shall not apply to any other combinations which include the Contribution. No hardware per se is licensed hereunder. +c) Recipient understands that although each Contributor grants the licenses to its Contributions set forth herein, no assurances are provided by any Contributor that the Program does not infringe the patent or other intellectual property rights of any other entity. Each Contributor disclaims any liability to Recipient for claims brought by any other entity based on infringement of intellectual property rights or otherwise. As a condition to exercising the rights and licenses granted hereunder, each Recipient hereby assumes sole responsibility to secure any other intellectual property rights needed, if any. For example, if a third party patent license is required to allow Recipient to distribute the Program, it is Recipient's responsibility to acquire that license before distributing the Program. +d) Each Contributor represents that to its knowledge it has sufficient copyright rights in its Contribution, if any, to grant the copyright license set forth in this Agreement. +3. REQUIREMENTS + +A Contributor may choose to distribute the Program in object code form under its own license agreement, provided that: + +a) it complies with the terms and conditions of this Agreement; and +b) its license agreement: +i) effectively disclaims on behalf of all Contributors all warranties and conditions, express and implied, including warranties or conditions of title and non-infringement, and implied warranties or conditions of merchantability and fitness for a particular purpose; +ii) effectively excludes on behalf of all Contributors all liability for damages, including direct, indirect, special, incidental and consequential damages, such as lost profits; +iii) states that any provisions which differ from this Agreement are offered by that Contributor alone and not by any other party; and +iv) states that source code for the Program is available from such Contributor, and informs licensees how to obtain it in a reasonable manner on or through a medium customarily used for software exchange. +When the Program is made available in source code form: + +a) it must be made available under this Agreement; and +b) a copy of this Agreement must be included with each copy of the Program. +Contributors may not remove or alter any copyright notices contained within the Program. + +Each Contributor must identify itself as the originator of its Contribution, if any, in a manner that reasonably allows subsequent Recipients to identify the originator of the Contribution. + +4. COMMERCIAL DISTRIBUTION + +Commercial distributors of software may accept certain responsibilities with respect to end users, business partners and the like. While this license is intended to facilitate the commercial use of the Program, the Contributor who includes the Program in a commercial product offering should do so in a manner which does not create potential liability for other Contributors. Therefore, if a Contributor includes the Program in a commercial product offering, such Contributor ("Commercial Contributor") hereby agrees to defend and indemnify every other Contributor ("Indemnified Contributor") against any losses, damages and costs (collectively "Losses") arising from claims, lawsuits and other legal actions brought by a third party against the Indemnified Contributor to the extent caused by the acts or omissions of such Commercial Contributor in connection with its distribution of the Program in a commercial product offering. The obligations in this section do not apply to any claims or Losses relating to any actual or alleged intellectual property infringement. In order to qualify, an Indemnified Contributor must: a) promptly notify the Commercial Contributor in writing of such claim, and b) allow the Commercial Contributor to control, and cooperate with the Commercial Contributor in, the defense and any related settlement negotiations. The Indemnified Contributor may participate in any such claim at its own expense. + +For example, a Contributor might include the Program in a commercial product offering, Product X. That Contributor is then a Commercial Contributor. If that Commercial Contributor then makes performance claims, or offers warranties related to Product X, those performance claims and warranties are such Commercial Contributor's responsibility alone. Under this section, the Commercial Contributor would have to defend claims against the other Contributors related to those performance claims and warranties, and if a court requires any other Contributor to pay any damages as a result, the Commercial Contributor must pay those damages. + +5. NO WARRANTY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement , including but not limited to the risks and costs of program errors, compliance with applicable laws, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. + +6. DISCLAIMER OF LIABILITY + +EXCEPT AS EXPRESSLY SET FORTH IN THIS AGREEMENT, NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES. + +7. GENERAL + +If any provision of this Agreement is invalid or unenforceable under applicable law, it shall not affect the validity or enforceability of the remainder of the terms of this Agreement, and without further action by the parties hereto, such provision shall be reformed to the minimum extent necessary to make such provision valid and enforceable. + +If Recipient institutes patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Program itself (excluding combinations of the Program with other software or hardware) infringes such Recipient's patent(s), then such Recipient's rights granted under Section 2(b) shall terminate as of the date such litigation is filed. + +All Recipient's rights under this Agreement shall terminate if it fails to comply with any of the material terms or conditions of this Agreement and does not cure such failure in a reasonable period of time after becoming aware of such noncompliance. If all Recipient's rights under this Agreement terminate, Recipient agrees to cease use and distribution of the Program as soon as reasonably practicable. However, Recipient's obligations under this Agreement and any licenses granted by Recipient relating to the Program shall continue and survive. + +Everyone is permitted to copy and distribute copies of this Agreement, but in order to avoid inconsistency the Agreement is copyrighted and may only be modified in the following manner. The Agreement Steward reserves the right to publish new versions (including revisions) of this Agreement from time to time. No one other than the Agreement Steward has the right to modify this Agreement. The Eclipse Foundation is the initial Agreement Steward. The Eclipse Foundation may assign the responsibility to serve as the Agreement Steward to a suitable separate entity. Each new version of the Agreement will be given a distinguishing version number. The Program (including Contributions) may always be distributed subject to the version of the Agreement under which it was received. In addition, after a new version of the Agreement is published, Contributor may elect to distribute the Program (including its Contributions) under the new version. Except as expressly stated in Sections 2(a) and 2(b) above, Recipient receives no rights or licenses to the intellectual property of any Contributor under this Agreement, whether expressly, by implication, estoppel or otherwise. All rights in the Program not expressly granted under this Agreement are reserved. + +This Agreement is governed by the laws of the State of New York and the intellectual property laws of the United States of America. No party to this Agreement will bring a legal action under this Agreement more than one year after the cause of action arose. Each party waives its rights to a jury trial in any resulting litigation. \ No newline at end of file diff --git a/LICENSE_MIT b/LICENSE_MIT new file mode 100644 index 00000000..e14c3714 --- /dev/null +++ b/LICENSE_MIT @@ -0,0 +1,17 @@ +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. \ No newline at end of file diff --git a/LICENSE_SCALA b/LICENSE_SCALA new file mode 100644 index 00000000..550830fe --- /dev/null +++ b/LICENSE_SCALA @@ -0,0 +1,33 @@ +Copyright (c) 2002-2011 EPFL, Lausanne, unless otherwise specified. +All rights reserved. + +This software was developed by the Programming Methods Laboratory of the +Swiss Federal Institute of Technology (EPFL), Lausanne, Switzerland. + +Permission to use, copy, modify, and distribute this software in source +or binary form for any purpose with or without fee is hereby granted, +provided that the following conditions are met: + + 1. Redistributions of source code must retain the above copyright + notice, this list of conditions and the following disclaimer. + + 2. Redistributions in binary form must reproduce the above copyright + notice, this list of conditions and the following disclaimer in the + documentation and/or other materials provided with the distribution. + + 3. Neither the name of the EPFL nor the names of its contributors + may be used to endorse or promote products derived from this + software without specific prior written permission. + + +THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND +ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY +OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF +SUCH DAMAGE. \ No newline at end of file diff --git a/NOTICE b/NOTICE new file mode 100644 index 00000000..0e686945 --- /dev/null +++ b/NOTICE @@ -0,0 +1,61 @@ +Digipost API Client + +Copyright 2011 Posten Norge AS. All Rights Reserved. + +This product includes software developed by Posten Norge AS. - https://www.posten.no/ +Licensed under Apache 2 - http://www.apache.org/licenses/LICENSE-2.0.html + + +This software includes third party software subject to the following licenses: + +********************************************************************** +APACHE 2 - LICENSE - http://www.apache.org/licenses/LICENSE-2.0.html +********************************************************************** +springframework:3.0.5.RELEASE - http://www.springsource.org +commons-codec:1.2 - http://commons.apache.org/codec +commons-httpclient:3.1 - http://hc.apache.org/httpclient-3.x/ +commons-io:2.0.1 - http://commons.apache.org/io/ +commons-lang:2.6 - http://commons.apache.org/lang/ +commons-logging:1.0.4 - http://commons.apache.org/logging/ +joda-time:1.6.2 - http://joda-time.sourceforge.net/ +castor:1.3.1 - http://www.castor.org/ + + +********************************************************************** +CDDL 1.0 - LICENSE_CDDL_1.0 - https://glassfish.dev.java.net/public/CDDLv1.0.html +********************************************************************** +activation-1.1.jar - http://java.sun.com/products/archive/javabeans/jaf11.html +stax-api-1.0-2.jar - http://stax.codehaus.org/Home + + +********************************************************************** +CDDL 1.1 - LICENSE_CDDL_1.1 - http://glassfish.java.net/public/CDDL+GPL_1_1.html +********************************************************************** +jaxb:2.2.2 - http://jaxb.java.net/ +jersey:1.7 - http://jersey.java.net/ +jersey-apache-client:1.9 - http://jersey.java.net/ + + +********************************************************************** +MIT - LICENSE_MIT - http://opensource.org/licenses/mit-license.php +********************************************************************** +bouncycastle:1.46 - http://www.bouncycastle.org/ +slf4j:1.6.1 - http://www.slf4j.org/ + + +********************************************************************** +SCALA - LICENSE_SCALA - http://www.scala-lang.org/node/146 +********************************************************************** +scala:2.9.1 - http://www.scala-lang.org/ + + +********************************************************************** +EPL 1.0 - LICENSE_EPL_1.0 - http://www.eclipse.org/legal/epl-v10.html +********************************************************************** +logback:0.9.28 - http://logback.qos.ch/ + + +********************************************************************** +PUBLIC DOMAIN - http://aopalliance.sourceforge.net/ +********************************************************************** +aopalliance:1.0 - http://aopalliance.sourceforge.net/ \ No newline at end of file diff --git a/assembly.xml b/assembly.xml new file mode 100644 index 00000000..2ac5c513 --- /dev/null +++ b/assembly.xml @@ -0,0 +1,56 @@ + + + non-dev + + zip + + + + ${project.build.directory}/appassembler + / + 0755 + 0755 + + + ${project.build.directory}/ + + dpost-api-client-${project.version}-javadoc.jar + dpost-api-client-${project.version}-sources.jar + + / + 0755 + 0755 + + + ${project.build.directory}/../../dpost-xsd/target + + dpost-xsd-${project.version}-sources.jar + + / + 0755 + 0755 + + + ${basedir} + + LICENSE* + NOTICE + + / + 0644 + 0755 + + + ${basedir} + + config.properties + + /bin + 0644 + 0755 + + + \ No newline at end of file diff --git a/config.properties b/config.properties new file mode 100644 index 00000000..70ef2d5c --- /dev/null +++ b/config.properties @@ -0,0 +1,20 @@ +# +# Copyright (C) Posten Norge AS +# +# Licensed under the Apache License, Version 2.0 (the "License"); +# you may not use this file except in compliance with the License. +# You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, software +# distributed under the License is distributed on an "AS IS" BASIS, +# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +# See the License for the specific language governing permissions and +# limitations under the License. +# + +endpoint=https://api.digipost.no +sertifikat= +sertifikatpassord= +brukerid= \ No newline at end of file diff --git a/pom.xml b/pom.xml new file mode 100644 index 00000000..8e1834ef --- /dev/null +++ b/pom.xml @@ -0,0 +1,397 @@ + + + 4.0.0 + + dpost-api-client + 1.11-SNAPSHOT + jar + ${project.artifactId} + ${project.artifactId} + + + no.posten.dpost + dpost-super-pom + 1.1 + + + + + + + org.springframework + spring-oxm + 3.0.5.RELEASE + + + commons-logging + commons-logging + + + + + aopalliance + aopalliance + 1.0 + + + commons-lang + commons-lang + 2.6 + + + commons-httpclient + commons-httpclient + 3.1 + + + commons-logging + commons-logging + + + + + + + + + + no.posten.dpost + dpost-xsd + ${project.version} + + + org.slf4j + slf4j-api + 1.6.1 + + + ch.qos.logback + logback-classic + 0.9.28 + + + com.sun.jersey + jersey-client + 1.7 + + + commons-io + commons-io + 2.0.1 + + + commons-httpclient + commons-httpclient + + + javax.xml.bind + jaxb-api + 2.2.2 + + + com.sun.xml.bind + jaxb-impl + 2.2.2 + + + org.bouncycastle + bcprov-jdk16 + 1.46 + + + junit + junit + 4.8.2 + test + + + org.mockito + mockito-all + 1.8.5 + test + + + org.scala-lang + scala-library + 2.9.1 + + + + com.sun.jersey.contribs + jersey-apache-client + 1.9 + + + + + + + + maven-compiler-plugin + 2.3.2 + + 1.6 + 1.6 + utf-8 + + + + com.mycila.maven-license-plugin + maven-license-plugin + 1.9.0 + +
src/main/resources/header.txt
+ true + + **/*.pdf + **/*.p12 + **/*.txt + **/*.xml + +
+ + + check-license-header + + check + + test + + +
+ + org.apache.maven.plugins + maven-jar-plugin + 2.3.1 + + + + true + no.posten.dpost.api.client.swing.DigipostSwingClient + + + + + + org.apache.maven.plugins + maven-javadoc-plugin + 2.8 + + + attach-javadoc + + jar + + + + + + org.apache.maven.plugins + maven-source-plugin + 2.1.2 + + true + + + + attach-source + + jar + + + + + + org.apache.maven.plugins + maven-enforcer-plugin + 1.0 + + + test + + enforce + + test + + + + + *:*:*:jar:compile + + + ch.qos.logback:logback-core:0.9.28:jar:compile + ch.qos.logback:logback-classic:0.9.28:jar:compile + org.scala-lang:scala-library:2.9.0:jar:compile + aopalliance:aopalliance:1.0:jar:compile + com.sun.jersey:jersey-client:1.7:jar:compile + com.sun.jersey:jersey-core:1.7:jar:compile + com.sun.jersey.contribs:jersey-apache-client:1.9:jar:compile + com.sun.xml.bind:jaxb-impl:2.2.2:jar:compile + commons-codec:commons-codec:1.2:jar:compile + commons-httpclient:commons-httpclient:3.1:jar:compile + commons-logging:commons-logging:1.0.4:jar:compile + commons-io:commons-io:2.0.1:jar:compile + commons-lang:commons-lang:2.6:jar:compile + javax.activation:activation:1.1:jar:compile + javax.xml.bind:jaxb-api:2.2.2:jar:compile + javax.xml.stream:stax-api:1.0-2:jar:compile + joda-time:joda-time:1.6.2:jar:compile + no.posten.dpost:dpost-xsd:${project.version}:jar:compile + org.bouncycastle:bcprov-jdk16:1.46:jar:compile + org.codehaus.castor:castor-core:1.3.1:jar:compile + org.codehaus.castor:castor-xml:1.3.1:jar:compile + org.slf4j:slf4j-api:1.6.1:jar:compile + org.springframework:spring-aop:3.0.5.RELEASE:jar:compile + org.springframework:spring-asm:3.0.5.RELEASE:jar:compile + org.springframework:spring-beans:3.0.5.RELEASE:jar:compile + org.springframework:spring-context:3.0.5.RELEASE:jar:compile + org.springframework:spring-core:3.0.5.RELEASE:jar:compile + org.springframework:spring-expression:3.0.5.RELEASE:jar:compile + org.springframework:spring-oxm:3.0.5.RELEASE:jar:compile + + true + Maven-avhengigheter har forandret seg. Sjekk at alle lisenser er OK før distribusjon. Husk også å oppdatere fila «NOTICE». + + + + + + + + org.scala-tools + maven-scala-plugin + 2.15.2 + + + + compile + testCompile + + + + + + **/*.scala + + + +
+
+ + + + assembly + + + !skip.assembly + + + + + + org.codehaus.mojo + appassembler-maven-plugin + 1.0-alpha-2 + + + + no.posten.dpost.api.client.swing.DigipostSwingClient + dpost-api-client + + windows + unix + + + + no.posten.dpost.api.client.cmd.DigipostCmdClient + dpost-api-cmd + + windows + unix + + + + + + + package + + assemble + + + + + + org.apache.maven.plugins + maven-assembly-plugin + + ${project.artifactId} + + assembly.xml + + false + + + + package + + single + + + + + + + + + + org.eclipse.m2e + lifecycle-mapping + 1.0.0 + + + + + + org.scala-tools + maven-scala-plugin + [2.15.2,) + + compile + testCompile + + + + true + + + + + org.apache.maven.plugins + maven-enforcer-plugin + [1.0,) + + enforce + + + + true + + + + + + + + + + + + + + UTF-8 + + +
diff --git a/src/main/java/no/posten/dpost/api/client/ApiService.java b/src/main/java/no/posten/dpost/api/client/ApiService.java new file mode 100644 index 00000000..62881ca8 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/ApiService.java @@ -0,0 +1,183 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client; + +import static no.posten.dpost.api.client.Headers.X_Digipost_UserId; +import static no.posten.dpost.api.client.representations.MediaTypes.DIGIPOST_MEDIA_TYPE_V1; + +import java.io.IOException; +import java.io.InputStream; +import java.net.URI; + +import javax.ws.rs.core.MediaType; + +import no.posten.dpost.api.client.DigipostClientException.ErrorType; +import no.posten.dpost.api.client.representations.Autocomplete; +import no.posten.dpost.api.client.representations.EntryPoint; +import no.posten.dpost.api.client.representations.ErrorMessage; +import no.posten.dpost.api.client.representations.Link; +import no.posten.dpost.api.client.representations.MediaTypes; +import no.posten.dpost.api.client.representations.Message; +import no.posten.dpost.api.client.representations.Recipients; + +import org.apache.commons.io.IOUtils; + +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.filter.ClientFilter; + +/** + * Denne klassen tar seg av de enkelte HTTP-forespørslene man kan gjøre mot + * REST-API-et, nemlig: + * + *
    + *
  • Hente søkeforslag (autocomplete)
  • + *
  • Søke etter mottakere
  • + *
  • Opprette en forsendelsesressurs på serveren + *
  • Hente en allerede opprettet forsendelsesressurs fra serveren + *
  • Sende innholdet (PDF) for en allerede opprettet forsendelsesressurs til + * serveren, og dermed sende brevet til mottakeren + *
      + * + * For å sende et brev gjennom Digipost er det tilstrekkelig å gjøre disse to + * kallene: + * + *
      + * createMessage(message);
      + * addToContentAndSend(createdMessage, content);
      + * 
      + * + * Dette kan også gjøres ved å kalle metoden {@code sendMessage} i klassen + * {@code MessageSender}, som i tillegg gjør en del feilhåndtering. + */ +public class ApiService { + + private static final String ENTRY_POINT = "/"; + private final WebResource webResource; + private final long senderAccountId; + + private EntryPoint cachedEntryPoint; + + public ApiService(final WebResource webResource, final long senderAccountId) { + this.webResource = webResource; + this.senderAccountId = senderAccountId; + } + + public ClientResponse getEntryPoint() { + return webResource + .path(ENTRY_POINT) + .accept(DIGIPOST_MEDIA_TYPE_V1) + .header(X_Digipost_UserId, senderAccountId) + .get(ClientResponse.class); + } + + /** + * Oppretter en ny forsendelsesressurs på serveren ved å sende en + * POST-forespørsel. + */ + public ClientResponse createMessage(final Message message) { + EntryPoint entryPoint = getCachedEntryPoint(); + return webResource + .path(entryPoint.getCreateMessageUri().getPath()) + .accept(DIGIPOST_MEDIA_TYPE_V1) + .header(X_Digipost_UserId, senderAccountId) + .type(DIGIPOST_MEDIA_TYPE_V1) + .post(ClientResponse.class, message); + } + + /** + * Henter en allerede eksisterende forsendelsesressurs fra serveren. + */ + public ClientResponse fetchExistingMessage(final URI location) { + return webResource + .path(location.getPath()) + .accept(DIGIPOST_MEDIA_TYPE_V1) + .header(X_Digipost_UserId, senderAccountId) + .get(ClientResponse.class); + } + + /** + * Angir innholdet i en allerede opprettet forsendelse og sender det som en + * POST-forespørsel til serveren. + * + * OBS! Denne metoden fører til at brevet blir sendt på ordentlig. + * + * Før man kaller denne metoden, må man allerede ha opprettet en + * forsendelsesressurs på serveren ved metoden {@code opprettForsendelse}. + */ + public ClientResponse addToContentAndSend(final Message createdMessage, final InputStream letterContent) { + Link addFileLink = fetchAddFileLink(createdMessage); + + byte[] content = readLetterContent(letterContent); + + return webResource + .path(addFileLink.getUri().getPath()) + .accept(DIGIPOST_MEDIA_TYPE_V1) + .header(X_Digipost_UserId, senderAccountId) + .type(MediaType.APPLICATION_OCTET_STREAM) + .post(ClientResponse.class, content); + + } + + private Link fetchAddFileLink(final Message createdMessage) { + Link addContentLink = createdMessage.getFileLink(); + if (addContentLink == null) { + throw new DigipostClientException(ErrorType.PROBLEM_WITH_REQUEST, + "Kan ikke legge til innhold til en forsendelse som ikke har en link for å gjøre dette."); + } + return addContentLink; + } + + private byte[] readLetterContent(final InputStream letterContent) { + try { + return IOUtils.toByteArray(letterContent); + } catch (IOException e) { + throw new RuntimeException(e); + } + } + + public Recipients search(final String searchString) { + return webResource + .path(getCachedEntryPoint().getSearchUri().getPath() + "/" + searchString) + .accept(DIGIPOST_MEDIA_TYPE_V1) + .header(X_Digipost_UserId, senderAccountId) + .get(Recipients.class); + } + + public Autocomplete searchSuggest(final String searchString) { + return webResource + .path(getCachedEntryPoint().getAutocompleteUri().getPath() + "/" + searchString) + .accept(MediaTypes.DIGIPOST_MEDIA_TYPE_V1) + .header(X_Digipost_UserId, senderAccountId) + .get(Autocomplete.class); + } + + public void addFilter(final ClientFilter filter) { + webResource.addFilter(filter); + } + + private EntryPoint getCachedEntryPoint() { + if (cachedEntryPoint == null) { + ClientResponse response = getEntryPoint(); + if (response.getStatus() != ClientResponse.Status.OK.getStatusCode()) { + throw new DigipostClientException(ErrorType.GENERAL_ERROR, response.getEntity(ErrorMessage.class).getErrorMessage()); + } else { + cachedEntryPoint = response.getEntity(EntryPoint.class); + } + } + return cachedEntryPoint; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/DigipostClient.java b/src/main/java/no/posten/dpost/api/client/DigipostClient.java new file mode 100644 index 00000000..3f7ceaba --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/DigipostClient.java @@ -0,0 +1,110 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client; + +import java.io.InputStream; + +import no.posten.dpost.api.client.filters.ContentMD5Filter; +import no.posten.dpost.api.client.filters.DateFilter; +import no.posten.dpost.api.client.filters.SignatureFilter; +import no.posten.dpost.api.client.filters.UserAgentFilter; +import no.posten.dpost.api.client.representations.Autocomplete; +import no.posten.dpost.api.client.representations.Message; +import no.posten.dpost.api.client.representations.Recipients; +import no.posten.dpost.api.client.security.FileKeystoreSigner; +import no.posten.dpost.api.client.security.Signer; +import no.posten.dpost.api.client.util.JerseyClientProvider; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.WebResource; +import com.sun.jersey.api.client.filter.ClientFilter; + +/** + * En klient for å sende brev gjennom Digipost. Hvis et objekt av denne klassen + * er opprettet med et fungerende sertifikat og tilhørende passord, kan man + * gjøre søk og sende brev gjennom Digipost. + */ +public class DigipostClient { + public static final EventLogger NOOP_EVENT_LOGGER = new EventLogger() { + @Override + public void log(final String eventText) { + // NOOP + } + }; + + private static final Logger LOG = LoggerFactory.getLogger(DigipostClient.class); + + private final EventLogger eventLogger; + private final ApiService apiService; + + public DigipostClient(final String digipostUrl, final long senderAccountId, final InputStream certificateP12File, + final String certificatePassword) { + this(digipostUrl, senderAccountId, new FileKeystoreSigner(certificateP12File, certificatePassword), NOOP_EVENT_LOGGER); + } + + public DigipostClient(final String digipostUrl, final long senderAccountId, final InputStream certificateP12File, + final String sertifikatPassord, final EventLogger eventLogger) { + this(digipostUrl, senderAccountId, new FileKeystoreSigner(certificateP12File, sertifikatPassord), eventLogger); + } + + public DigipostClient(final String digipostUrl, final long senderAccountId, final Signer signer) { + this(digipostUrl, senderAccountId, signer, NOOP_EVENT_LOGGER); + } + + public DigipostClient(final String digipostUrl, final long senderAccountId, final Signer signer, final EventLogger eventLogger) { + this.eventLogger = eventLogger != null ? eventLogger : NOOP_EVENT_LOGGER; + + Client client = JerseyClientProvider.getClient(); + WebResource webResource = client.resource(digipostUrl); + webResource.addFilter(new ContentMD5Filter(eventLogger)); + webResource.addFilter(new SignatureFilter(signer, eventLogger)); + webResource.addFilter(new DateFilter(eventLogger)); + webResource.addFilter(new UserAgentFilter()); + log("Initialiserte Jersey-klient mot " + digipostUrl); + + apiService = new ApiService(webResource, senderAccountId); + } + + /** + * Sender et brev gjennom Digipost. Denne metoden gjør alle HTTP-kallene som + * er nødvendige for å sende brevet. Det vil si at den først gjør et kall + * for å opprette en message-ressurs på serveren og deretter poster brevets + * innhold. + */ + public Message sendMessage(final Message message, final InputStream letterContent) { + return new MessageSender(apiService, eventLogger).sendMessage(message, letterContent); + } + + public Recipients search(final String searchString) { + return apiService.search(searchString); + } + + public Autocomplete getAutocompleteSuggestions(final String searchString) { + return apiService.searchSuggest(searchString); + } + + private void log(final String stringToSignMsg) { + LOG.debug(stringToSignMsg); + eventLogger.log(stringToSignMsg); + } + + public void addFilter(final ClientFilter filter) { + apiService.addFilter(filter); + } +} diff --git a/src/main/java/no/posten/dpost/api/client/DigipostClientException.java b/src/main/java/no/posten/dpost/api/client/DigipostClientException.java new file mode 100644 index 00000000..e024afac --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/DigipostClientException.java @@ -0,0 +1,48 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client; + +public class DigipostClientException extends RuntimeException { + private static final long serialVersionUID = 1L; + + public enum ErrorType { + RECIPIENT_DOES_NOT_EXIST, + PROBLEM_WITH_REQUEST, + SERVER_ERROR, + INVALID_TRANSACTION, + MESSAGE_DOES_NOT_EXIST, + DUPLICATE_MESSAGE_ID, + MESSAGE_DELIVERED, + GENERAL_ERROR; + } + + private final ErrorType errorType; + private final String errorMessage; + + public DigipostClientException(final ErrorType errorType, final String errorMessage) { + this.errorType = errorType; + this.errorMessage = errorMessage; + } + + public ErrorType getErrorType() { + return errorType; + } + + public String getErrorMessage() { + return errorMessage; + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/EventLogger.java b/src/main/java/no/posten/dpost/api/client/EventLogger.java new file mode 100644 index 00000000..7e007322 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/EventLogger.java @@ -0,0 +1,20 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client; + +public interface EventLogger { + void log(String logMessage); +} diff --git a/src/main/java/no/posten/dpost/api/client/Headers.java b/src/main/java/no/posten/dpost/api/client/Headers.java new file mode 100644 index 00000000..687d4dd4 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/Headers.java @@ -0,0 +1,28 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client; + +public final class Headers { + public static final String X_Digipost_Prefix = "X-Digipost-"; + + public static final String X_Digipost_Signature = X_Digipost_Prefix + "Signature"; + public static final String X_Digipost_UserId = X_Digipost_Prefix + "UserId"; + + public static final String Date = "Date"; + public static final String User_Agent = "User-Agent"; + public static final String Content_MD5 = "Content-MD5"; + +} diff --git a/src/main/java/no/posten/dpost/api/client/MessageSender.java b/src/main/java/no/posten/dpost/api/client/MessageSender.java new file mode 100644 index 00000000..dafd0ddf --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/MessageSender.java @@ -0,0 +1,195 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client; + +import java.io.InputStream; + +import javax.ws.rs.core.Response.Status; + +import no.posten.dpost.api.client.DigipostClientException.ErrorType; +import no.posten.dpost.api.client.representations.ErrorMessage; +import no.posten.dpost.api.client.representations.Message; +import no.posten.dpost.api.client.representations.MessageStatus; + +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class MessageSender { + private static final Logger LOG = LoggerFactory.getLogger(MessageSender.class); + + private final EventLogger eventLogger; + private final ApiService apiService; + + public MessageSender(final ApiService apiService, final EventLogger eventLogger) { + this.apiService = apiService; + this.eventLogger = eventLogger; + } + + /** + * Sender et brev gjennom Digipost. Denne metoden gjør begge HTTP-kallene + * som er nødvendige for å sende brevet. Det vil si at den først gjør et + * kall for å opprette en forsendelsesressurs på serveren og deretter poster + * brevets innhold. + */ + public Message sendMessage(final Message message, final InputStream letterContent) { + log("\n\n---STARTER FØRSTE INTERAKSJON MED API (OPPRETTE FORSENDELSE)---"); + Message createdMessage = createOrFetchMessage(message); + log("\n\n---STARTER ANDRE INTERAKSJON MED API (LEGGE TIL FIL)---"); + Message sentMessage = addToContentAndSendMessage(createdMessage, letterContent); + log("\n\n---API-INTERAKSJON ER FULLFØRT (OG BREVET ER DERMED SENDT)---"); + return sentMessage; + } + + /** + * Oppretter en forsendelsesressurs på serveren eller henter en allerede + * opprettet forsendelsesressurs. + * + * Dersom forsendelsen allerede er opprettet, vil denne metoden gjøre en + * GET-forespørsel mot serveren for å hente en representasjon av + * forsendelsesressursen slik den er på serveren. Dette vil ikke føre til + * noen endringer av ressursen. + * + * Dersom forsendelsen ikke eksisterer fra før, vil denne metoden opprette + * en ny forsendelsesressurs på serveren og returnere en representasjon av + * ressursen. + */ + public Message createOrFetchMessage(final Message message) { + ClientResponse response = apiService.createMessage(message); + + if (messageAlreadyExists(response)) { + + ClientResponse existingMessageResponse = apiService.fetchExistingMessage(response.getLocation()); + checkResponse(existingMessageResponse); + Message exisitingMessage = existingMessageResponse.getEntity(Message.class); + checkThatMessageExists(exisitingMessage, message); + checkThatMessageHasNotAlreadyBeenDelivered(exisitingMessage); + log("Identisk forsendelse fantes fra før. Bruker denne istedenfor å opprette ny. Status: [" + response.toString() + "]"); + return exisitingMessage; + + } else { + + check404Error(response, ErrorType.RECIPIENT_DOES_NOT_EXIST); + checkResponse(response); + log("Forsendelse opprettet. Status: [" + response.toString() + "]"); + return response.getEntity(Message.class); + + } + + } + + /** + * Legger til innhold (PDF) til en forsendelse og sender brevet. For at + * denne metoden skal kunne kalles, må man først ha opprettet + * forsendelsesressursen på serveren ved metoden + * {@code createOrFetchMesssage}. + * + */ + public Message addToContentAndSendMessage(final Message createdMessage, final InputStream letterContent) { + verifyCorrectStatus(createdMessage, MessageStatus.EXPECTING_CONTENT); + ClientResponse response = apiService.addToContentAndSend(createdMessage, letterContent); + + check404Error(response, ErrorType.MESSAGE_DOES_NOT_EXIST); + checkResponse(response); + + log("Innhold ble lagt til og brevet sendt. Status: [" + response.toString() + "]"); + return response.getEntity(Message.class); + } + + private void verifyCorrectStatus(final Message createdMessage, final MessageStatus expectedStatus) { + if (createdMessage.getStatus() != expectedStatus) { + throw new DigipostClientException(ErrorType.INVALID_TRANSACTION, + "Kan ikke legge til innhold til en forsendelse som ikke er i tilstanden " + expectedStatus + "."); + } + } + + private void checkResponse(final ClientResponse response) { + Status status = Status.fromStatusCode(response.getStatus()); + if (!responseOk(response)) { + String errorMessage = fetchErrorMessageString(response); + log(errorMessage); + switch (status) { + case BAD_REQUEST: + throw new DigipostClientException(ErrorType.PROBLEM_WITH_REQUEST, errorMessage); + case CONFLICT: + throw new DigipostClientException(ErrorType.INVALID_TRANSACTION, errorMessage); + case INTERNAL_SERVER_ERROR: + throw new DigipostClientException(ErrorType.SERVER_ERROR, errorMessage); + default: + throw new DigipostClientException(ErrorType.GENERAL_ERROR, errorMessage); + } + } + } + + private void check404Error(final ClientResponse response, final ErrorType errorBy404) { + if (Status.fromStatusCode(response.getStatus()) == Status.NOT_FOUND) { + throw new DigipostClientException(errorBy404, fetchErrorMessageString(response)); + } + } + + private void checkThatMessageExists(final Message exisitingMessage, final Message message) { + if (!exisitingMessage.isIdenticalTo(message)) { + String errorMessage = "Forsendelse med id [" + message.getMessageId() + "] finnes fra før med annen spesifikasjon."; + log(errorMessage); + throw new DigipostClientException(ErrorType.DUPLICATE_MESSAGE_ID, errorMessage); + } + } + + private void checkThatMessageHasNotAlreadyBeenDelivered(final Message existingMessage) { + if (MessageStatus.DELIVERED == existingMessage.getStatus()) { + String errorMessage = "En identisk forsendelse er allerede levert til mottaker. Dette skyldes sannsynligvis doble kall til Digipost."; + log(errorMessage); + throw new DigipostClientException(ErrorType.MESSAGE_DELIVERED, errorMessage); + } + } + + private boolean messageAlreadyExists(final ClientResponse response) { + return Status.CONFLICT.equals(Status.fromStatusCode(response.getStatus())); + } + + private String fetchErrorMessageString(final ClientResponse response) { + try { + return response.getEntity(ErrorMessage.class).getErrorMessage(); + } catch (ClientHandlerException e) { + throw new DigipostClientException(ErrorType.SERVER_ERROR, + "Det skjedde en feil på serveren, men klienten kunne ikke lese responsen."); + } catch (UniformInterfaceException e) { + return ""; + } + } + + private boolean responseOk(final ClientResponse response) { + Status status = Status.fromStatusCode(response.getStatus()); + if (status == null) { + return false; + } + switch (status) { + case CREATED: + case OK: + return true; + default: + return false; + } + } + + private void log(final String message) { + LOG.debug(message); + eventLogger.log(message); + } +} diff --git a/src/main/java/no/posten/dpost/api/client/filters/ContentMD5Filter.java b/src/main/java/no/posten/dpost/api/client/filters/ContentMD5Filter.java new file mode 100644 index 00000000..3ed817e8 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/filters/ContentMD5Filter.java @@ -0,0 +1,114 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.filters; + +import static no.posten.dpost.api.client.DigipostClient.NOOP_EVENT_LOGGER; +import static no.posten.dpost.api.client.Headers.Content_MD5; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.security.MessageDigest; +import java.security.NoSuchAlgorithmException; + +import no.posten.dpost.api.client.EventLogger; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jersey.api.client.AbstractClientRequestAdapter; +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientRequestAdapter; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class ContentMD5Filter extends ClientFilter { + + private static final Logger LOG = LoggerFactory.getLogger(ContentMD5Filter.class); + private final EventLogger eventLogger; + + public ContentMD5Filter(final EventLogger eventListener) { + eventLogger = eventListener != null ? eventListener : NOOP_EVENT_LOGGER; + } + + public ContentMD5Filter() { + this(NOOP_EVENT_LOGGER); + } + + @Override + public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException { + cr.setAdapter(new ContentMD5Adapter(cr.getAdapter())); + return getNext().handle(cr); + } + + private void log(final String stringToSignMsg) { + LOG.debug(stringToSignMsg); + eventLogger.log(stringToSignMsg); + } + + private final class ContentMD5Adapter extends AbstractClientRequestAdapter { + ContentMD5Adapter(final ClientRequestAdapter cra) { + super(cra); + } + + @Override + public OutputStream adapt(final ClientRequest request, final OutputStream out) throws IOException { + return new ContentMD5OutputStream(request, getAdapter().adapt(request, out)); + } + } + + private final class ContentMD5OutputStream extends OutputStream { + + private final ByteArrayOutputStream byteArrayOutputStream; + private final OutputStream jerseyStream; + private final ClientRequest request; + + public ContentMD5OutputStream(final ClientRequest request, final OutputStream jerseyStream) { + this.jerseyStream = jerseyStream; + this.request = request; + + byteArrayOutputStream = new ByteArrayOutputStream(); + } + + @Override + public void write(final int b) throws IOException { + byteArrayOutputStream.write(b); + } + + @Override + public void close() throws IOException { + byteArrayOutputStream.close(); + byte[] byteArray = byteArrayOutputStream.toByteArray(); + settContentMD5Header(byteArray); + IOUtils.write(byteArray, jerseyStream); + jerseyStream.close(); + } + + private void settContentMD5Header(final byte[] data) { + try { + MessageDigest instance = MessageDigest.getInstance("MD5"); + String contentMD5 = new String(Base64.encodeBase64(instance.digest(data))); + request.getHeaders().add(Content_MD5, contentMD5); + log(ContentMD5Filter.class.getSimpleName() + " satt headeren " + Content_MD5 + "=" + contentMD5); + } catch (NoSuchAlgorithmException e) { + log("Feil ved generering av Content-MD5"); + } + } + } +} diff --git a/src/main/java/no/posten/dpost/api/client/filters/DateFilter.java b/src/main/java/no/posten/dpost/api/client/filters/DateFilter.java new file mode 100644 index 00000000..5f9f11e5 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/filters/DateFilter.java @@ -0,0 +1,64 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.filters; + +import static no.posten.dpost.api.client.DigipostClient.NOOP_EVENT_LOGGER; +import static no.posten.dpost.api.client.Headers.Date; + +import java.util.Date; + +import no.posten.dpost.api.client.EventLogger; +import no.posten.dpost.api.client.Headers; + +import org.apache.commons.httpclient.util.DateUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class DateFilter extends ClientFilter { + private static final Logger LOG = LoggerFactory.getLogger(DateFilter.class); + private final EventLogger eventLogger; + + public DateFilter() { + this(NOOP_EVENT_LOGGER); + } + + public DateFilter(final EventLogger eventListener) { + this.eventLogger = eventListener != null ? eventListener : NOOP_EVENT_LOGGER; + } + + @Override + public ClientResponse handle(final ClientRequest cr) { + modifyRequest(cr); + return getNext().handle(cr); + } + + private void log(final String stringToSignMsg) { + LOG.debug(stringToSignMsg); + eventLogger.log(stringToSignMsg); + } + + private ClientRequest modifyRequest(final ClientRequest cr) { + String dateOnRFC1123Format = DateUtil.formatDate(new Date()); + cr.getHeaders().add(Date, dateOnRFC1123Format); + log(getClass().getSimpleName() + " satt headeren " + Headers.Date + "=" + dateOnRFC1123Format); + return cr; + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/filters/SignatureFilter.java b/src/main/java/no/posten/dpost/api/client/filters/SignatureFilter.java new file mode 100644 index 00000000..58ea9974 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/filters/SignatureFilter.java @@ -0,0 +1,129 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.filters; + +import static no.posten.dpost.api.client.DigipostClient.NOOP_EVENT_LOGGER; + +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.OutputStream; +import java.security.Security; + +import no.posten.dpost.api.client.EventLogger; +import no.posten.dpost.api.client.Headers; +import no.posten.dpost.api.client.security.ClientRequestToSign; +import no.posten.dpost.api.client.security.MessageSignatureUtil; +import no.posten.dpost.api.client.security.Signer; + +import org.apache.commons.codec.binary.Base64; +import org.apache.commons.io.IOUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import com.sun.jersey.api.client.AbstractClientRequestAdapter; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientRequestAdapter; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class SignatureFilter extends ClientFilter { + + private static final Logger LOG = LoggerFactory.getLogger(SignatureFilter.class); + + private final Signer signer; + + private final EventLogger eventLogger; + + public SignatureFilter(final Signer signer) { + this(signer, NOOP_EVENT_LOGGER); + } + + public SignatureFilter(final Signer signer, final EventLogger eventListener) { + this.signer = signer; + eventLogger = eventListener != null ? eventListener : NOOP_EVENT_LOGGER; + } + + @Override + public ClientResponse handle(final ClientRequest cr) { + if (cr.getEntity() == null) { + setSignatureHeader(cr); + } else { + cr.setAdapter(new SikkerhetsAdapter(cr.getAdapter())); + } + return getNext().handle(cr); + } + + private void setSignatureHeader(final ClientRequest request) { + Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider()); + String stringToSign = MessageSignatureUtil.getCanonicalRequestRepresentation(new ClientRequestToSign(request)); + log(getClass().getSimpleName() + " beregnet streng som skal signeres:\n===START SIGNATURSTRENG===\n" + stringToSign + + "===SLUTT SIGNATURSTRENG==="); + + byte[] signatureBytes = signer.sign(stringToSign); + String signature = new String(Base64.encodeBase64(signatureBytes)); + request.getHeaders().add(Headers.X_Digipost_Signature, signature); + log(getClass().getSimpleName() + " satt headeren " + Headers.X_Digipost_Signature + "=" + signature); + } + + private void log(final String stringToSignMsg) { + LOG.debug(stringToSignMsg); + eventLogger.log(stringToSignMsg); + } + + private final class SikkerhetsAdapter extends AbstractClientRequestAdapter { + SikkerhetsAdapter(final ClientRequestAdapter cra) { + super(cra); + } + + @Override + public OutputStream adapt(final ClientRequest request, final OutputStream out) throws IOException { + return new SecurityAdapterOutputStream(request, getAdapter().adapt(request, out)); + } + } + + private final class SecurityAdapterOutputStream extends OutputStream { + + private final ByteArrayOutputStream byteArrayOutputStream; + private final OutputStream jerseyStream; + private final ClientRequest request; + + public SecurityAdapterOutputStream(final ClientRequest request, final OutputStream jerseyStream) { + this.request = request; + this.jerseyStream = jerseyStream; + + byteArrayOutputStream = new ByteArrayOutputStream(); + } + + @Override + public void write(final int b) throws IOException { + byteArrayOutputStream.write(b); + } + + @Override + public void close() throws IOException { + setSignatureHeader(request); + writeTemporarilyToJerseystream(); + jerseyStream.close(); + super.close(); + } + + private void writeTemporarilyToJerseystream() throws IOException { + IOUtils.write(byteArrayOutputStream.toByteArray(), jerseyStream); + byteArrayOutputStream.close(); + } + + } +} \ No newline at end of file diff --git a/src/main/java/no/posten/dpost/api/client/filters/UserAgentFilter.java b/src/main/java/no/posten/dpost/api/client/filters/UserAgentFilter.java new file mode 100644 index 00000000..0842d6e4 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/filters/UserAgentFilter.java @@ -0,0 +1,32 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.filters; + +import no.posten.dpost.api.client.Headers; + +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientRequest; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.filter.ClientFilter; + +public class UserAgentFilter extends ClientFilter { + + @Override + public ClientResponse handle(final ClientRequest cr) throws ClientHandlerException { + cr.getHeaders().add(Headers.User_Agent, "Digipost API Client v1.0.0"); + return getNext().handle(cr); + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Address.java b/src/main/java/no/posten/dpost/api/client/representations/Address.java new file mode 100644 index 00000000..c1f60b92 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Address.java @@ -0,0 +1,67 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; + +@XmlAccessorType(XmlAccessType.FIELD) +public class Address { + + private String street; + private String houseNumber; + private String houseLetter; + private String additionalAddressLine; + private String zipCode; + private String city; + + public Address(final String street, final String houseNumber, final String houseLetter, final String additionalAddressLine, + final String zipCode, final String city) { + this.street = street; + this.houseNumber = houseNumber; + this.houseLetter = houseLetter; + this.additionalAddressLine = additionalAddressLine; + this.zipCode = zipCode; + this.city = city; + } + + Address() { + } + + public String getStreet() { + return street; + } + + public String getHouseNumber() { + return houseNumber; + } + + public String getHouseLetter() { + return houseLetter; + } + + public String getAdditionalAddressLine() { + return additionalAddressLine; + } + + public String getZipCode() { + return zipCode; + } + + public String getCity() { + return city; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/AuthenticationLevel.java b/src/main/java/no/posten/dpost/api/client/representations/AuthenticationLevel.java new file mode 100644 index 00000000..74955ac9 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/AuthenticationLevel.java @@ -0,0 +1,53 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import javax.xml.bind.annotation.XmlEnum; + +@XmlEnum +public enum AuthenticationLevel { + PASSWORD(2), + TWO_FACTOR(3); + + private final int level; + + AuthenticationLevel(final int level) { + this.level = level; + } + + public int level() { + return level; + } + + public static AuthenticationLevel fromLevel(final int verdi) { + switch (verdi) { + case 2: + return PASSWORD; + case 3: + return TWO_FACTOR; + default: + throw new IllegalArgumentException("Unknown authentication level: " + verdi); + } + } + + public String value() { + return name(); + } + + public static AuthenticationLevel fromValue(final String v) { + return valueOf(v); + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Autocomplete.java b/src/main/java/no/posten/dpost/api/client/representations/Autocomplete.java new file mode 100644 index 00000000..b35cb264 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Autocomplete.java @@ -0,0 +1,58 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement +public class Autocomplete extends Representation { + + @XmlElement(name = "suggestion") + private final List suggestions; + + public Autocomplete(final List suggestions, final Link... links) { + super(links); + this.suggestions = suggestions; + } + + Autocomplete() { + suggestions = new ArrayList(); + } + + public List getSuggestions() { + return suggestions; + } + + public Link getSelfLink() { + return getLinkByRelationName(Relation.SELF); + } + + @XmlElement(name = "link") + protected List getLink() { + return links; + } + + protected void setLink(final List links) { + this.links = links; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/DigipostAddress.java b/src/main/java/no/posten/dpost/api/client/representations/DigipostAddress.java new file mode 100644 index 00000000..dc1086c3 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/DigipostAddress.java @@ -0,0 +1,36 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import org.apache.commons.lang.StringUtils; + +public class DigipostAddress extends RecipientIdentifier { + + public DigipostAddress(final String address) { + super(address); + assert !StringUtils.isEmpty(address) : "DigipostAddress cannot be empty"; + } + + @Override + public String toString() { + return String.format("%s(%s)", getClass().getSimpleName(), identifier); + } + + @Override + public boolean isPersonalIdentificationNumber() { + return false; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/DigipostUri.java b/src/main/java/no/posten/dpost/api/client/representations/DigipostUri.java new file mode 100644 index 00000000..201d68ae --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/DigipostUri.java @@ -0,0 +1,68 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.commons.lang.StringUtils; + +public class DigipostUri { + private final URI uri; + + public DigipostUri(final String... uriComponents) { + try { + uri = new URI(StringUtils.join(uriComponents, "/").replaceAll("([^:])/+", "$1/")); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + public DigipostUri(final URI uri) { + this.uri = uri; + } + + public URI getFullUri() { + return uri; + } + + @Override + public String toString() { + return uri.toString(); + } + + @Override + public boolean equals(final Object obj) { + if (obj instanceof DigipostUri) { + return ((DigipostUri) obj).uri.equals(uri); + } + return false; + } + + @Override + public int hashCode() { + return uri.hashCode(); + } + + public String getBaseUri() { + String port = ""; + if (uri.getPort() != 80 && uri.getPort() != -1) { + port = ":" + String.valueOf(uri.getPort()); + } + + return uri.getScheme() + "://" + uri.getHost() + port; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/EntryPoint.java b/src/main/java/no/posten/dpost/api/client/representations/EntryPoint.java new file mode 100644 index 00000000..858975a9 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/EntryPoint.java @@ -0,0 +1,61 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import static no.posten.dpost.api.client.representations.Relation.AUTOCOMPLETE; +import static no.posten.dpost.api.client.representations.Relation.CREATE_MESSAGE; +import static no.posten.dpost.api.client.representations.Relation.SEARCH; + +import java.net.URI; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "links") +public class EntryPoint extends Representation { + + public EntryPoint(final Link... links) { + super(links); + } + + EntryPoint() { + } + + public URI getCreateMessageUri() { + return getLinkByRelationName(CREATE_MESSAGE).getUri(); + } + + public URI getSearchUri() { + return getLinkByRelationName(SEARCH).getUri(); + } + + public URI getAutocompleteUri() { + return getLinkByRelationName(AUTOCOMPLETE).getUri(); + } + + @XmlElement(name = "link") + protected List getLink() { + return links; + } + + protected void setLink(final List links) { + this.links = links; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/ErrorMessage.java b/src/main/java/no/posten/dpost/api/client/representations/ErrorMessage.java new file mode 100644 index 00000000..289da57f --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/ErrorMessage.java @@ -0,0 +1,78 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement(name = "error") +public class ErrorMessage extends Representation { + + @XmlElement(required = true) + private String errorMessage; + + public ErrorMessage(final String errorMessage, final Link... linker) { + super(linker); + this.errorMessage = errorMessage; + } + + ErrorMessage() { + } + + @Override + public int hashCode() { + return new HashCodeBuilder().append(errorMessage).toHashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + ErrorMessage other = (ErrorMessage) obj; + return new EqualsBuilder().append(errorMessage, other.errorMessage).isEquals(); + } + + @Override + public String toString() { + return String.format("%s(%s)", getClass().getSimpleName(), errorMessage); + } + + public String getErrorMessage() { + return errorMessage; + } + + @XmlElement(name = "link") + public List getLink() { + return links; + } + + public void setLink(final List links) { + this.links = links; + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Link.java b/src/main/java/no/posten/dpost/api/client/representations/Link.java new file mode 100644 index 00000000..5fa4f08e --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Link.java @@ -0,0 +1,126 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import java.net.URI; +import java.net.URISyntaxException; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlTransient; +import javax.xml.bind.annotation.XmlType; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(name = "link", propOrder = { "rel", "uri", "mediaType" }) +public class Link { + private static final String RELATIONS_BASE_PATH = "/relations"; + + @XmlTransient + private Relation rel; + @XmlTransient + private String relationBaseUri; + + @XmlElement(required = true) + private String uri; + @XmlElement(required = true) + private String mediaType; + + public Link(final Relation relation, final DigipostUri uri, final String mediaType) { + rel = relation; + relationBaseUri = uri.getBaseUri() + RELATIONS_BASE_PATH; + this.uri = uri.getFullUri().toString(); + this.mediaType = mediaType; + } + + public Link(final Relation relation, final DigipostUri uri) { + this(relation, uri, MediaTypes.DIGIPOST_MEDIA_TYPE_V1); + } + + Link() { + } + + private String parseRelationsBaseUri(final String rel) { + return rel.substring(0, rel.lastIndexOf("/")); + } + + private Relation parseRel(final String rel) { + return Relation.valueOf(rel.substring(rel.lastIndexOf("/") + 1).toUpperCase()); + } + + public String getRelationUri() { + return relationBaseUri + "/" + rel.name().toLowerCase(); + } + + @XmlElement(required = true) + public String getRel() { + return getRelationUri(); + } + + public void setRel(final String rel) { + this.rel = parseRel(rel); + relationBaseUri = parseRelationsBaseUri(rel); + } + + public Relation getRelationName() { + return rel; + } + + public URI getUri() { + try { + return new URI(uri); + } catch (URISyntaxException e) { + throw new RuntimeException(e); + } + } + + public String getMediaType() { + return mediaType; + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + + public boolean equalsRelation(final Relation relation) { + return rel.equals(relation); + } + + @Override + public int hashCode() { + return new HashCodeBuilder(31, 1).append(mediaType).append(rel).append(relationBaseUri).append(uri).toHashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null || getClass() != obj.getClass()) + return false; + Link other = (Link) obj; + return new EqualsBuilder() + .append(mediaType, other.mediaType) + .append(rel, other.rel) + .append(relationBaseUri, other.relationBaseUri) + .append(uri, other.uri) + .isEquals(); + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/MediaTypes.java b/src/main/java/no/posten/dpost/api/client/representations/MediaTypes.java new file mode 100644 index 00000000..eb2fcdb4 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/MediaTypes.java @@ -0,0 +1,22 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +public class MediaTypes { + + public static final String DIGIPOST_MEDIA_TYPE_V1 = "application/vnd.digipost-v1+xml"; + +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Message.java b/src/main/java/no/posten/dpost/api/client/representations/Message.java new file mode 100644 index 00000000..968e2107 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Message.java @@ -0,0 +1,147 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import static no.posten.dpost.api.client.representations.MessageStatus.EXPECTING_CONTENT; + +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; +import javax.xml.bind.annotation.XmlTransient; +import javax.xml.bind.annotation.XmlType; + +import org.apache.commons.lang.StringUtils; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlType(propOrder = { "messageId", "subject", "digipostAddress", "personalIdentificationNumber", "smsNotification", "status", "link", + "authenticationLevel" }) +@XmlRootElement +public class Message extends Representation { + @XmlElement(required = true) + private String messageId; + @XmlElement(required = true) + private String subject; + @XmlTransient + private RecipientIdentifier recipientIdentifier; + private boolean smsNotification; + private MessageStatus status; + private AuthenticationLevel authenticationLevel; + + public Message(final String messageId, final String subject, final RecipientIdentifier recipientIdentifier, + final boolean smsNotification, final AuthenticationLevel authenticationLevel, final Link... links) { + this(messageId, subject, recipientIdentifier, smsNotification, EXPECTING_CONTENT, authenticationLevel, links); + } + + public Message(final String messageId, final String subject, final RecipientIdentifier recipientIdentifier, + final boolean smsNotification, final MessageStatus status, final AuthenticationLevel authenticationLevel, final Link... links) { + super(links); + this.messageId = messageId; + this.subject = subject; + this.recipientIdentifier = recipientIdentifier; + this.smsNotification = smsNotification; + this.status = status; + this.authenticationLevel = authenticationLevel; + } + + Message() { + } + + public Link getSelfLink() { + return getLinkByRelationName(Relation.SELF); + } + + public Link getFileLink() { + return getLinkByRelationName(Relation.ADD_CONTENT); + } + + public String getSubject() { + return subject; + } + + public MessageStatus getStatus() { + return status; + } + + public boolean hasSubject() { + return !StringUtils.isBlank(subject); + } + + public String getMessageId() { + return messageId; + } + + public boolean isSmsNotification() { + return smsNotification; + } + + /** + * To forsendelser regnes som identiske hvis de har samme forsendelses-id og + * emne og mottakerne har samme kunde-id. + */ + public boolean isIdenticalTo(final Message message) { + return messageId.equals(message.getMessageId()) && subject.equals(message.getSubject()); + } + + public RecipientIdentifier getRecipientIdentifier() { + return recipientIdentifier; + } + + public AuthenticationLevel getAuthenticationLevel() { + return authenticationLevel; + } + + @XmlElement + protected String getDigipostAddress() { + if (recipientIdentifier.isPersonalIdentificationNumber()) { + return null; + } else { + return recipientIdentifier.asString(); + } + } + + protected void setDigipostAddress(final String digipostAddress) { + recipientIdentifier = new DigipostAddress(digipostAddress); + } + + @XmlElement + protected String getPersonalIdentificationNumber() { + if (recipientIdentifier.isPersonalIdentificationNumber()) { + return recipientIdentifier.asString(); + } else { + return null; + } + } + + protected void setPersonalIdentificationNumber(final String personalIdentificationNumber) { + recipientIdentifier = new PersonalIdentificationNumber(personalIdentificationNumber); + } + + public void setStatus(final MessageStatus status) { + this.status = status; + } + + @XmlElement(name = "link") + protected List getLink() { + return links; + } + + protected void setLink(final List links) { + this.links = links; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/MessageStatus.java b/src/main/java/no/posten/dpost/api/client/representations/MessageStatus.java new file mode 100644 index 00000000..46bd8cfb --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/MessageStatus.java @@ -0,0 +1,32 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import javax.xml.bind.annotation.XmlEnum; + +@XmlEnum +public enum MessageStatus { + EXPECTING_CONTENT, + DELIVERED; + + public String value() { + return name(); + } + + public static MessageStatus fromValue(final String v) { + return valueOf(v); + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/ObjectFactory.java b/src/main/java/no/posten/dpost/api/client/representations/ObjectFactory.java new file mode 100644 index 00000000..91a2bf9e --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/ObjectFactory.java @@ -0,0 +1,45 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import javax.xml.bind.annotation.XmlRegistry; + +@XmlRegistry +public class ObjectFactory { + + public ObjectFactory() { + } + + public Recipients createRecipients() { + return new Recipients(); + } + + public ErrorMessage createErrorMessage() { + return new ErrorMessage(); + } + + public Autocomplete createAutocomplete() { + return new Autocomplete(); + } + + public Message createMessage() { + return new Message(); + } + + public EntryPoint createEntryPoint() { + return new EntryPoint(); + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/PersonalIdentificationNumber.java b/src/main/java/no/posten/dpost/api/client/representations/PersonalIdentificationNumber.java new file mode 100644 index 00000000..09445187 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/PersonalIdentificationNumber.java @@ -0,0 +1,28 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +public class PersonalIdentificationNumber extends RecipientIdentifier { + + public PersonalIdentificationNumber(final String birthNumber) { + super(birthNumber); + } + + @Override + public boolean isPersonalIdentificationNumber() { + return true; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Recipient.java b/src/main/java/no/posten/dpost/api/client/representations/Recipient.java new file mode 100644 index 00000000..35447744 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Recipient.java @@ -0,0 +1,115 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +@XmlAccessorType(XmlAccessType.FIELD) +public class Recipient extends Representation { + + private String firstName; + private String middleName; + private String lastName; + @XmlElement(name = "digipostAddress") + private String digipostAddress; + @XmlElement(name = "address") + private final List
      addresses; + + public Recipient(final String firstName, final String middleName, final String lastName, final String digipostAddress, + final List
      addresses, final Link... links) { + super(links); + this.firstName = firstName; + this.middleName = middleName; + this.lastName = lastName; + this.digipostAddress = digipostAddress; + this.addresses = addresses; + } + + Recipient() { + addresses = new ArrayList
      (); + } + + public String getFirstName() { + return firstName; + } + + public String getMiddleName() { + return middleName; + } + + public String getLastName() { + return lastName; + } + + public String getDigipostAddress() { + return digipostAddress; + } + + public List
      getAddresses() { + return addresses; + } + + public static class Builder { + private final String firstName; + private final String middleName; + private final String lastName; + private final String digipostAddress; + private final List
      addresses; + private final List links; + + public Builder(final String firstName, final String middleName, final String lastName, final String digipostAddress) { + this.lastName = lastName; + this.middleName = middleName; + this.firstName = firstName; + this.digipostAddress = digipostAddress; + addresses = new ArrayList
      (); + links = new ArrayList(); + } + + public Builder address(final Address address) { + addresses.add(address); + return this; + } + + public Builder link(final Link link) { + links.add(link); + return this; + } + + public Recipient build() { + return new Recipient(firstName, middleName, lastName, digipostAddress, addresses, links.toArray(new Link[links.size()])); + } + } + + public Link getSelfLink() { + return getLinkByRelationName(Relation.SELF); + } + + @XmlElement(name = "link") + protected List getLink() { + return links; + } + + protected void setLink(final List links) { + this.links = links; + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/RecipientIdentifier.java b/src/main/java/no/posten/dpost/api/client/representations/RecipientIdentifier.java new file mode 100644 index 00000000..ef9da78c --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/RecipientIdentifier.java @@ -0,0 +1,30 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +public abstract class RecipientIdentifier { + protected final String identifier; + + public RecipientIdentifier(final String identifier) { + this.identifier = identifier; + } + + public String asString() { + return identifier; + } + + public abstract boolean isPersonalIdentificationNumber(); +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Recipients.java b/src/main/java/no/posten/dpost/api/client/representations/Recipients.java new file mode 100644 index 00000000..473768b3 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Recipients.java @@ -0,0 +1,64 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import static no.posten.dpost.api.client.representations.Relation.SELF; + +import java.util.LinkedList; +import java.util.List; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; +import javax.xml.bind.annotation.XmlRootElement; + +@XmlAccessorType(XmlAccessType.FIELD) +@XmlRootElement +public class Recipients extends Representation { + + @XmlElement(name = "recipient") + private final List recipients; + + public Recipients(final Link... links) { + super(links); + recipients = new LinkedList(); + } + + public Recipients() { + recipients = new LinkedList(); + } + + public List getRecipients() { + return recipients; + } + + public Link getSelfUri() { + return getLinkByRelationName(SELF); + } + + public void add(final Recipient recipient) { + recipients.add(recipient); + } + + @XmlElement(name = "link") + protected List getLink() { + return links; + } + + protected void setLink(final List links) { + this.links = links; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Relation.java b/src/main/java/no/posten/dpost/api/client/representations/Relation.java new file mode 100644 index 00000000..d2f61aef --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Relation.java @@ -0,0 +1,26 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +public enum Relation { + SELF, + ADD_CONTENT, + SEARCH, + AUTOCOMPLETE, + CREATE_MESSAGE, + GET_EXISTING_MESSAGE, + API_DOCUMENTATION +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Representation.java b/src/main/java/no/posten/dpost/api/client/representations/Representation.java new file mode 100644 index 00000000..df8f8852 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Representation.java @@ -0,0 +1,46 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +public abstract class Representation { + + protected List links; + + public Representation(final Link... linker) { + links = new ArrayList(Arrays.asList(linker)); + } + + Representation() { + links = new ArrayList(); + } + + public void addLink(final Link link) { + links.add(link); + } + + protected Link getLinkByRelationName(final Relation relation) { + for (Link l : links) { + if (l.equalsRelation(relation)) { + return l; + } + } + return null; + } +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/Suggestion.java b/src/main/java/no/posten/dpost/api/client/representations/Suggestion.java new file mode 100644 index 00000000..871b42f6 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/Suggestion.java @@ -0,0 +1,70 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import javax.xml.bind.annotation.XmlAccessType; +import javax.xml.bind.annotation.XmlAccessorType; +import javax.xml.bind.annotation.XmlElement; + +import org.apache.commons.lang.builder.EqualsBuilder; +import org.apache.commons.lang.builder.HashCodeBuilder; +import org.apache.commons.lang.builder.ToStringBuilder; + +@XmlAccessorType(XmlAccessType.FIELD) +public class Suggestion { + private String searchString; + @XmlElement(name = "link") + private Link searchLink; + + public Suggestion(final String searchString, final Link searchLink) { + this.searchString = searchString; + this.searchLink = searchLink; + } + + Suggestion() { + } + + public String getSearchString() { + return searchString; + } + + public Link getSearchLink() { + return searchLink; + } + + @Override + public int hashCode() { + return new HashCodeBuilder(31, 1).append(searchLink).append(searchString).toHashCode(); + } + + @Override + public boolean equals(final Object obj) { + if (this == obj) + return true; + if (obj == null) + return false; + if (getClass() != obj.getClass()) + return false; + Suggestion other = (Suggestion) obj; + return new EqualsBuilder().append(searchLink, other.searchLink).append(searchString, other.searchString).isEquals(); + } + + @Override + public String toString() { + return ToStringBuilder.reflectionToString(this); + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/representations/package-info.java b/src/main/java/no/posten/dpost/api/client/representations/package-info.java new file mode 100644 index 00000000..dca07a81 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/representations/package-info.java @@ -0,0 +1,20 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +@javax.xml.bind.annotation.XmlSchema( + namespace = "http://api.digipost.no/schema/v1", + elementFormDefault = javax.xml.bind.annotation.XmlNsForm.QUALIFIED) +package no.posten.dpost.api.client.representations; + diff --git a/src/main/java/no/posten/dpost/api/client/security/ClientRequestToSign.java b/src/main/java/no/posten/dpost/api/client/security/ClientRequestToSign.java new file mode 100644 index 00000000..f220f4e2 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/security/ClientRequestToSign.java @@ -0,0 +1,61 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.security; + +import java.util.SortedMap; +import java.util.TreeMap; + +import javax.ws.rs.core.MultivaluedMap; + + +import com.sun.jersey.api.client.ClientRequest; + +public class ClientRequestToSign implements RequestToSign { + + private final ClientRequest clientRequest; + + public ClientRequestToSign(final ClientRequest clientRequest) { + this.clientRequest = clientRequest; + } + + @Override + public String getMethod() { + return clientRequest.getMethod(); + } + + @Override + public SortedMap getHeaders() { + TreeMap sortedHeaders = new TreeMap(); + MultivaluedMap headers = clientRequest.getHeaders(); + for (String key : headers.keySet()) { + sortedHeaders.put(key, ClientRequest.getHeaderValue(headers.getFirst(key))); + } + return sortedHeaders; + } + + @Override + public String getPath() { + String path = clientRequest.getURI().getRawPath(); + return path != null ? path : ""; + } + + @Override + public String getParameters() { + String query = clientRequest.getURI().getRawQuery(); + return query != null ? query : ""; + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/security/CryptoUtil.java b/src/main/java/no/posten/dpost/api/client/security/CryptoUtil.java new file mode 100644 index 00000000..f260cc25 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/security/CryptoUtil.java @@ -0,0 +1,52 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.security; + +import java.io.InputStream; +import java.security.KeyStore; +import java.security.PrivateKey; +import java.security.Signature; +import java.security.interfaces.RSAPrivateCrtKey; + +public class CryptoUtil { + public static PrivateKey loadKeyFromP12(final InputStream certificateStream, final String passord) { + RSAPrivateCrtKey key; + try { + KeyStore keyStore = KeyStore.getInstance("PKCS12"); + keyStore.load(certificateStream, passord.toCharArray()); + String onlyKeyAlias = keyStore.aliases().nextElement(); + key = (RSAPrivateCrtKey) keyStore.getKey(onlyKeyAlias, passord.toCharArray()); + } catch (Exception e) { + throw new RuntimeException("Det skjedde en feil ved lasting av nøkkelen", e); + } + if (key == null) { + throw new RuntimeException("Nøkkelen som ble lastet, var null"); + } + return key; + } + + public static byte[] sign(final PrivateKey privateKey, final String messageToSign) { + Signature instance; + try { + instance = Signature.getInstance("SHA256WithRSAEncryption"); + instance.initSign(privateKey); + instance.update(messageToSign.getBytes()); + return instance.sign(); + } catch (Exception e) { + throw new RuntimeException("Det skjedde en feil ved signeringen", e); + } + } +} diff --git a/src/main/java/no/posten/dpost/api/client/security/FileKeystoreSigner.java b/src/main/java/no/posten/dpost/api/client/security/FileKeystoreSigner.java new file mode 100644 index 00000000..61568d38 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/security/FileKeystoreSigner.java @@ -0,0 +1,35 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.security; + +import java.io.InputStream; +import java.security.PrivateKey; + + +public class FileKeystoreSigner implements Signer { + + private final PrivateKey privateKey; + + public FileKeystoreSigner(final InputStream certificate, final String password) { + privateKey = CryptoUtil.loadKeyFromP12(certificate, password); + } + + @Override + public byte[] sign(final String dataToSign) { + return CryptoUtil.sign(privateKey, dataToSign); + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/security/MessageSignatureUtil.java b/src/main/java/no/posten/dpost/api/client/security/MessageSignatureUtil.java new file mode 100644 index 00000000..cdb79c1a --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/security/MessageSignatureUtil.java @@ -0,0 +1,69 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.security; + +import static no.posten.dpost.api.client.Headers.Content_MD5; +import static no.posten.dpost.api.client.Headers.Date; +import static no.posten.dpost.api.client.Headers.X_Digipost_UserId; + +import java.util.Arrays; +import java.util.List; +import java.util.Map.Entry; +import java.util.SortedMap; + +public class MessageSignatureUtil { + + private static final List HEADERS_FOR_SIGNATURE = Arrays.asList(Content_MD5.toLowerCase(), Date.toLowerCase(), + X_Digipost_UserId.toLowerCase()); + + public static String getCanonicalRequestRepresentation(final RequestToSign request) { + StringBuilder s = new StringBuilder(); + s.append(getCanonicalMethodRepresentation(request)); + s.append(getCanonicalUrlRepresentation(request)); + s.append(getCanonicalHeaderRepresentation(request)); + s.append(getCanonicalParameterRepresentation(request)); + return s.toString(); + } + + private static String getCanonicalMethodRepresentation(final RequestToSign request) { + return request.getMethod().toUpperCase() + "\n"; + } + + private static String getCanonicalUrlRepresentation(final RequestToSign request) { + return request.getPath().toLowerCase() + "\n"; + } + + private static String getCanonicalHeaderRepresentation(final RequestToSign request) { + SortedMap headers = request.getHeaders(); + StringBuilder headersString = new StringBuilder(); + for (Entry entry : headers.entrySet()) { + String key = entry.getKey(); + if (isHeaderForSignature(key)) { + headersString.append(key.toLowerCase() + ": " + entry.getValue() + "\n"); + } + } + return headersString.toString(); + } + + private static String getCanonicalParameterRepresentation(final RequestToSign request) { + return request.getParameters().toLowerCase() + "\n"; + } + + private static boolean isHeaderForSignature(final String key) { + return HEADERS_FOR_SIGNATURE.contains(key.toLowerCase()); + } + +} diff --git a/src/main/java/no/posten/dpost/api/client/security/RequestToSign.java b/src/main/java/no/posten/dpost/api/client/security/RequestToSign.java new file mode 100644 index 00000000..7d4b6cec --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/security/RequestToSign.java @@ -0,0 +1,30 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.security; + +import java.util.SortedMap; + +public interface RequestToSign { + + String getMethod(); + + SortedMap getHeaders(); + + String getPath(); + + String getParameters(); + +} diff --git a/src/main/java/no/posten/dpost/api/client/security/Signer.java b/src/main/java/no/posten/dpost/api/client/security/Signer.java new file mode 100644 index 00000000..18f4acbb --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/security/Signer.java @@ -0,0 +1,22 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.security; + +public interface Signer { + + public byte[] sign(String dataToSign); + +} diff --git a/src/main/java/no/posten/dpost/api/client/swing/DigipostSwingClient.java b/src/main/java/no/posten/dpost/api/client/swing/DigipostSwingClient.java new file mode 100644 index 00000000..50db18c8 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/swing/DigipostSwingClient.java @@ -0,0 +1,488 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.swing; + +import static java.lang.String.valueOf; +import static java.lang.System.currentTimeMillis; +import static no.posten.dpost.api.client.representations.AuthenticationLevel.PASSWORD; + +import java.awt.BorderLayout; +import java.awt.CardLayout; +import java.awt.Component; +import java.awt.EventQueue; +import java.awt.Font; +import java.awt.GridBagConstraints; +import java.awt.GridBagLayout; +import java.awt.Insets; +import java.awt.event.ActionEvent; +import java.awt.event.ActionListener; +import java.io.File; +import java.io.IOException; +import java.security.cert.CertificateException; +import java.security.cert.X509Certificate; + +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.HttpsURLConnection; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import javax.net.ssl.TrustManager; +import javax.net.ssl.X509TrustManager; +import javax.swing.Box; +import javax.swing.JButton; +import javax.swing.JFileChooser; +import javax.swing.JFrame; +import javax.swing.JLabel; +import javax.swing.JPanel; +import javax.swing.JPasswordField; +import javax.swing.JScrollPane; +import javax.swing.JTextArea; +import javax.swing.JTextField; +import javax.swing.WindowConstants; +import javax.swing.border.EmptyBorder; + +import no.posten.dpost.api.client.DigipostClient; +import no.posten.dpost.api.client.DigipostClientException; +import no.posten.dpost.api.client.EventLogger; +import no.posten.dpost.api.client.representations.DigipostAddress; +import no.posten.dpost.api.client.representations.Message; + +import org.apache.commons.io.FileUtils; + +public class DigipostSwingClient { + + private static final String BREV = "BREV"; + private static final String CERT = "CERT"; + private JFrame frmDigipostApiClient; + private JTextField certField; + private JPasswordField passwordField; + private JTextField senderField; + private JTextField subjectField; + private JTextField recipientField; + private JTextField contentField; + private JTextArea logTextArea; + + private DigipostClient client; + private final EventLogger eventLogger = new EventLogger() { + + @Override + public void log(final String logMesssage) { + logTextArea.append(logMesssage + "\n"); + } + }; + private JTextField endpointField; + + /** + * Launch the application. + */ + public static void main(final String[] args) { + EventQueue.invokeLater(new Runnable() { + @Override + public void run() { + try { + DigipostSwingClient window = new DigipostSwingClient(); + window.frmDigipostApiClient.setVisible(true); + } catch (Exception e) { + e.printStackTrace(); + } + } + }); + } + + /** + * Create the application. + */ + public DigipostSwingClient() { + initialize(); + } + + /** + * Initialize the contents of the frame. + */ + private void initialize() { + frmDigipostApiClient = new JFrame(); + frmDigipostApiClient.setTitle("Digipost API Client"); + frmDigipostApiClient.setSize(768, 576); + frmDigipostApiClient.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE); + frmDigipostApiClient.setLocationRelativeTo(null); // Sentrerer vinduet + final JPanel contentPane = new JPanel(); + contentPane.setLayout(new CardLayout(0, 0)); + + final JPanel brevPanel = new JPanel(); + brevPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); + + contentPane.add(brevPanel, BREV); + brevPanel.setLayout(new BorderLayout(0, 0)); + + JPanel brevTopPanel = new JPanel(); + brevTopPanel.setBorder(new EmptyBorder(0, 0, 20, 0)); + brevPanel.add(brevTopPanel, BorderLayout.NORTH); + brevTopPanel.setLayout(new BorderLayout(0, 0)); + + JPanel brevHelpPanel = new JPanel(); + brevHelpPanel.setBorder(new EmptyBorder(0, 0, 20, 0)); + brevTopPanel.add(brevHelpPanel, BorderLayout.NORTH); + brevHelpPanel.setLayout(new BorderLayout(0, 0)); + + JLabel steg2Label = new JLabel("Steg 2: Lag og send brev."); + steg2Label.setFont(new Font("Dialog", Font.BOLD, 16)); + brevHelpPanel.add(steg2Label, BorderLayout.NORTH); + + JLabel steg2SubLabel = new JLabel( + "
      Her spesifiserer du selve forsendelsen du ønsker å sende.

      Fra dette eksempel-GUI-et kan du kun sende " + + "til en persons Digipost-adresse, men dersom du bruker API-et, kan du også sende til en persons fødselsnummer. " + + "Les mer i dokumentasjonen."); + brevHelpPanel.add(steg2SubLabel, BorderLayout.SOUTH); + + JPanel brevMainPanel = new JPanel(); + brevTopPanel.add(brevMainPanel, BorderLayout.SOUTH); + GridBagLayout gbl_brevMainPanel = new GridBagLayout(); + gbl_brevMainPanel.columnWidths = new int[] { 0, 0, 0, 0 }; + gbl_brevMainPanel.rowHeights = new int[] { 0, 0, 0, 0, 0, 0 }; + gbl_brevMainPanel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE }; + gbl_brevMainPanel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE }; + brevMainPanel.setLayout(gbl_brevMainPanel); + + JLabel emneLabel = new JLabel("Brev-emne"); + GridBagConstraints gbc_emneLabel = new GridBagConstraints(); + gbc_emneLabel.anchor = GridBagConstraints.EAST; + gbc_emneLabel.insets = new Insets(0, 0, 5, 5); + gbc_emneLabel.gridx = 0; + gbc_emneLabel.gridy = 0; + brevMainPanel.add(emneLabel, gbc_emneLabel); + + subjectField = new JTextField(); + GridBagConstraints gbc_emneField = new GridBagConstraints(); + gbc_emneField.insets = new Insets(0, 0, 5, 5); + gbc_emneField.fill = GridBagConstraints.HORIZONTAL; + gbc_emneField.gridx = 1; + gbc_emneField.gridy = 0; + brevMainPanel.add(subjectField, gbc_emneField); + subjectField.setColumns(10); + + JLabel mottakerLabel = new JLabel("Mottakers digipostadresse"); + GridBagConstraints gbc_mottakerLabel = new GridBagConstraints(); + gbc_mottakerLabel.anchor = GridBagConstraints.EAST; + gbc_mottakerLabel.insets = new Insets(0, 0, 5, 5); + gbc_mottakerLabel.gridx = 0; + gbc_mottakerLabel.gridy = 1; + brevMainPanel.add(mottakerLabel, gbc_mottakerLabel); + + recipientField = new JTextField(); + GridBagConstraints gbc_mottakerField = new GridBagConstraints(); + gbc_mottakerField.insets = new Insets(0, 0, 5, 5); + gbc_mottakerField.fill = GridBagConstraints.HORIZONTAL; + gbc_mottakerField.gridx = 1; + gbc_mottakerField.gridy = 1; + brevMainPanel.add(recipientField, gbc_mottakerField); + recipientField.setColumns(10); + + JLabel innholdLabel = new JLabel("Brevets innhold (pdf)"); + GridBagConstraints gbc_innholdLabel = new GridBagConstraints(); + gbc_innholdLabel.anchor = GridBagConstraints.EAST; + gbc_innholdLabel.insets = new Insets(0, 0, 5, 5); + gbc_innholdLabel.gridx = 0; + gbc_innholdLabel.gridy = 2; + brevMainPanel.add(innholdLabel, gbc_innholdLabel); + + contentField = new JTextField(); + GridBagConstraints gbc_innholdField = new GridBagConstraints(); + gbc_innholdField.insets = new Insets(0, 0, 5, 5); + gbc_innholdField.fill = GridBagConstraints.HORIZONTAL; + gbc_innholdField.gridx = 1; + gbc_innholdField.gridy = 2; + brevMainPanel.add(contentField, gbc_innholdField); + contentField.setColumns(10); + + JButton velgInnholdButton = new JButton("Velg..."); + velgInnholdButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent e) { + JFileChooser filChooser = new JFileChooser(); + filChooser.showOpenDialog(brevPanel); + File filFile = filChooser.getSelectedFile(); + if (filFile != null) { + contentField.setText(filFile.toString()); + } + } + }); + GridBagConstraints gbc_chooseContentButton = new GridBagConstraints(); + gbc_chooseContentButton.anchor = GridBagConstraints.WEST; + gbc_chooseContentButton.insets = new Insets(0, 0, 5, 0); + gbc_chooseContentButton.gridx = 2; + gbc_chooseContentButton.gridy = 2; + brevMainPanel.add(velgInnholdButton, gbc_chooseContentButton); + + JButton sendButton = new JButton("Send brev"); + sendButton.setFont(new Font("Dialog", Font.BOLD, 14)); + sendButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent e) { + try { + Message message = createMessage(subjectField.getText(), recipientField.getText()); + client.sendMessage(message, FileUtils.openInputStream(new File(contentField.getText()))); + } catch (IOException ex) { + eventLogger.log(ex.getMessage() + "\n"); + } catch (DigipostClientException ex) { + eventLogger.log("\nDigipostClient kastet exception. \nFeilkode: " + ex.getErrorType() + "\nFeilmelding: " + + ex.getErrorMessage()); + } + } + }); + + Component verticalStrut_1 = Box.createVerticalStrut(20); + GridBagConstraints gbc_verticalStrut_1 = new GridBagConstraints(); + gbc_verticalStrut_1.insets = new Insets(0, 0, 5, 0); + gbc_verticalStrut_1.gridx = 2; + gbc_verticalStrut_1.gridy = 3; + brevMainPanel.add(verticalStrut_1, gbc_verticalStrut_1); + + JButton btnBack = new JButton("Tilbake"); + btnBack.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent e) { + CardLayout layout = (CardLayout) contentPane.getLayout(); + layout.show(contentPane, CERT); + } + }); + GridBagConstraints gbc_btnBack = new GridBagConstraints(); + gbc_btnBack.anchor = GridBagConstraints.EAST; + gbc_btnBack.insets = new Insets(0, 0, 0, 5); + gbc_btnBack.gridx = 1; + gbc_btnBack.gridy = 4; + brevMainPanel.add(btnBack, gbc_btnBack); + GridBagConstraints gbc_sendButton = new GridBagConstraints(); + gbc_sendButton.gridx = 2; + gbc_sendButton.gridy = 4; + brevMainPanel.add(sendButton, gbc_sendButton); + + JPanel logPanel = new JPanel(); + brevPanel.add(logPanel, BorderLayout.CENTER); + logPanel.setLayout(new BorderLayout(0, 0)); + + JScrollPane logScroll = new JScrollPane(); + logPanel.add(logScroll); + + logTextArea = new JTextArea(); + logTextArea.setLineWrap(true); + logTextArea.setWrapStyleWord(true); + logTextArea.setEditable(false); + logScroll.setViewportView(logTextArea); + frmDigipostApiClient.setContentPane(contentPane); + + CardLayout layout = (CardLayout) contentPane.getLayout(); + layout.show(contentPane, CERT); + + final JPanel velgCertPanel = new JPanel(); + velgCertPanel.setBorder(new EmptyBorder(10, 10, 10, 10)); + contentPane.add(velgCertPanel, CERT); + velgCertPanel.setLayout(new BorderLayout(0, 0)); + + JPanel helpPanel = new JPanel(); + helpPanel.setBorder(new EmptyBorder(0, 0, 20, 0)); + velgCertPanel.add(helpPanel, BorderLayout.NORTH); + helpPanel.setLayout(new BorderLayout(0, 0)); + + JLabel steg1Label = new JLabel("Steg 1: Velg Sertifikat"); + steg1Label.setFont(new Font("Dialog", Font.BOLD, 16)); + helpPanel.add(steg1Label); + + JLabel steg1SubLabel = new JLabel( + "
      Før du kan sende brev, må du laste inn sertifikatet som er knyttet til din virksomhets Digipost-konto." + + " Dette må være på .p12-formatet.

      Hvis dette er et Buypass-sertifikat, og du enda ikke har lastet " + + "det opp til Digipost, kan du gjøre dette på " + + "https://www.digipost.no/virksomhet. Les mer om dette i dokumentasjonen."); + helpPanel.add(steg1SubLabel, BorderLayout.SOUTH); + + JPanel certPanel = new JPanel(); + velgCertPanel.add(certPanel, BorderLayout.CENTER); + GridBagLayout gbl_certPanel = new GridBagLayout(); + gbl_certPanel.columnWidths = new int[] { 0, 0, 0, 0 }; + gbl_certPanel.rowHeights = new int[] { 0, 0, 0, 0, 0, 0, 0 }; + gbl_certPanel.columnWeights = new double[] { 0.0, 1.0, 0.0, Double.MIN_VALUE }; + gbl_certPanel.rowWeights = new double[] { 0.0, 0.0, 0.0, 0.0, 0.0, 0.0, Double.MIN_VALUE }; + certPanel.setLayout(gbl_certPanel); + + JLabel certLabel = new JLabel("Sertifikatfil (.p12)"); + GridBagConstraints gbc_certLabel = new GridBagConstraints(); + gbc_certLabel.anchor = GridBagConstraints.EAST; + gbc_certLabel.insets = new Insets(0, 0, 5, 5); + gbc_certLabel.gridx = 0; + gbc_certLabel.gridy = 0; + certPanel.add(certLabel, gbc_certLabel); + + certField = new JTextField(); + GridBagConstraints gbc_certField = new GridBagConstraints(); + gbc_certField.insets = new Insets(0, 0, 5, 5); + gbc_certField.fill = GridBagConstraints.HORIZONTAL; + gbc_certField.gridx = 1; + gbc_certField.gridy = 0; + certPanel.add(certField, gbc_certField); + certField.setColumns(10); + + JButton certButton = new JButton("Velg..."); + certButton.addActionListener(new ActionListener() { + @Override + public void actionPerformed(final ActionEvent e) { + JFileChooser filChooser = new JFileChooser(); + filChooser.showOpenDialog(brevPanel); + File filFile = filChooser.getSelectedFile(); + if (filFile != null) { + certField.setText(filFile.toString()); + } + } + }); + GridBagConstraints gbc_certButton = new GridBagConstraints(); + gbc_certButton.insets = new Insets(0, 0, 5, 0); + gbc_certButton.gridx = 2; + gbc_certButton.gridy = 0; + certPanel.add(certButton, gbc_certButton); + + JLabel passordLabel = new JLabel("Sertifikatpassord"); + GridBagConstraints gbc_passordLabel = new GridBagConstraints(); + gbc_passordLabel.anchor = GridBagConstraints.EAST; + gbc_passordLabel.insets = new Insets(0, 0, 5, 5); + gbc_passordLabel.gridx = 0; + gbc_passordLabel.gridy = 1; + certPanel.add(passordLabel, gbc_passordLabel); + + passwordField = new JPasswordField(); + GridBagConstraints gbc_passordField = new GridBagConstraints(); + gbc_passordField.insets = new Insets(0, 0, 5, 5); + gbc_passordField.fill = GridBagConstraints.HORIZONTAL; + gbc_passordField.gridx = 1; + gbc_passordField.gridy = 1; + certPanel.add(passwordField, gbc_passordField); + passwordField.setColumns(10); + + JLabel avsenderLabel = new JLabel("Avsenders ID"); + GridBagConstraints gbc_avsenderLabel = new GridBagConstraints(); + gbc_avsenderLabel.anchor = GridBagConstraints.EAST; + gbc_avsenderLabel.insets = new Insets(0, 0, 5, 5); + gbc_avsenderLabel.gridx = 0; + gbc_avsenderLabel.gridy = 2; + certPanel.add(avsenderLabel, gbc_avsenderLabel); + + senderField = new JTextField(); + GridBagConstraints gbc_avsenderField = new GridBagConstraints(); + gbc_avsenderField.insets = new Insets(0, 0, 5, 5); + gbc_avsenderField.fill = GridBagConstraints.HORIZONTAL; + gbc_avsenderField.gridx = 1; + gbc_avsenderField.gridy = 2; + certPanel.add(senderField, gbc_avsenderField); + senderField.setColumns(10); + + JLabel endpointLabel = new JLabel("API-endpoint URL"); + GridBagConstraints gbc_endpointLabel = new GridBagConstraints(); + gbc_endpointLabel.anchor = GridBagConstraints.EAST; + gbc_endpointLabel.insets = new Insets(0, 0, 5, 5); + gbc_endpointLabel.gridx = 0; + gbc_endpointLabel.gridy = 3; + certPanel.add(endpointLabel, gbc_endpointLabel); + + endpointField = new JTextField("https://api.digipost.no"); + GridBagConstraints gbc_endpointField = new GridBagConstraints(); + gbc_endpointField.insets = new Insets(0, 0, 5, 5); + gbc_endpointField.fill = GridBagConstraints.HORIZONTAL; + gbc_endpointField.gridx = 1; + gbc_endpointField.gridy = 3; + certPanel.add(endpointField, gbc_endpointField); + endpointField.setColumns(10); + + JButton nesteButton = new JButton("Neste"); + nesteButton.addActionListener(new ActionListener() { + + @Override + public void actionPerformed(final ActionEvent e) { + CardLayout layout = (CardLayout) contentPane.getLayout(); + layout.show(contentPane, BREV); + + turnOffEndpointSslValidationIfWeAreTargetingDigipostTestEnvironment(endpointField.getText()); + + try { + client = new DigipostClient(endpointField.getText(), Long.parseLong(senderField.getText()), FileUtils + .openInputStream(new File(certField.getText())), new String(passwordField.getPassword()), eventLogger); + } catch (NumberFormatException e1) { + eventLogger.log("FEIL: Avsenders ID må være et tall > 0"); + } catch (IOException e1) { + eventLogger.log("FEIL: Klarte ikke å lese sertifikatfil:\n" + e1); + } catch (Exception e1) { + eventLogger.log("FEIL: Kunne ikke initialisere Digipost-API-klienten. Dette kan f.eks skyldes at" + + " sertifikatfilen var ugyldig, eller at du skrev inn feil passord. Feilmelding var:\n" + e1.getMessage()); + } + } + }); + + Component verticalStrut = Box.createVerticalStrut(20); + GridBagConstraints gbc_verticalStrut = new GridBagConstraints(); + gbc_verticalStrut.insets = new Insets(0, 0, 5, 0); + gbc_verticalStrut.gridx = 2; + gbc_verticalStrut.gridy = 4; + certPanel.add(verticalStrut, gbc_verticalStrut); + GridBagConstraints gbc_nesteButton = new GridBagConstraints(); + gbc_nesteButton.gridx = 2; + gbc_nesteButton.gridy = 5; + certPanel.add(nesteButton, gbc_nesteButton); + + CardLayout l = (CardLayout) contentPane.getLayout(); + l.show(contentPane, CERT); + } + + private Message createMessage(final String subject, final String address) { + return new Message(valueOf(currentTimeMillis()), subject, new DigipostAddress(address), false, PASSWORD); + } + + /** + * Dersom vi tester mot et av Digiposts testmiljøer, vil vi ikke bruke + * SSL-validering. + */ + private void turnOffEndpointSslValidationIfWeAreTargetingDigipostTestEnvironment(final String endpoint) { + if (endpoint.contains("camelon")) { + eventLogger.log("Detekterte at vi går mot Digipost Testmiljø. Skrur derfor av SSL-sjekk"); + try { + TrustManager[] noopTrustManager = new TrustManager[] { new X509TrustManager() { + @Override + public java.security.cert.X509Certificate[] getAcceptedIssuers() { + return null; + } + + @Override + public void checkClientTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { + } + + @Override + public void checkServerTrusted(final X509Certificate[] chain, final String authType) throws CertificateException { + } + } }; + SSLContext sc = SSLContext.getInstance("SSL"); + sc.init(null, noopTrustManager, new java.security.SecureRandom()); + HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory()); + HostnameVerifier noopHostnameVerifier = new HostnameVerifier() { + @Override + public boolean verify(final String hostname, final SSLSession session) { + return true; + } + }; + HttpsURLConnection.setDefaultHostnameVerifier(noopHostnameVerifier); + } catch (Exception e) { + eventLogger.log("Klarte ikke å skru av SSL-sjekk."); + throw new RuntimeException(e); + } + } + } +} diff --git a/src/main/java/no/posten/dpost/api/client/util/JerseyClientProvider.java b/src/main/java/no/posten/dpost/api/client/util/JerseyClientProvider.java new file mode 100644 index 00000000..0e86d164 --- /dev/null +++ b/src/main/java/no/posten/dpost/api/client/util/JerseyClientProvider.java @@ -0,0 +1,64 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.util; + +import org.apache.commons.httpclient.HostConfiguration; +import org.apache.commons.httpclient.HttpClient; +import org.apache.commons.httpclient.HttpConnectionManager; +import org.apache.commons.httpclient.MultiThreadedHttpConnectionManager; +import org.apache.commons.httpclient.params.HttpConnectionManagerParams; + +import com.sun.jersey.api.client.Client; +import com.sun.jersey.api.client.config.ClientConfig; +import com.sun.jersey.client.apache.ApacheHttpClient; +import com.sun.jersey.client.apache.ApacheHttpClientHandler; +import com.sun.jersey.client.apache.config.ApacheHttpClientConfig; +import com.sun.jersey.client.apache.config.DefaultApacheHttpClientConfig; + +public class JerseyClientProvider { + private static ApacheHttpClient client; + + static { + ApacheHttpClientHandler clientHandler = new ApacheHttpClientHandler(opprettMultiThreadedHttpClient(), opprettClientConfig()); + client = new ApacheHttpClient(clientHandler); + } + + private static final int MAX_HTTP_CONNECTIONS = 100; + + private static final Integer THREADPOOL_SIZE = 100; + private static final Integer CONNECTION_TIMEOUT = 5000; + + public static Client getClient() { + return client; + } + + private static HttpClient opprettMultiThreadedHttpClient() { + HttpConnectionManager httpConnectionManager = new MultiThreadedHttpConnectionManager(); + HttpConnectionManagerParams params = new HttpConnectionManagerParams(); + params.setMaxTotalConnections(MAX_HTTP_CONNECTIONS); + params.setMaxConnectionsPerHost(HostConfiguration.ANY_HOST_CONFIGURATION, MAX_HTTP_CONNECTIONS); + httpConnectionManager.setParams(params); + return new HttpClient(httpConnectionManager); + } + + private static ClientConfig opprettClientConfig() { + DefaultApacheHttpClientConfig config = new DefaultApacheHttpClientConfig(); + config.getProperties().put(ApacheHttpClientConfig.PROPERTY_THREADPOOL_SIZE, THREADPOOL_SIZE); + config.getProperties().put(ApacheHttpClientConfig.PROPERTY_CONNECT_TIMEOUT, CONNECTION_TIMEOUT); + config.getProperties().put(ApacheHttpClientConfig.PROPERTY_READ_TIMEOUT, CONNECTION_TIMEOUT); + return config; + } +} diff --git a/src/main/resources/cert.p12 b/src/main/resources/cert.p12 new file mode 100644 index 00000000..7ad9c91e Binary files /dev/null and b/src/main/resources/cert.p12 differ diff --git a/src/main/resources/header.txt b/src/main/resources/header.txt new file mode 100644 index 00000000..cccf60b3 --- /dev/null +++ b/src/main/resources/header.txt @@ -0,0 +1,13 @@ +Copyright (C) Posten Norge AS + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. \ No newline at end of file diff --git a/src/main/resources/posten.pdf b/src/main/resources/posten.pdf new file mode 100644 index 00000000..720b938a Binary files /dev/null and b/src/main/resources/posten.pdf differ diff --git a/src/main/scala/no/posten/dpost/api/client/cmd/DigipostCmdClient.scala b/src/main/scala/no/posten/dpost/api/client/cmd/DigipostCmdClient.scala new file mode 100644 index 00000000..26b49649 --- /dev/null +++ b/src/main/scala/no/posten/dpost/api/client/cmd/DigipostCmdClient.scala @@ -0,0 +1,91 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.cmd +import no.posten.dpost.api.client.DigipostClient +import no.posten.dpost.api.client.representations.Recipient +import no.posten.dpost.api.client.DigipostClientException +import java.io.File +import scala.io.Source +import java.io.FileInputStream +import com.sun.jersey.api.client.filter.LoggingFilter +import no.posten.dpost.api.client.representations.Message +import no.posten.dpost.api.client.representations.DigipostAddress +import no.posten.dpost.api.client.representations.PersonalIdentificationNumber +import no.posten.dpost.api.client.representations.AuthenticationLevel.PASSWORD + +object DigipostCmdClient extends App { + val config = loadConfig() + val options = parseOptions(args.toList) + + val messageFiles = options("brev").split(',') + val certStream = new FileInputStream(new File(config("sertifikat"))) + val client = new DigipostClient(config("endpoint"), config("brukerid").toLong, certStream, config("sertifikatpassord")) + if (options.contains("debug")) client.addFilter(new LoggingFilter()) + + try { + val buildMessage = getMessageBuilder(options.keys.toList) + messageFiles.foreach((brev: String) => { + val brevStream = new FileInputStream(new File(brev)) + val response = client.sendMessage(buildMessage(System.currentTimeMillis().toString(), options("emne")), brevStream) + brevStream.close() + }) + } catch { + case ex: DigipostClientException => println(ex.getErrorMessage()) + case ex2 => println(ex2) + } + + def messageWithPersonalIdentificationNumber(messageId: String, subject: String, personalIdentificationNumber: PersonalIdentificationNumber): Message = { + new Message(messageId, subject, personalIdentificationNumber, false, PASSWORD) + } + + def getMessageBuilder(keys: List[String]): (String, String) => Message = keys match { + case "digipostadresse" :: tail => (messageId: String, subject: String) => + new Message(messageId, subject, new DigipostAddress(options("digipostadresse")), false, PASSWORD) + case "fødselsnummer" :: tail => (messageId: String, subject: String) => + new Message(messageId, subject, new PersonalIdentificationNumber(options("fødselsnummer")), false, PASSWORD) + case other :: tail => getMessageBuilder(tail) + case Nil => + println("Ingen mottaker spesifisert") + exit(1) + } + + def loadConfig(): Map[String, String] = { + val configFile = "./bin/config.properties" + val ConfigLine = """^(.*?)=(.*)$""".r + Source.fromFile(configFile).getLines().map { + case ConfigLine(key, value) => Map(key -> value) + case _ => Map() + }.flatten.toMap + } + + def parseOptions(args: List[String]): Map[String, String] = { + val usage = """Usage: dpost-api-cmd [--debug] [--digipostadresse] [--fødselsnummer] emne brevfil[,brevfil,brevfil,...]""" + if (args.length == 0) println(usage) + + def nextOption(list: List[String]): Map[String, String] = list match { + case Nil => Map() + case "--digipostadresse" :: value :: tail => Map("digipostadresse" -> value) ++ nextOption(tail) + case "--fødselsnummer" :: value :: tail => Map("fødselsnummer" -> value) ++ nextOption(tail) + case "--debug" :: tail => Map("debug" -> "true") ++ nextOption(tail) + case emne :: brev :: Nil => Map("emne" -> emne, "brev" -> brev) + case option :: tail => + println("Ugyldig parameter " + option) + println(usage) + exit(1) + } + nextOption(args) + } +} diff --git a/src/test/java/no/posten/dpost/api/client/BrevSenderTest.java b/src/test/java/no/posten/dpost/api/client/BrevSenderTest.java new file mode 100644 index 00000000..093ef1fd --- /dev/null +++ b/src/test/java/no/posten/dpost/api/client/BrevSenderTest.java @@ -0,0 +1,127 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Matchers.any; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.verify; +import static org.mockito.Mockito.when; + +import java.net.URI; +import java.net.URISyntaxException; + +import no.posten.dpost.api.client.DigipostClientException.ErrorType; +import no.posten.dpost.api.client.representations.AuthenticationLevel; +import no.posten.dpost.api.client.representations.Message; +import no.posten.dpost.api.client.representations.MessageStatus; +import no.posten.dpost.api.client.representations.PersonalIdentificationNumber; + +import org.junit.Before; +import org.junit.Test; + +import com.sun.jersey.api.client.ClientHandlerException; +import com.sun.jersey.api.client.ClientResponse; +import com.sun.jersey.api.client.ClientResponse.Status; +import com.sun.jersey.api.client.UniformInterfaceException; + +public class BrevSenderTest { + + @Before + public void setUp() { + } + + @Test + public void skalHenteEksisterendeForsendelseHvisDenFinnesFraForr() { + ApiService api = mock(ApiService.class); + Message forsendelseIn = lagDefaultForsendelse(); + when(api.createMessage(forsendelseIn)).thenReturn(new MockClientResponse(Status.CONFLICT)); + + Message eksisterendeForsendelse = lagDefaultForsendelse(); + eksisterendeForsendelse.setStatus(MessageStatus.EXPECTING_CONTENT); + when(api.fetchExistingMessage((URI) any())).thenReturn(new MockClientResponse(Status.OK, eksisterendeForsendelse)); + + MessageSender brevSender = new MessageSender(api, DigipostClient.NOOP_EVENT_LOGGER); + Message forsendelse = brevSender.createOrFetchMessage(forsendelseIn); + + verify(api).fetchExistingMessage((URI) any()); + assertTrue(forsendelse.isIdenticalTo(forsendelseIn)); + } + + @Test + public void skalKasteFeilHvisForsendelseAlleredeLevert() { + ApiService api = mock(ApiService.class); + Message forsendelseIn = lagDefaultForsendelse(); + when(api.createMessage(forsendelseIn)).thenReturn(new MockClientResponse(Status.CONFLICT)); + + Message eksisterendeForsendelse = lagDefaultForsendelse(); + eksisterendeForsendelse.setStatus(MessageStatus.DELIVERED); + when(api.fetchExistingMessage((URI) any())).thenReturn(new MockClientResponse(Status.OK, eksisterendeForsendelse)); + + MessageSender brevSender = new MessageSender(api, DigipostClient.NOOP_EVENT_LOGGER); + + try { + brevSender.createOrFetchMessage(forsendelseIn); + } catch (Exception e) { + assertTrue(e instanceof DigipostClientException); + DigipostClientException de = (DigipostClientException) e; + assertEquals(ErrorType.MESSAGE_DELIVERED, de.getErrorType()); + } + + } + + private Message lagDefaultForsendelse() { + return lagEnkeltForsendelse("emne", "id", "12345678900"); + } + + private Message lagEnkeltForsendelse(final String subject, final String messageId, final String fnr) { + return new Message(messageId, subject, new PersonalIdentificationNumber(fnr), true, AuthenticationLevel.PASSWORD); + } + + private class MockClientResponse extends ClientResponse { + + private final Message eksisterendeForsendelse; + + public MockClientResponse(final Status responseStatus) { + super(responseStatus.getStatusCode(), null, null, null); + eksisterendeForsendelse = null; + } + + public MockClientResponse(final Status responseStatus, final Message eksisterendeForsendelse) { + super(responseStatus.getStatusCode(), null, null, null); + this.eksisterendeForsendelse = eksisterendeForsendelse; + } + + @SuppressWarnings("unchecked") + @Override + public T getEntity(final Class c) throws ClientHandlerException, UniformInterfaceException { + return (T) eksisterendeForsendelse; + } + + @Override + public URI getLocation() { + try { + return new URI("http://localhost/forsendelse/2"); + } catch (URISyntaxException e) { + e.printStackTrace(); + return null; + } + } + + } + +} diff --git a/src/test/java/no/posten/dpost/api/client/representations/XsdValidationTest.java b/src/test/java/no/posten/dpost/api/client/representations/XsdValidationTest.java new file mode 100644 index 00000000..8efa7fb9 --- /dev/null +++ b/src/test/java/no/posten/dpost/api/client/representations/XsdValidationTest.java @@ -0,0 +1,67 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.client.representations; + +import java.util.ArrayList; +import java.util.List; + +import javax.xml.XMLConstants; +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; +import javax.xml.validation.Schema; +import javax.xml.validation.SchemaFactory; + +import org.junit.Before; +import org.junit.Test; +import org.xml.sax.SAXException; +import org.xml.sax.helpers.DefaultHandler; + +public class XsdValidationTest { + + private Marshaller marshaller; + + @Before + public void setUp() throws SAXException, JAXBException { + SchemaFactory schemaFactory = SchemaFactory.newInstance(XMLConstants.W3C_XML_SCHEMA_NS_URI); + Schema schema = schemaFactory.newSchema(getClass().getResource("/xsd/api/api_v1.xsd")); + marshaller = JAXBContext.newInstance("no.posten.dpost.api.client.representations").createMarshaller(); + marshaller.setSchema(schema); + } + + @Test + public void validateAll() throws JAXBException { + Link link = new Link(Relation.SELF, new DigipostUri("http://localhost/self"), MediaTypes.DIGIPOST_MEDIA_TYPE_V1); + Recipients recipients = new Recipients(); + Address address = new Address("Streetn", "houseNumber", "houseLetter", "additionalAddressLine", "zipCode", "city"); + ArrayList
      addresses = new ArrayList
      (); + addresses.add(address); + Recipient recipient = new Recipient("Even", "Emmil", "Beinlaus", "even.beinlaus#1234", addresses, link); + recipients.add(recipient); + EntryPoint entryPoint = new EntryPoint(link); + + marshallAndValidate(entryPoint); + marshallAndValidate(recipients); + marshallAndValidate(new ErrorMessage("Error message", link)); + List suggestions = new ArrayList(); + suggestions.add(new Suggestion("even", link)); + marshallAndValidate(new Autocomplete(suggestions, link)); + } + + public void marshallAndValidate(final Object element) throws JAXBException { + marshaller.marshal(element, new DefaultHandler()); + } +} \ No newline at end of file diff --git a/src/test/java/no/posten/dpost/api/eksempelkode/AutocompleteEksempel.java b/src/test/java/no/posten/dpost/api/eksempelkode/AutocompleteEksempel.java new file mode 100644 index 00000000..a9bd924b --- /dev/null +++ b/src/test/java/no/posten/dpost/api/eksempelkode/AutocompleteEksempel.java @@ -0,0 +1,68 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.eksempelkode; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import no.posten.dpost.api.client.DigipostClient; +import no.posten.dpost.api.client.representations.Suggestion; + +import org.apache.commons.io.FileUtils; + +/** + * Kode som brukes i dokumentasjonen for klientbiblioteket. + * + */ +@SuppressWarnings("unused") +public class AutocompleteEksempel { + // Din virksomhets Digipost-kontoid + private static final long AVSENDERS_KONTOID = 10987; + + // Passordet sertifikatfilen er beskyttet med + private static final String SERTIFIKAT_PASSORD = "SertifikatPassord123"; + + public static void main(final String[] args) { + + // 1. Vi leser inn sertifikatet du har knyttet til din Digipost-konto (i + // .p12-formatet) + InputStream sertifikatInputStream = lesInnSertifikat(); + + // 2. Vi oppretter en DigipostClient + DigipostClient client = new DigipostClient("https://api.digipost.no", AVSENDERS_KONTOID, sertifikatInputStream, SERTIFIKAT_PASSORD); + + // 3. Vi ber om forslag til autofullføring + List suggestions = client.getAutocompleteSuggestions("Gunn").getSuggestions(); + + } + + private static InputStream getMessageContent() { + // Her må du returnere brevinnholdet du ønsker å sende istedenfor null + return null; + } + + private static InputStream lesInnSertifikat() { + try { + // Leser inn sertifikatet selv med Apache Commons FileUtils. + return FileUtils.openInputStream(new File("/path/til/sertifikatfil.p12")); + } catch (IOException e) { + // Håndter at sertifikatet ikke kunne leses! + throw new RuntimeException("Kunne ikke lese sertifikatfil"); + } + } +} diff --git a/src/test/java/no/posten/dpost/api/eksempelkode/ForsendelseEksempel.java b/src/test/java/no/posten/dpost/api/eksempelkode/ForsendelseEksempel.java new file mode 100644 index 00000000..5234e768 --- /dev/null +++ b/src/test/java/no/posten/dpost/api/eksempelkode/ForsendelseEksempel.java @@ -0,0 +1,77 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.eksempelkode; + +import static no.posten.dpost.api.client.representations.AuthenticationLevel.PASSWORD; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import no.posten.dpost.api.client.DigipostClient; +import no.posten.dpost.api.client.representations.Message; +import no.posten.dpost.api.client.representations.PersonalIdentificationNumber; + +import org.apache.commons.io.FileUtils; + +/** + * Kode som brukes i dokumentasjonen for klientbiblioteket. + * + */ +public class ForsendelseEksempel { + // Din virksomhets Digipost-kontoid + private static final long AVSENDERS_KONTOID = 10987; + + // Passordet sertifikatfilen er beskyttet med + private static final String SERTIFIKAT_PASSORD = "SertifikatPassord123"; + + public static void main(final String[] args) { + + // 1. Vi leser inn sertifikatet du har knyttet til din Digipost-konto (i + // .p12-formatet) + InputStream sertifikatInputStream = lesInnSertifikat(); + + // 2. Vi oppretter en DigipostClient + DigipostClient client = new DigipostClient("https://api.digipost.no", AVSENDERS_KONTOID, sertifikatInputStream, SERTIFIKAT_PASSORD); + + // 3. Vi oppretter et fødselsnummerobjekt + PersonalIdentificationNumber pin = new PersonalIdentificationNumber("26079833787"); + + // 4. Vi oppretter en forsendelse + Message message = new Message("dinForsendelseId", "Brevets emne", pin, false, PASSWORD); + + // 5. Vi henter inputstreamen til PDF-filen vi ønsker å sende + InputStream messageContent = getMessageContent(); + + // 6. Vi lar klientbiblioteket håndtere utsendelsen + client.sendMessage(message, messageContent); + } + + private static InputStream getMessageContent() { + // Her må du returnere brevinnholdet du ønsker å sende istedenfor null + return null; + } + + private static InputStream lesInnSertifikat() { + try { + // Leser inn sertifikatet selv med Apache Commons FileUtils. + return FileUtils.openInputStream(new File("/path/til/sertifikatfil.p12")); + } catch (IOException e) { + // Håndter at sertifikatet ikke kunne leses! + throw new RuntimeException("Kunne ikke lese sertifikatfil"); + } + } +} diff --git a/src/test/java/no/posten/dpost/api/eksempelkode/ForsendelseEksempelDigipostadresse.java b/src/test/java/no/posten/dpost/api/eksempelkode/ForsendelseEksempelDigipostadresse.java new file mode 100644 index 00000000..c43f472a --- /dev/null +++ b/src/test/java/no/posten/dpost/api/eksempelkode/ForsendelseEksempelDigipostadresse.java @@ -0,0 +1,77 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.eksempelkode; + +import static no.posten.dpost.api.client.representations.AuthenticationLevel.PASSWORD; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; + +import no.posten.dpost.api.client.DigipostClient; +import no.posten.dpost.api.client.representations.DigipostAddress; +import no.posten.dpost.api.client.representations.Message; + +import org.apache.commons.io.FileUtils; + +/** + * Kode som brukes i dokumentasjonen for klientbiblioteket. + * + */ +public class ForsendelseEksempelDigipostadresse { + // Din virksomhets Digipost-kontoid + private static final long AVSENDERS_KONTOID = 10987; + + // Passordet sertifikatfilen er beskyttet med + private static final String SERTIFIKAT_PASSORD = "SertifikatPassord123"; + + public static void main(final String[] args) { + + // 1. Vi leser inn sertifikatet du har knyttet til din Digipost-konto (i + // .p12-formatet) + InputStream sertifikatInputStream = lesInnSertifikat(); + + // 2. Vi oppretter en DigipostClient + DigipostClient client = new DigipostClient("https://api.digipost.no", AVSENDERS_KONTOID, sertifikatInputStream, SERTIFIKAT_PASSORD); + + // 3. Vi oppretter et digipostadresseobjekt + DigipostAddress address = new DigipostAddress("fornavn.etternavn#6789"); + + // 4. Vi oppretter en forsendelse + Message message = new Message("dinForsendelseId", "Brevets emne", address, false, PASSWORD); + + // 5. Vi henter inputstreamen til PDF-filen vi ønsker å sende + InputStream messageContent = getMessageContent(); + + // 6. Vi lar klientbiblioteket håndtere utsendelsen + client.sendMessage(message, messageContent); + } + + private static InputStream getMessageContent() { + // Her må du returnere brevinnholdet du ønsker å sende istedenfor null + return null; + } + + private static InputStream lesInnSertifikat() { + try { + // Leser inn sertifikatet selv med Apache Commons FileUtils. + return FileUtils.openInputStream(new File("/path/til/sertifikatfil.p12")); + } catch (IOException e) { + // Håndter at sertifikatet ikke kunne leses! + throw new RuntimeException("Kunne ikke lese sertifikatfil"); + } + } +} diff --git a/src/test/java/no/posten/dpost/api/eksempelkode/SokEksempel.java b/src/test/java/no/posten/dpost/api/eksempelkode/SokEksempel.java new file mode 100644 index 00000000..c4b7d123 --- /dev/null +++ b/src/test/java/no/posten/dpost/api/eksempelkode/SokEksempel.java @@ -0,0 +1,68 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.eksempelkode; + +import java.io.File; +import java.io.IOException; +import java.io.InputStream; +import java.util.List; + +import no.posten.dpost.api.client.DigipostClient; +import no.posten.dpost.api.client.representations.Recipient; + +import org.apache.commons.io.FileUtils; + +/** + * Kode som brukes i dokumentasjonen for klientbiblioteket. + * + */ +@SuppressWarnings("unused") +public class SokEksempel { + // Din virksomhets Digipost-kontoid + private static final long AVSENDERS_KONTOID = 10987; + + // Passordet sertifikatfilen er beskyttet med + private static final String SERTIFIKAT_PASSORD = "SertifikatPassord123"; + + public static void main(final String[] args) { + + // 1. Vi leser inn sertifikatet du har knyttet til din Digipost-konto (i + // .p12-formatet) + InputStream sertifikatInputStream = lesInnSertifikat(); + + // 2. Vi oppretter en DigipostClient + DigipostClient client = new DigipostClient("https://api.digipost.no", AVSENDERS_KONTOID, sertifikatInputStream, SERTIFIKAT_PASSORD); + + // 3. Vi søker etter personer med matchende navn eller adresse + List recipients = client.search("Ole Nilsen Stavanger").getRecipients(); + + } + + private static InputStream getMessageContent() { + // Her må du returnere brevinnholdet du ønsker å sende istedenfor null + return null; + } + + private static InputStream lesInnSertifikat() { + try { + // Leser inn sertifikatet selv med Apache Commons FileUtils. + return FileUtils.openInputStream(new File("/path/til/sertifikatfil.p12")); + } catch (IOException e) { + // Håndter at sertifikatet ikke kunne leses! + throw new RuntimeException("Kunne ikke lese sertifikatfil"); + } + } +} diff --git a/src/test/java/no/posten/dpost/api/representations/ForsendelseRepresentasjonTest.java b/src/test/java/no/posten/dpost/api/representations/ForsendelseRepresentasjonTest.java new file mode 100644 index 00000000..460ba0b1 --- /dev/null +++ b/src/test/java/no/posten/dpost/api/representations/ForsendelseRepresentasjonTest.java @@ -0,0 +1,41 @@ +/** + * Copyright (C) Posten Norge AS + * + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package no.posten.dpost.api.representations; + +import static no.posten.dpost.api.client.representations.AuthenticationLevel.PASSWORD; +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import no.posten.dpost.api.client.representations.DigipostAddress; +import no.posten.dpost.api.client.representations.Message; + +import org.junit.Test; + +public class ForsendelseRepresentasjonTest { + + @Test + public void skalHanteraDuplikatForsendelse() { + DigipostAddress digipostAddress = new DigipostAddress("peter.pan#0000"); + Message adresseForsendelse1 = new Message("id", "emne", digipostAddress, false, PASSWORD); + Message adresseForsendelse3 = new Message("id", "annetemne", digipostAddress, false, PASSWORD); + + assertTrue(adresseForsendelse1.isIdenticalTo(adresseForsendelse1)); + assertTrue(adresseForsendelse3.isIdenticalTo(adresseForsendelse3)); + + assertFalse(adresseForsendelse1.isIdenticalTo(adresseForsendelse3)); + } + +}